【发布时间】:2013-07-12 15:49:22
【问题描述】:
当我运行这个程序时,我看到的只是一个空白的 JFrame。我不知道为什么paintComponent 方法不起作用。这是我的代码:
package com.drawing;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyPaint extends JPanel {
private void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(panel);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillRect(50, 50, 100, 100);
}
public static void main(String[] args) {
My paintTester = new MyPaint();
paintTester.go();
}
}
【问题讨论】:
-
在
go()中使用this而不是panel -
另外,为什么不将 JFrame 和 JPanel 放在两个不同的类中?
-
只是一个建议,而不是在
JFrame上设置大小,最好覆盖getPreferredSize(),就像你覆盖paintComponent()方法并调用frame.pack()一样
标签: java eclipse swing drawing awt