簡體   English   中英

如何基於先前選擇的JButton更改JPanel的內容?

[英]How do you change contents of a JPanel based on a previously selected JButton?

我正在為社區創建界面。 選項包括“添加人”,“添加到家庭”和“從家庭中刪除成員”。 我認為制作多個JPanels非常耗時,因此我使JPanel依賴於用戶的“選擇”。 例如,

if(choice == 1)
 {
        addPTitle = new JLabel("ADD PERSON");
        addPTitle.setHorizontalAlignment(SwingConstants.CENTER);
        addPTitle.setBounds(75,20,350,50);
        addPTitle.setFont(calibri);
        addPTitle.setForeground(red);
    }
    else if(choice == 2)
    {
        addPTitle = new JLabel("ADD TO FAMILY");
        addPTitle.setHorizontalAlignment(SwingConstants.CENTER);
        addPTitle.setBounds(75,20,350,50);
        addPTitle.setFont(calibri);
        addPTitle.setForeground(red);
    }
    else if(choice == 3)
    {
        addPTitle = new JLabel("REMOVE MEMBER");
        addPTitle.setHorizontalAlignment(SwingConstants.CENTER);
        addPTitle.setBounds(75,20,350,50);
        addPTitle.setFont(calibri);
        addPTitle.setForeground(red);
    }

當我手動更改選擇值時,它工作正常,但是當我嘗試為按鈕本身添加ActionListener ,選擇值沒有更改,並且所顯示的JPanel內容仍然基於我手動設置的值。 這是我的ActionListener代碼:

private class ButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == "ADD PERSON")
        {
            choice = 1;
            frame.setContentPane(addP);
            frame.invalidate();
            frame.validate();
        }
        else if(e.getSource() == "ADD TO FAMILY"){
            choice = 2;
            frame.setContentPane(addP);
            frame.invalidate();
            frame.validate();
        }
        else if(e.getSource() == "REMOVE MEMBER FROM FAMILY"){
            choice = 3;
            frame.setContentPane(addP);
            frame.invalidate();
            frame.validate();
        }

e.getSource()返回一個對象。 您正在嘗試將其與字符串進行比較。 相反,您可以使用e.getActionCommand() (假設您尚未更改action命令)

同樣,如果您很想動手,請勿將字符串與==進行比較。 使用equals

if ("ADD PERSON".equals(e.getActionCommand()) {}

或者,如果您的按鈕作用域在ActionListener可訪問,則可以比較該對象,

if (e.getSource() == addPersonButton) {}

另一種選擇,如果您有任何理由沒有改變動作命令,你也可以使用該按鈕的文字比較

JButton button = (JButton)e.getSource();
String text = button.getText();
if ("ADD PERSON".equals(text)) {}

邊注

您應該重新驗證面板。

使用Jpanel.revalidate()。

暫無
暫無

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

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