一个很基础的GUI小程序,但GUI上多了一个假Button

图片

如图所示是结果,代码如下:

package SimpleGui3;
import javax.swing.*;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;

public class SimpleGui3 {    
    public static void main(String[] args) {
        MyFrame gui = new MyFrame();
    }
}

class MyFrame extends JFrame implements ActionListener {
    JButton button;
    MyDrawPanel draw_panel;
    
    public MyFrame() {    
        this.setVisible(true);
        this.setSize(300, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        
        button = new JButton("click to change colors");
        button.addActionListener(this);
        this.getContentPane().add(BorderLayout.SOUTH,button);
        
        draw_panel = new MyDrawPanel();
        this.getContentPane().add(BorderLayout.CENTER,draw_panel);
        
    }
    
    public void actionPerformed(ActionEvent event) {
        this.repaint();
    }
}
//无关紧要的部分↓
class MyDrawPanel extends JPanel {
    public void paintComponent(Graphics g) {
        int[] color_array = new int[3];
        for(int i=0;i<color_array.length;i++) {
            color_array[i] = (int)(Math.random() * 255);
        }
        Color c = new Color(color_array[0],color_array[1],color_array[2]);
        g.setColor(c);
        g.fillRect(20, 50, 100, 100);
    }
}

点击一下位于SOUTH的按钮,上面那个假的(那个也点不了)就自然而然消失了,程序也正常运行,方块的颜色也变了一个...但就刚运行的时候会有上下两个,为什么会有这种情况呢?谢谢

阅读 2.1k
1 个回答

估计与重绘有关, 且与操作系统平台相关, 在我的机器上并没有你说的现象.
你可以试试把setVisible置后

public MyFrame() {    
        
        this.setSize(300, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        
        button = new JButton("click to change colors");
        button.addActionListener(this);
        this.getContentPane().add(BorderLayout.SOUTH,button);
        
        draw_panel = new MyDrawPanel();
        this.getContentPane().add(BorderLayout.CENTER,draw_panel);
        this.setVisible(true); //放在这里试试
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题