[英]How to change CardLayout panels from a separate panel?
我的軟件布局有點像向導基礎。 因此,基礎面板分為兩個JPanel
。 左側面板永不改變。 還有一個與CardLayout
一起使用的右面板。 它具有許多子面板,並通過一種方法顯示每個子面板。
我可以輕松地從一個內面板轉到另一個內面板。 但是我想在左側面板中有一個按鈕,並在右側面板中進行更改。
這是一個示例代碼,您可以運行它:
基礎:
public class Base {
JFrame frame = new JFrame("Panel");
BorderLayout bl = new BorderLayout();
public Base(){
frame.setLayout(bl);
frame.setSize(800, 600);
frame.add(new LeftBar(), BorderLayout.WEST);
frame.add(new MainPanel(), BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
new Base();
}
}
左邊
public class LeftBar extends JPanel{
JButton button;
MainPanel mainPanel = new MainPanel();
public LeftBar(){
setPreferredSize(new Dimension(200, 40));
setLayout(new BorderLayout());
setBackground(Color.black);
button = new JButton("Show Second Page");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
mainPanel.showPanel("secondPage");
}
});
add(button, BorderLayout.NORTH);
}
}
右邊
public class MainPanel extends JPanel {
private CardLayout cl = new CardLayout();
private JPanel panelHolder = new JPanel(cl);
public MainPanel(){
FirstPage firstPage = new FirstPage(this);
SecondPage secondPage = new SecondPage(this);
setLayout(new GridLayout(0,1));
panelHolder.add(firstPage, "firstPage");
panelHolder.add(secondPage, "secondPage");
cl.show(panelHolder, "firstPage");
add(panelHolder);
}
public void showPanel(String panelIdentifier){
cl.show(panelHolder, panelIdentifier);
}
}
右側內面板:
public class FirstPage extends JPanel {
MainPanel mainPanel;
JButton button;
public FirstPage(MainPanel mainPanel) {
this.mainPanel = mainPanel;
setBackground(Color.GRAY);
button = new JButton("Show page");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
mainPanel.showPanel("secondPage");
}
});
add(button);
}
}
public class SecondPage extends JPanel{
MainPanel mainPanel;
JButton button;
public SecondPage(MainPanel mainPanel){
this.mainPanel = mainPanel;
setBackground(Color.white);
add(new JLabel("This is second page"));
}
}
這是給您這個想法的圖片:
正如我所解釋的,可以使用以下方法將“從第一頁”移動到“第二頁” : mainPanel.showPanel("secondPage");
或mainPanel.showPanel("firstPage");
。
但是我在左側欄中還有一個JButton
,我調用了相同的方法來顯示CardLayout的第二個面板。 但這行不通。 它沒有給出任何錯誤。
知道如何從面板外部更改這些CardLayout
面板嗎?
問題在於LeftBar
具有mainPanel
成員,該成員已初始化為MainPanel
的新實例。 所以,你有兩個實例MainPanel
,在一個分配的Base
,並添加到幀,另一個在分配LeftBar
。
因此, LeftBar
執行mainPanel.showPanel("secondPage");
LeftBar
在MainPanel
的第二個實例上,該實例甚至不屬於可視層次結構。 要解決此問題,只需將MainPanel
的現有實例MainPanel
給MainPanel
的構造LeftBar
。 您已經在FirstPage
和SecondPage
執行了此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.