簡體   English   中英

使用 JComboBox 選擇時 JPanel 不刷新

[英]JPanel not refreshing upon selection with JComboBox

我正在嘗試編寫一個非常短的 class 將 JPanel 與 JComboBox“聯系起來”。 我想我的邏輯是錯誤的,但是當我 select 使用 JComboBox 的一些新東西時沒有任何反應......這是(或多或少)我的代碼:

private DisplayPanel currentDisplay; //a displaypanel is simply an extended JPanel with an id field, and an overriden .equals() method
private JComboBox selector;
private List<DisplayPanel> displays;

public SelectionPanel(DisplayPanel panel){
    displays = new ArrayList<DisplayPanel>();
    selector = new JComboBox(new String[]{panel.id});
    currentDisplay = panel;
    selector.addActionListener(this);
    this.add(selector);
    this.add(currentDisplay);
    this.displays.add(panel);
}

public void addNewSelection(DisplayPanel panel){
    displays.add(panel);
    selector.addItem(panel.id);
}


@Override
public void actionPerformed(ActionEvent e) {
    JComboBox source = (JComboBox) e.getSource();
    String id = (String) source.getSelectedItem();
    for(DisplayPanel display: displays)
        if(id.equals(display.id))
                currentDisplay = display;
    this.validate();        
}

我假設我需要以某種方式覆蓋 repaint() function,但我真的不確定最好的方法。

這是(或多或少)我的代碼:

這對我們沒有幫助,因為我們不知道如何使用代碼的上下文。 為了獲得更好的幫助,請在提問時發布SSCCE

當前顯示 = 顯示;

那行代碼似乎不正確。 它所做的只是改變一個變量的值。 它不會將面板添加到 GUI。 你的基本代碼是:

panel.remove( theOldPanel );
panel.add( theNewPanel );
panel.revalidate();
panel.repaint();

然而,這正是 CardLayout 為您所做的,因此正確的解決方案是遵循 aardvarkk 的建議。

當您將 currentDisplay 添加到 GUI 時,您不會將 currentDisplay變量添加到 GUI,而是將 currentDisplay 變量引用的object添加到 GUI。 因此,稍后當您更改 currentDisplay 變量所指的組件時,這應該不會對 GUI 顯示的組件產生任何影響,因為它仍然包含原始 object。

我支持 aardvarkk 的出色建議,即您使用 CardLayout(1+ 到 aardvarkk)。 如果您這樣做,您會發現它會順利運行(然后您應該接受 Aardvarkk答案作為答案)。

暫無
暫無

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

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