[英]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.