【发布时间】:2015-09-10 12:34:42
【问题描述】:
我正在尝试按照 Oracle 文档中的指南在 Eclipse 中创建 Swing GUI。但是,他们在教程中使用了 Netbeans,我认为这可能是问题的原因。
我试图创建一个温度转换器,但华氏数的标签一再抱怨它无法解决。以下是源代码:
private JPanel contentPane;
private JTextField tempTextField; // Not sure if I need the other components here as well?
// Could be needed in order to be used in the
// actionPerformed method.
...
JButton convertButton = new JButton("Convert");
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Parse degrees Celsius as a double and convert to Fahrenheit.
int tempFahr = (int)((Double.parseDouble(tempTextField.getText()))
* 1.8 + 32);
fahrenheitLabel.setText(tempFahr + " Fahrenheit"); // fahrenheitLabel is what's
} //highlighted in Eclipse.
});
convertButton.setBounds(6, 38, 134, 29);
contentPane.add(convertButton);
JLabel fahrenheitLabel = new JLabel("Fahrenheit");
fahrenheitLabel.setBounds(152, 43, 78, 16);
contentPane.add(fahrenheitLabel);
Oracle 文档的链接在这里:http://docs.oracle.com/javase/tutorial/uiswing/learn/creatinggui.html
我应该指出,即使 fahrenheitLabel 在方法之前声明,错误仍然存在 - 所以它绝对不是重要的代码顺序(我认为)。
如果它与名称不正确的组件有关,我会感到惊讶,但这是一个屏幕截图:
非常感谢任何可以就此事提出建议的人!
编辑:感谢那些已经提出建议以修改代码顺序的人。但是,它告诉我需要将 fahrenheitLabel 设为 final,我认为这与在用户输入不同输入时动态更改的能力相冲突。
编辑 2:显然使变量 final 是有效的。谢谢大家的建议。
【问题讨论】:
-
即使在 actionPerformed 方法之前声明了 JLabel,你确定它不起作用吗? - 它显然不适用于此代码,因为您在尝试设置它的文本后声明了
fahrenheitLabel。 -
我做到了,但它随后抱怨“无法引用封闭范围内定义的非最终局部变量 fahrenheitLabel”。建议将变量设为 final,但我不确定这是否是意图。
-
如需尽快获得更好的帮助,请发帖minimal reproducible example 或Short, Self Contained, Correct Example。
-
fahrenheitLabel.setBounds(152, 43, 78, 16);Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。 -
我很欣赏 cmets Andrew,但为什么需要将 fahrenheitLabel 声明为 final?
标签: java eclipse swing user-interface