当我尝试使用 paint(Graphics g) 代码时出现错误。您能否帮助解决代码,以便有一个带有 3d 矩形的窗口。谢谢!
private static void paint(Graphics g){
g.draw3DRect(10, 10, 50, 50, true);
然后向底部:
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
paint();
}
});
}
}
最佳答案
在Java中,重写时不能降低方法的可见性。同样,实例方法不能成为static
。必须是
@Override
public void paint(Graphics g){
super.paint(g);
g.draw3DRect(10, 10, 50, 50, true);
}
在 Swing 中,不要在顶级窗口(例如 JFrame
)中进行自定义绘制。
而是创建 JComponent
的子类并覆盖 paintComponent
并确保调用 super.paintComponent(g)
。
class MyComponent extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.draw3DRect(10, 10, 50, 50, true);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
}
不要忘记将新组件的实例添加到 JFrame
:
frame.add(new MyComponent());
关于java - Jpanel 和图形错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16795371/