gpt4 book ai didi

java - Eclipse 中的 Swing GUI

转载 作者:行者123 更新时间:2023-11-30 07:57:17 24 4
gpt4 key购买 nike

我正在尝试按照 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,错误仍然存​​在 - 所以它绝对不是重要的代码顺序(我认为)。

如果这与名称不正确的组件有关,我会感到惊讶,但这是一个屏幕截图:

enter image description here

非常感谢任何可以就此事提出建议的人!

编辑:感谢那些已经提出修改代码顺序建议的人。然而,它随后告诉我需要将 fahrenheitLabel 设置为最终的,我认为这与用户输入不同输入时动态更改的能力相冲突。

编辑2:显然使变量最终是有效的。感谢大家的建议。

最佳答案

当然它不知道标签,因为你在方法之后声明它。尝试放置

JLabel fahrenheitLabel = new JLabel("华氏度");

之前

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.
});

关于java - Eclipse 中的 Swing GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32502066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com