[英]Drawing on JPanel that is in a JFrame
It's been a long time since I did any drawing programs in Java and I can't get this one to work. 自从我用Java编写了任何绘图程序以来,已经很长时间了,我无法使这个程序正常工作。 The window stays empty even though there should be a filled oval there.
即使在那里应该有一个填充的椭圆形窗口也将保持空白。 Before the code was throwing a NullPonterException in the draw() function.
在代码之前,在draw()函数中抛出NullPonterException。
public class Map extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private Graphics graphics;
public static void main(String[] args) {
Map frame = new Map();
}
public Map() {
setTitle("Bugs");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 600);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel drawingPanel = new JPanel();
contentPane.add(drawingPanel, BorderLayout.CENTER);
this.setVisible(true);
graphics = drawingPanel.getGraphics();
draw(graphics);
}
public void draw(Graphics g){
Bug b = new Bug();
g.setColor(Color.RED);
g.fillOval(b.getPosX(), b.getPosY(), b.getRadius(), b.getRadius());
}
}
It is not enough to call draw(...)
only one time. 仅调用一次
draw(...)
是不够的。 This way the drawn content is lost immediately after your component is redrawn. 这样,在重新绘制组件后,绘制的内容立即丢失。
The correct approach would be as follows: 正确的方法如下:
public class BugPanel extends JPanel {
private Bug bug;
public BugPanel(Bug b) {
bug = b;
}
@Override
public void paint(Graphics g) {
// draw your bug here
}
}
Then add this panel to the center region of your frame. 然后将此面板添加到框架的中心区域。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.