简体   繁体   English

从其他选项卡更改JLabel的文本

[英]Changing JLabel's text from a different tab

I can't seem to change a JLabel's text from another tab. 我似乎无法从另一个选项卡更改JLabel的文本。

For example: Tab 1 has: 例如:选项卡1具有:

    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. 然后选项卡2将是一个选项选项卡,您可以在其中更改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 因此,这在行“ AWT-EventQueue-0” java.lang.NullPointerException中给了我一个异常

My guess is I cannot access the headerLbl in tab 1 from tab 2. What do I need to do to access it? 我的猜测是我无法从选项卡2中访问选项卡1中的headerLbl。我需要做什么才能访问它?

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. 首先,尽管两个标签都使用不同的方法,但是两个标签都命名为headerLbl是一个坏主意,因为这会在您编码时引起混乱。

The easiest solution I can think of is to declare headerLbl as a class variable 我能想到的最简单的解决方案是将headerLbl声明为类变量

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 然后在您的第二个方法中,将headerLbl的名称更改为诸如changeNameLbl之类的名称或其他名称,以便它们不冲突

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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