When I start my program, it loads the main form with buttons that does it's necessary functions. I'd like to know how to create a button that, once clicked, will open another form with it's own buttons and functions.
For example:
Main Form has the buttons: 'Log In', 'Quit'
I would like to create another form when you click on the 'Log In' button...
And yes, I know I can use String username = JOptionPane.showInputDialog("Input Username");
for it, but I would like to create my own Log In form.
Any help would be much appreciated...
First, write the following LogInForm class.
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class LogInForm extends JPanel
{
JTextField username, password;
JButton login;
public LogInForm()
{
this.setLayout(new FlowLayout());
username = new JTextField("Username");
this.add(username);
password = new JTextField("Password");
this.add(password);
login = new JButton("log in");
this.add(login);
}
}
Then write the following class to do the job.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainForm extends JPanel
{
private JButton quit, logIn;
public MainForm()
{
this.setLayout(new FlowLayout());
quit = new JButton("quit");
this.add(quit);
logIn = new JButton("login");
this.add(logIn);
ActionHandler handler = new ActionHandler();
logIn.addActionListener(handler);
}
private class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == logIn)
{
JFrame logInFrame = new JFrame();
LogInForm logInForm = new LogInForm();
logInFrame.getContentPane().add(logInForm);
logInFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
logInFrame.setSize(400,300);
logInFrame.setVisible(true);
}
}
}
public static void main(String[] args)
{
JFrame mainFrame = new JFrame();
MainForm panel = new MainForm();
mainFrame.getContentPane().add(panel);
mainFrame.setSize(300,200);
mainFrame.setVisible(true);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.