java - Eclipse 中的 Swing GUI

标签 java eclipse swing user-interface

我正在尝试按照 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/

相关文章:

java - Hibernate 表未映射

java - 补间引擎和 libgdx 的故障

java - JFace:Setgrayed 在树查看器中不起作用

c++ - 使用 Eclipse 时如何向我的 C++ 编译可执行文件添加图标?

java - Mac OSX 上 VM 中的 Oracle Database 12c

java - 字符串格式错误

eclipse - .jar 文件与不兼容的 Scala 版本 (2.10) 交叉编译

java - 动画 JDialog

java - 如何使输入到 jTextField 中的任何数字出现在 x 中?

java - 如何知道java中JRadioButton是否启用