簡體   English   中英

Java swing - 重新調整大小時重繪組件(JButtons和JLabel)

[英]Java swing - Repaint is duplicating components (JButtons and JLabels) when re-sized

我有這個奇怪的問題。 我的教授似乎無法復制它,他提供的幫助充其量是最小的。 所以說到這一點。 此代碼在面板上生成JButton並添加到JFrame的內容窗格中:

public myPanel extends JPanel {
    static final long serialVersionUID = 1;
    public myPanel() {
        this.setPreferredSize(new Dimension(600, 40));
    }
    public void paintComponent(Graphics graphicsDrawer) {
        super.paintComponent(graphicsDrawer);
        this.add(new JButton("A Button"));
    }
}

這是GUI代碼

public class myGUI {
    public myGUI() {
    }
    public void showGUI() {
        JFrame frame = new JFrame("Issues!!!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new myPanel());
        frame.pack();
        frame.setVisible(true);
    }
}

然后由該類運行GUI

// It is unnecessary to show here but I made a class that
// implements runnable that creates a myGUI object and calls
// showGUI
public static void main(String[] args) {
    RunnableGUI runGUI = new RunnableGUI();
    javax.swing.SwingUtilities.invokeLater(runGUI);
}

這是我最起碼的代碼。 但是我已經把它隔離了,即使有了必需品,這個問題仍然存在。 下面是我遇到問題的照片。

初始幀帶有1個按鈕

Vertical Re-size創建額外的按鈕

我已經嘗試過所有我能找到並想到的東西。

我認為每次重新調整大小時,框架都會重新繪制按鈕。 但是,由於分配要求,必須能夠重新調整框架的大小。

運行Windows 8 w / JRE 7,8(我將下載6但我不認為這會有所幫助)

永遠不要這樣做:

public void paintComponent(Graphics graphicsDrawer) {
    super.paintComponent(graphicsDrawer);
    this.add(new JButton("A Button"));  // ***** yikes! ****
}

該方法的paintComponent是畫。 您不必在是否或者即使它會被稱為完全控制,並且可以多次調用,這意味着大量的添加按鈕。 此外,您希望避免組件創建代碼或任何減慢繪制方法中的程序流的代碼,因為這些方法部分地決定了GUI的感知響應性,因此您將希望繪制方法( paintpaintComponent )是精簡的,意味着快速

在構造函數或初始化方法中添加按鈕,以便控制調用代碼的頻率。

public myPanel extends JPanel {
    static final long serialVersionUID = 1;
    public myPanel() {

        this.setPreferredSize(new Dimension(600, 40));
        this.add(new JButton("A Button"));
    }
    public void paintComponent(Graphics graphicsDrawer) {
        super.paintComponent(graphicsDrawer);

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM