[英]Drawing with AWT and components in Java
我目前正在使用AWT在Java中进行游戏。 主类扩展了Frame,我一直在使用它通过.getGraphics()和.drawRect()绘制图形。 这样做一直很好,只不过当我在框架中添加标签之类的组件时,它停止渲染图形并仅显示组件。
getGraphics()
进行绘制。 那不是正确的方法。 paintComponent(Graphics g)
方法。 使用此方法进行所有绘画,并使用隐式传递的Graphics上下文。 您无需实际调用 paintComponent
因为它将为您隐式调用。 paintComponent
,你将要覆盖paint
,如AWT组件不具有paintComponent
方法。 但我强烈建议您使用Swing public class SimplePaint {
public SimplePaint() {
JFrame frame = new JFrame();
frame.add(new DrawPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class DrawPanel extends JPanel {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(50, 50, 150, 150);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new SimplePaint();
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.