简体   繁体   中英

Changing JLabel's text from a different tab

I can't seem to change a JLabel's text from another tab.

For example: Tab 1 has:

    JLabel headerLbl = new JLabel("Original Title");
    headerLbl.setSize(275, 40);
    headerLbl.setLocation(75, 10);
    headerLbl.setFont(new Font("Serif", Font.PLAIN, 28));
    headerLbl.setForeground(Color.BLUE);
    firstPanel.add(headerLbl);

Then Tab 2 would be an options tab where you can change the text of headerLbl. My code so far is:

private void initializeOptionsTab()
  {
    JPanel optionsPanel = new JPanel();
    optionsPanel.setLayout(null);

    JLabel headerLbl = new JLabel("Change Name To:");
    headerLbl.setSize(150, 25);
    headerLbl.setLocation(150, 15);
    optionsPanel.add(headerLbl);

    this.compTxtFld = new JTextField();
    this.compTxtFld.setSize(200, 20);
    this.compTxtFld.setLocation(120, 45);
    optionsPanel.add(this.compTxtFld);

    JButton setNewNameButton = new JButton("Set New Name");
    setNewNameButton.setSize(130, 25);
    setNewNameButton.setLocation(150, 85);
    optionsPanel.add(setNewNameButton);


    setNewNameButton.addActionListener(new ActionListener() 
    { 
        public void actionPerformed(ActionEvent e) 
        { 
            FrameMain.this.setNewNameButtonClick(); 
        }

    });
    this.tabbedPane.addTab("Options", optionsPanel);
  }

Then the code for the Button is:

private void setNewNameButtonClick()
  {
    setTitle(this.compTxtFld.getText());

    headerLbl.setText(this.compTxtFld.getText());
  }

So this gives me a Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException for lines

My guess is I cannot access the headerLbl in tab 1 from tab 2. What do I need to do to access it?

First of all it's a bad idea to have 2 labels both named headerLbl even though they are in different methods because it can cause confusion as you are coding.

The easiest solution I can think of is to declare headerLbl as a class variable

So like this:

public class FrameMain{
     JLabel headerLbl = new JLabel();
   //The rest is the same

}

and then inside your second method, change the name of headerLbl to something like changeNameLbl or something... so they don't conflict

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM