我写了一个程序,它是一个带有两个文本字段和两个按钮的登录窗口,此阶段的actionPerformed方法用于测试目的。
我的问题是,我把所有组件放在构造函数中,我不知道如何编写我的main()方法以使程序运行,我尝试了类似于获取类的引用,设置可见性,但它们都不起作用。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class LoginUI extends JFrame implements ActionListener
{
JTextField Tusername;
JTextField Tpassword;
JButton Login = new JButton("Login");
JButton register = new JButton("Register");
JLabel passwordLabel = new JLabel("Password");
JLabel userLabel = new JLabel("User");
public String username;
public String password;
public LoginUI()
{
JFrame frame = new JFrame("Login or register");
JPanel Panel = new JPanel();
frame.add(Panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Login.setBounds(10, 80, 80, 25);
Panel.add(Login);
Login.addActionListener(this);
register.setBounds(180, 80, 80, 25);
Panel.add(register);
register.addActionListener(this);
Panel.setLayout(null);
JLabel userLabel = new JLabel("User");
userLabel.setBounds(10, 10, 80, 25);
Panel.add(userLabel);
Tusername = new JTextField(20);
Tusername.setBounds(100, 10, 160, 25);
Panel.add(Tusername);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 40, 80, 25);
Panel.add(passwordLabel);
Tpassword = new JPasswordField(20);
Tpassword.setBounds(100, 40, 160, 25);
Panel.add(Tpassword);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == Login)
{
String username = Tusername.getText();
System.out.println(username);
}
else if (e.getSource() == register)
{
String password = Tpassword.getText();
System.out.println(password);
}
}
public static void main(String args[])
{
}}