我在class
中获得了一些JButton
的,JLabel
和JTextField
。 我只是在panel.add()方法中初始化它们,并且我在它们的每一个附近都有一个The value of the field 'nameOfField' is not used
警告。未使用字段'nameOfField'的值 - Java Swing
我的类:
public class GuiClass
{
private JFrame frame;
private JButton button1;
private JButton button2;
private JLabel label;
private JTextField textField;
private JPanel upperPanel;
private JPanel lowerPanel;
public GuiClass()
{
this.frame = new JFrame("Complex layout GUI example");
this.upperPanel = new JPanel();
this.lowerPanel = new JPanel();
this.upperPanel.add(this.label = new JLabel("Enter your password:"));
this.upperPanel.add(this.textField = new JTextField(20)); // Size of the textField
this.lowerPanel.add(this.button1 = new JButton("Cancel"));
this.lowerPanel.add(this.button2 = new JButton("Login"));
this.frame.setLayout(new GridLayout(2,1));
this.frame.add(this.upperPanel);
this.frame.add(this.lowerPanel);
this.frame.pack();
this.frame.setVisible(true);
}
}
警告靠近按钮1,按钮2,标签和文本框。 我使用Eclipse
。什么困扰它?
PS
我可以生成吸气的和setter的,并警告显然走了,但我想从中学习Java编程什么是我的错误(如果有的话)。
谢谢。
由于你从来没有真正使用它们,所以Eclipse看到了''button2''这样的字段是没有必要的。添加可以在没有赋值的情况下完成,所以这不是真正的用法。引入公共getter可以消除警告,因为字段_could_可以通过该getter间接访问,而Eclipse不知道是否是这种情况(您可能正在编写库等)。 – Thomas
其他IDE也有类似的功能。 –
@Thomas好吧,这是一个更快的方式来编写这样的代码。所以....我应该改变它首先初始化变量,然后添加或只是离开它? – God