[英]Changing JLabel's text from a different tab
我似乎无法从另一个选项卡更改JLabel的文本。
例如:选项卡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);
然后选项卡2将是一个选项选项卡,您可以在其中更改headerLbl的文本。 到目前为止,我的代码是:
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);
}
然后,按钮的代码为:
private void setNewNameButtonClick()
{
setTitle(this.compTxtFld.getText());
headerLbl.setText(this.compTxtFld.getText());
}
因此,这在行“ AWT-EventQueue-0” java.lang.NullPointerException中给了我一个异常
我的猜测是我无法从选项卡2中访问选项卡1中的headerLbl。我需要做什么才能访问它?
首先,尽管两个标签都使用不同的方法,但是两个标签都命名为headerLbl是一个坏主意,因为这会在您编码时引起混乱。
我能想到的最简单的解决方案是将headerLbl声明为类变量
像这样:
public class FrameMain{
JLabel headerLbl = new JLabel();
//The rest is the same
}
然后在您的第二个方法中,将headerLbl的名称更改为诸如changeNameLbl之类的名称或其他名称,以便它们不冲突
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.