我试图仅在单击按钮时更改JLabel的值。

这是GUI代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class login extends JFrame implements ActionListener
{
       public login (){

         //Create (Frame, Label, Text input for doctors name & Password field):

       JFrame frame = new JFrame("Doctor Login");
       JLabel label = new JLabel("Login Below:");
       JTextField name = new JTextField(10);
       JPasswordField pass = new JPasswordField(10);
       JButton button = new JButton("Login");

        //Exit program on close:
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       //Label
       label.setPreferredSize(new Dimension(175, 100));
       label.setLocation(100,100);

       //Add Elements to frame:
       frame.setLayout(new FlowLayout());
       frame.getContentPane().add(label);
       frame.getContentPane().add(name);
       frame.getContentPane().add(pass);
       frame.getContentPane().add(button);

       //Create border for text field:
       Border nameBorder = BorderFactory.createLineBorder(Color.BLACK, 1);

       name.setBorder(nameBorder);
       pass.setBorder(nameBorder);

       //Set Size of frame:
       frame.setSize(500, 250);

       //Set Location of the frame on the screen:
       frame.setLocation(200,200);

       //Display
       frame.setVisible(true);


       //Compiler Gives an error here - Illegal Start of Expression
       public void actionEvent(ActionEvent event){
           label.setText("Logged in");
       }
    }

}


主类代码:

import java.util.*;
import java.util.Date;

public class main
{

public static void main(String[] args) {

   login login = new login();

}


}


登录类中的actionEvent方法返回错误的表达式非法开始。

最佳答案

如果仅要将ActionListener添加到按钮,则应删除

implements ActionListener


并做:

button.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        label.setText(...);
    }
});


笔记:


请注意,由于在构造函数中添加了该方法,因此出现了该错误。
您应该遵循Java命名约定,对类使用SomeClass或对变量或方法使用someVariable之类的名称。

关于java - 如何实现ActionListener,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22462581/

10-11 00:07