[英]Drawing with AWT and components in Java
I'm currently making a game in Java with AWT. 我目前正在使用AWT在Java中进行游戏。 The main class extends Frame, and I've been using it to draw the graphics using .getGraphics() and .drawRect().
主类扩展了Frame,我一直在使用它通过.getGraphics()和.drawRect()绘制图形。 This has been working fine, except that when I add components like labels to the frame it stops rendering the graphics and only displays the components.
这样做一直很好,只不过当我在框架中添加标签之类的组件时,它停止渲染图形并仅显示组件。
getGraphics()
to paint. getGraphics()
进行绘制。 That is not the proper way. paintComponent(Graphics g)
method of the JPanel. paintComponent(Graphics g)
方法。 Do all your painting in this method, use the implicitly passed Graphics context. paintComponent
as it will be implicitly called for you. paintComponent
因为它将为您隐式调用。 paintComponent
, you're going to want to override paint
, as AWT components don't have a paintComponent
method. paintComponent
,你将要覆盖paint
,如AWT组件不具有paintComponent
方法。 But I strongly urge you to use 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.