JAVA GUI代码未按预期运行

时间:2018-04-27 12:59:30

标签: java user-interface

我从书中输入了这段代码

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);
}}

结果是: enter image description here

以下是本书的原始代码,我从本书的网站上下载了此代码

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);
  }}

结果是这样的: enter image description here

我一次又一次地检查它以确保它们是相同的,似乎它们是相同的。但为什么GUI不同?

请提前帮助,谢谢。

1 个答案:

答案 0 :(得分:5)

在您自己的代码中,方法名称为painComponent时应为paintComponent

提示:添加@Override以覆盖方法,然后编译器会告诉您这样的错误:

@Override
public void painComponent(Graphics g) {