尝试使用事件处理程序注册Swing按钮时,为什么会出现错误?

时间:2016-06-01 22:38:22

标签: java swing

我正在尝试创建一个简单的Java Swing应用程序,它允许我简单地将公里数转换为英里数。将按钮注册到事件处理程序时,我收到错误。错误位于textField标识符中。有一条红色的波浪形线在下面突出显示,我不知道为什么它是一个错误。这是代码。非常感激。

import javax.swing.*;
import java.awt.event.*;

public class Graphics
    {
    public static void main(String[] args)
        {
    // Create a window
    JFrame window = new JFrame();
    window.setTitle("Distance Converter");
    window.setSize(550, 450);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);

    // Create a panel
    JPanel panel = new JPanel();

    // Create components
    JLabel message = new JLabel("Enter distance in kilometers");
    JTextField textField = new JTextField(10);
    JButton button = new JButton("Calculate");

    // Add the components to the panel
    panel.add(message);
    panel.add(textField);
    panel.add(button);

    // Add the panel to the window
    window.add(panel);
}

// Add action listener to button
MyButtonListener listener = new MyButtonListener();
button.@addActionListener(listener);


// Register an event listener to the calculate button
private class MyButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        final double converstion = 0.6214;
        String input; // To hold the user's input
        double miles; // To hold the number of miles

        // Get the text entered by the user into the text field
        input = textField.getText();
        // textField is underlined with red: There is an error here.
        // I do not understand why there is an error here.

        // Convert the input to miles
        miles = Double.parseDouble(input) * converstion;

        // Display the result.

        JOptionPane.showMessageDialog(null, input + " kilometers is " + miles + " miles.");

    }
}
}

1 个答案:

答案 0 :(得分:1)

您不能在方法或静态初始化器之外编写语句(方法调用,变量赋值等)。对button.addListener()的调用应该在一个方法中完成,例如main方法。

public static void main(String[] args) {
    ...
    // Add action listener to button
    MyButtonListener listener = new MyButtonListener();
    button.addActionListener(listener);
    ...
}

此外,@符号不应出现在方法调用中的方法名称之前。将来,你应该发布你得到的错误并阅读它,因为它会给你一个关于问题的线索。