我从书上输入了这段代码
public class SimpleGui3C {
JFrame frame;
public static void main (String[] args) {
SimpleGui3C gui = new SimpleGui3C();
gui.go();
}
public void go() {
frame = new JFrame("My own code");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(420,300);
frame.setVisible(true);
}}
class MyDrawPanel extends JPanel {
public void painComponent(Graphics g) {
g.fillRect(0,0,this.getWidth(), this.getHeight());
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color randomColor = new Color(red, green, blue);
g.setColor(randomColor);
g.fillOval(70,70,100,100);
}}
这是本书的原始代码,我从本书的网站上下载了这段代码
public class SimpleGui3C {
JFrame frame;
public static void main (String[] args) {
SimpleGui3C gui = new SimpleGui3C();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(420,300);
frame.setVisible(true);
}}
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.fillRect(0,0,this.getWidth(), this.getHeight());
// make random colors to fill with
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color randomColor = new Color(red, green, blue);
g.setColor(randomColor);
g.fillOval(70,70,100,100);
}}
我检查了一遍又一遍,确保它们是一样的,看起来它们是一样的。但为什么 GUI 不同?
请帮助,在此先感谢。
最佳答案
在您自己的代码中,方法名称是 painComponent
而它应该是 paintComponent
。
提示:将@Override
添加到重写的方法中,然后编译器会告诉你这样的错误:
@Override
public void painComponent(Graphics g) {
关于JAVA GUI 代码没有按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50062948/