在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/Java/ 一個(gè)很基礎(chǔ)的GUI小程序,但GUI上多了一個(gè)假Button

一個(gè)很基礎(chǔ)的GUI小程序,但GUI上多了一個(gè)假Button

圖片

如圖所示是結(jié)果,代碼如下:

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();
    }
}
//無(wú)關(guān)緊要的部分↓
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);
    }
}

點(diǎn)擊一下位于SOUTH的按鈕,上面那個(gè)假的(那個(gè)也點(diǎn)不了)就自然而然消失了,程序也正常運(yùn)行,方塊的顏色也變了一個(gè)...但就剛運(yùn)行的時(shí)候會(huì)有上下兩個(gè),為什么會(huì)有這種情況呢?謝謝

回答
編輯回答
莫小染

估計(jì)與重繪有關(guān), 且與操作系統(tǒng)平臺(tái)相關(guān), 在我的機(jī)器上并沒(méi)有你說(shuō)的現(xiàn)象.
你可以試試把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); //放在這里試試
    }
2017年7月30日 13:08