我试图在单击按钮时简单地更改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方法返回错误Illegal Start of Expression。
答案 0 :(得分:4)
如果只想将ActionListener
添加到按钮,则应删除
implements ActionListener
并且做:
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
label.setText(...);
}
});
注意:
SomeClass
等名称,对变量或方法使用someVariable
。答案 1 :(得分:2)
您错误地将和错误地命名为actionPerformed方法。现在你将它嵌套在构造函数中,Java不允许将方法嵌套在其他方法或构造函数中(对于不允许嵌套在方法或构造函数中的构造函数也是如此)。将其移出构造函数,将其命名为actionPerformed(ActionEvent e)
,然后查看会发生什么。