2016-06-22 228 views
0

我有2個面板在我的框架中,1是按鈕(我想使用radioButton,但現在它更容易使用按鈕),另一個是卡布局面板。當我按下特定按鈕時,我的計劃是洗牌乍得。像移動按鈕將顯示移動面板卡。移動面板卡具有x0標籤和文本字段,行面板卡具有x0和x1標籤和文本字段。按鈕更改卡片佈局

有2班,1對buttonpanel =按鈕 另一種是爲卡= PanelMiddle 這裏是我的代碼:

public class PanelMiddle{ 
    JPanel controlPanel = new JPanel(); 
    CardLayout cl = new CardLayout(); 

    JPanel movePanel = new JPanel(); 
    JPanel linePanel = new JPanel(); 

    JLabel x0Label = new JLabel("x0"); 
    JTextField x0TextField = new JTextField(3); 
    JLabel x1Label = new JLabel("x1"); 
    JTextField x1TextField = new JTextField(3); 

    public PanelMiddle(){ 
     controlPanel.setLayout(cl); 

     //move panel 
     movePanel.setLayout(new GridLayout (1,2)); 
     movePanel.add(x0Label); 
     movePanel.add(x0TextField); 
     controlPanel.add(movePanel,"Move"); //add the keyword Move to show the move card 

     //line panel 
     linePanel.setLayout(new GridLayout (2,2)); 
     //linePanel.add(x0Label); 
     linePanel.add(x1Label); 
     //linePanel.add(x0TextField); 
     linePanel.add(x1TextField); 
     controlPanel.add(linePanel,"Line"); // add the keyword Line to show the line card 

     } 
    } 

在其他I類有:

public class Buttons extends PanelMiddle{ 
    JPanel buttonPanel = new JPanel(); 

    JButton moveB = new JButton ("Move"); 
    JButton lineB = new JButton ("Line"); 

    public Buttons(){ 
    buttonPanel.setLayout(new GridLayout (2,1)); 
    buttonPanel.add(moveB); 
    buttonPanel.add(lineB); 

    action(); 
    } 

    public void action(){ 
    moveB.addActionListener((e) -> { 
    cl.show(controlPanel,"Move"); 
    }); 

    lineB.addActionListener((e) -> { cl.show(controlPanel,"Line");}); 
    } 
    } 

我得到的結果很奇怪。它沒有完全顯示我的面板。但是當我嘗試評論所有的線條面板時,它就可以工作。有人在這裏修復嗎?

注意:我很抱歉,我不知道如何編輯這裏的文本,所以它有點混亂。

編輯1:如guleryuz說,我註釋掉x0Labelx0TextField從線路板

回答

1

在Swing組件層次結構中的成分只能被添加到一個容器中,要添加x0Label和x0TextField兩人雙雙面板。所以當你添加x0Labe兩個第二個面板(linePanel)時,它將從movePanel中移除(對於x0TextField,也是這種情況),因此movePanel變爲空。

更多詳情here

+0

啊!好的!這是一個問題,但它仍然沒有解決我的按鈕不會改變面板。 –