我已经完成了登录编码,当点击登录按钮时,应该从JPanel lp导航到JPanel ap。如果我的代码中有任何错误或修改,请帮助我。我检查了很多代码,并且我编辑了最大值,我更喜欢简单的步骤
import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginPage extends JFrame implements ActionListener
{
JLabel jl,jl2,jl3,jl4;
JTextField jt,jt2;
JTextArea jt1;
JButton jb,jb2;
JPanel lp, ap;
JPasswordField pass,Passw;
public static void main(String args[])
{
LoginPage jf=new LoginPage("Login");
Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
int a=d.height/3;
int b=d.width/12;
jf.setBounds(a,b,660,500);
jf.setResizable(false);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(null);
}
public LoginPage(String title)
{
//First Panel containing Login details
lp=new JPanel();
lp.setLayout(null);
jl=new JLabel("Login to your Account Safely");
jl.setBounds(250,30,300,30);
lp.add(jl);
jl2=new JLabel("UserName");
jl2.setBounds(100,150,100,30);
lp.add(jl2);
jt=new JTextField(JTextField.CENTER);
jt.setBounds(250,150,300,25);
jt.setBorder(new LineBorder(Color.BLACK));
lp.add(jt);
jl3=new JLabel("Password");
jl3.setBounds(100,250,100,30);
lp.add(jl3);
pass=new JPasswordField(10);
pass.setBounds(250,250,300,25);
pass.setBorder(new LineBorder(Color.BLACK));
lp.add(pass);
jb=new JButton("Login");
jb.setBounds(250,350,80,25);
jb.setBorder(new LineBorder(Color.BLUE));
jb.setCursor(new Cursor(Cursor.HAND_CURSOR));
jb.addActionListener(this);
lp.add(jb);
jb2=new JButton("Cancel");
jb2.setBounds(450,350,80,25);
jb2.setBorder(new LineBorder(Color.RED));
jb2.setCursor(new Cursor(Cursor.HAND_CURSOR));
jb2.addActionListener(this);
lp.add(jb2);
add(lp);
// Next Panel containing Account details
ap=new JPanel();
ap.setLayout(null);
jl4=new JLabel("Login to your Account Safely");
jl4.setBounds(250,30,300,30);
ap.add(jl4);
jt2=new JTextField(JTextField.CENTER);
jt2.setBounds(250,150,300,25);
jt2.setBorder(new LineBorder(Color.BLACK));
ap.add(jt2);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==jb)
{
if(("".equals(jt.getText())) || ("".equals(pass.getText())))
{
JOptionPane.showMessageDialog(null,"Username and Password fields are mandatory");
}
else if(("admin".equals(jt.getText())) && ("admin".equals(pass.getText())))
{
lp.setVisible(false);
add(ap);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Username or Password");
}
}
else if(ae.getSource()==jb2)
{
System.exit(0);
}
}
}
答案 0 :(得分:1)
这个问题可能就是你在寻找的东西:
How do I change JPanel inside a JFrame on the fly?
但是我会在你的情况下使用 CardLayout 。从框架添加/删除面板比看起来更复杂。