我在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