Cant valid email textfield java - java

My problem is that i want to check if email textfield contains char "#".How am i supposed to do it?I also want to check if other textfields such as name, username, password are empty.Thanks alot in advance for your help. This application blowed my mind!
private JButton signupButton;
private JTextField name;
private JTextField email;
private JTextField username;
private JPasswordField pass;
private UserManager userManager;
public SignUpFrame (UserManager userManager){
super("Please fill in your Data");
userManager = new UserManager();
signupButton = new JButton("Sign Up!");
signupButton.addActionListener(new signupButtonListener());
name = new JTextField(15);
email = new JTextField(15);
username = new JTextField(15);
pass = new JPasswordField(15);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(5,2));
mainPanel.add(new JLabel("Name:"));
mainPanel.add(name);
mainPanel.add(new JLabel("Email:"));
mainPanel.add(email);
mainPanel.add(new JLabel("Username"));
mainPanel.add(username);
mainPanel.add(new JLabel("Password:"));
mainPanel.add(pass);
mainPanel.add(signupButton);
this.setContentPane(mainPanel);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
class signupButtonListener implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
String nam,emai,id,psw;
nam = name.getText();
emai= email.getText();
id = username.getText();
psw = pass.getText();
User u1 = new User(nam,emai,id,psw);
UserManager.userList.add(u1);
}

To check if a TextField is empty you can use if statements like:
if(name.getText().length() > 0){ nam = name.getText(); }
...
And for checking if there a char # in your email TextField you can use the .contains() method:
emai= email.getText();
if(emai.contains("#")){ ... }
I hope i was able to help you..

Try doing an if to test what the field hold ie
if(nam.equals("")){
//alert the user
}
You can do this with all the fields.
You could possible use regular expression for the email - something like
String emailreg = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";
Boolean result = emailAddress.matches(emailreg);
if(result == true){
//email is valid
}
Hope this helps.

Related

How do I edit components from another JFrame using a button from a different JFrame?

I have been trying to make a function wherein the user presses a button from a JFrame. Atfer pressing the button, all textfields, disabled buttons in another JFrame would reset, (textfields empty, buttons enabled) but I encountered a bug where my code does not do anything or rather it is unable to access the textfields and buttons of another class
Main Class:
public static void main(String[] args) {
UserInterface userinterface = new UserInterface();
userinterface.frame_main.setVisible(true);
}
Frame 1:
public class UserInterface{
public JFrame frame_main = new JFrame();
JPanel pnl_main = new JPanel();
JLabel lbl_firstname = new JLabel("First Name: ");
JLabel lbl_lastname = new JLabel("Last Name: ");
JLabel lbl_midname = new JLabel("Middle Name: ");
JLabel lbl_customerno = new JLabel("Contact Number: ");
JLabel lbl_customeremail = new JLabel("Email Address: ");
JButton btn_submit = new JButton("Submit");
JButton btn_clear = new JButton("Clear All");
JTextField txt_firstname = new JTextField(15);
JTextField txt_lastname = new JTextField(15);
JTextField txt_midname = new JTextField(15);
JTextField txt_customerno = new JTextField(13);
JTextField txt_customeremail = new JTextField(15);
FlowLayout fl = new FlowLayout();
Font set_font = new Font("", Font.BOLD, 14);
public UserInterface(){
frame_main.setSize(300,300);
frame_main.setLocation(200,200);
frame_main.setTitle("Event Driven Program");
frame_main.setResizable(false);
frame_main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txt_firstname.setFont(set_font);
txt_lastname.setFont(set_font);
txt_midname.setFont(set_font);
txt_customerno.setFont(set_font);
txt_customeremail.setFont(set_font);
pnl_main.add(lbl_firstname);
pnl_main.add(txt_firstname);
pnl_main.add(lbl_lastname);
pnl_main.add(txt_lastname);
pnl_main.add(lbl_midname);
pnl_main.add(txt_midname);
pnl_main.add(lbl_customerno);
pnl_main.add(txt_customerno);
pnl_main.add(lbl_customeremail);
pnl_main.add(txt_customeremail);
btn_submit.addActionListener(new actionButton1());
btn_submit.setEnabled(true);
pnl_main.add(btn_submit);
btn_clear.addActionListener(new actionButton2());
pnl_main.add(btn_clear);
frame_main.add(pnl_main);
}
public JButton getButton(){
return btn_submit;
}
class actionButton1 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
String firstname = txt_firstname.getText();
String lastname = txt_lastname.getText();
String midname = txt_midname.getText();
String customerno = txt_customerno.getText();
String customeremail = txt_customeremail.getText();
getButton().setEnabled(false);
new CustomerForm(firstname, lastname, midname, customerno, customeremail).setVisible(true);
}
}
class actionButton2 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
txt_firstname.setText("");
txt_lastname.setText("");
txt_midname.setText("");
txt_customerno.setText("");
txt_customeremail.setText("");
getButton().setEnabled(true);
}
}
}
Frame 2(where the button problem is):
public class CustomerForm extends JFrame{
JPanel pnl_info = new JPanel();
JTextArea output_area = new JTextArea(20, 20);
JFrame frame_info = new JFrame();
Font set_font = new Font("", Font.BOLD, 14);
FlowLayout fl = new FlowLayout();
JButton btn_okay = new JButton("Okay");
String firstname;
String lastname;
String midname;
String customerno;
String customeremail;
UserInterface ui = new UserInterface();
public CustomerForm(String firstname, String lastname, String midname, String customerno, String customeremail) {
this.setSize(300,600);
this.setLocation(500,300);
output_area.setBackground(Color.LIGHT_GRAY);
output_area.setEditable(false);
output_area.setFont(set_font);
btn_okay.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
CustomerForm.this.dispose();
ui.btn_submit.setEnabled(true);
ui.txt_firstname.setText("");
ui.txt_lastname.setText("");
ui.txt_midname.setText("");
ui.txt_customerno.setText("");
ui.txt_customeremail.setText("");
}
});
pnl_info.add(output_area);
pnl_info.add(btn_okay);
this.firstname = firstname;
this.lastname = lastname;
this.midname = midname;
this.customerno = customerno;
this.customeremail = customeremail;
output_area.append("\nFirst Name: " + firstname +
"\n\nLast Name: " + lastname +
"\n\nMiddle Name: " + midname +
"\n\nContact Number: " + customerno +
"\n\nEmail Address: " + customeremail);
this.add(pnl_info, BorderLayout.CENTER);
}
}
I think the problem is with my reference to the first frame but I have yet to know what causes the real problem Hopefully someone could help me out it would be a great push towards my learning of Java.
First of all: Class names typically starts uppercase.
You are trying to manipulate the GUI from the actionPerformed method which is not the GUI thread. Take a look at this:
How to pass the message from working thread to GUI in java

Java getText() from JTextField returns empty string while there is text in it

I'm trying to make a login form but when I try to get the username text and password text from the textfields it returns as an empty string.
public class Login extends JPanel {
private JLabel lblUsername;
private JLabel lblPassword;
private JButton btnLogin;
private JTextField txtUsername;
private JPasswordField txtPassword;
public void paintComponent(Graphics g) {
super.paintComponent(g);
setLayout(null);
lblUsername = new JLabel("Username:");
lblUsername.setSize(80,20);
lblUsername.setLocation(80,40);
lblPassword = new JLabel("Password:");
lblPassword.setSize(50,20);
lblPassword.setLocation(80,80);
txtUsername = new JTextField();
txtUsername.setSize(150,20);
txtUsername.setLocation(160,40);
txtPassword = new JPasswordField();
txtPassword.setSize(150,20);
txtPassword.setLocation(160,80);
btnLogin = new JButton("Login");
btnLogin.setSize(150,30);
btnLogin.setLocation(120,120);
btnLogin.addActionListener(new ActionListener()
{
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e)
{
System.out.println("Username " + txtUsername.getText() + " - Password: " + txtPassword.getText());
sqlFunctions database = new sqlFunctions();
if (database.checkAdminLogin(txtUsername.getText(), txtPassword.getText()) == true) {
System.out.println("Login success");
Frame.hideLogin();
} else {
JOptionPane.showMessageDialog(null, "Login is niet gelukt, probeer opnieuw.");
}
}
});
add(lblUsername);
add(lblPassword);
add(txtUsername);
add(txtPassword);
add(btnLogin);
}
}
I've had this issue with this project before. When I tried to use a buttonhandler for multiple buttons and work with if cases and e.getSource() it would never recognize which button was clicked.
Thanks for the help in advance :)

Java Object Method Not Accessible

In the following code, the file runs fine if I take the password.setEchoCar(char) method call out. Why can I not call it when the object is created right above it?
There shoudlnt be a scope problem and I checked the javadoc for the method, it seems to be the correct method for specifying a non-default password character.
Thanks
import javax.swing.*;
public class Authenticator extends javax.swing.JFrame {
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
password.setEchoChar('%');
JTextArea comments = new JTextArea(4, 15);
JButton ok = new JButton("OK");
JButton cancel = new JButton("Cancel");
public Authenticator () {
super("Account Information");
setSize(300, 220);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
JLabel usernameLabel= new JLabel("Username: ");
JLabel passwordLabel = new JLabel("Password: ");
JLabel commentsLabel = new JLabel("Comments: ");
comments.setLineWrap(true);
comments.setWrapStyleWord(true);
pane.add(usernameLabel);
pane.add(username);
pane.add(passwordLabel);
pane.add(password);
pane.add(commentsLabel);
pane.add(comments);
pane.add(ok);
pane.add(cancel);
add(pane);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
}
public static void main(String[] arguments) {
Authenticator.setLookAndFeel();
Authenticator auth = new Authenticator();
}
}
You're trying to execute code out side of an executable context (within the variable decleration area)...
public class Authenticator extends javax.swing.JFrame {
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
password.setEchoChar('%');
//...
public Authenticator () {
//...
Move password.setEchoChar('%'); to the constructor
public class Authenticator extends javax.swing.JFrame {
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
//...
public Authenticator () {
super("Account Information");
password.setEchoChar('%');
//...
JPasswordField password = new JPasswordField(15);
{
password.setEchoChar('%');
}
You can do that in an initializer block, but unless you have initialization code that is common to a number of constructors, it's considered good style to do it in the constructor.

How to make blank fields valid until user clicks SAVE -Java

This is a simple program that uses a JDialog to add or edit work orders. When the dialog appears, the user will enter information into the fields (name, date, position, billing rate, etc.). The program must validate each of these fields. The problem is that if I leave a field blank and I tab to the next field, the error message pops up. Actually, this isn't a problem, its working as it should, however, I would like to make it so that all blank fields are valid until the user clicks SAVE. Any suggestions or ideas? I have pasted the entire program below so feel free to compile and run it yourself, thank you!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.lang.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
import java.io.*;
import static javax.swing.GroupLayout.Alignment.*;
public class WorkOrderProject
{
public static void main (String args[])
{
new MyFrameClass();
}
}
class MyFrameClass extends JDialog implements ActionListener
{
JButton addButton, editButton;
JPanel buttonPanel;
WorkOrder workOrderToEdit = new WorkOrder();
MyFrameClass()
{
Container cp;
addButton = new JButton("ADD");
addButton.addActionListener(this);
addButton.setActionCommand("ADD");
editButton = new JButton("EDIT");
editButton.addActionListener(this);
editButton.setActionCommand("EDIT");
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(addButton);
buttonPanel.add(editButton);
cp = getContentPane();
cp.add(buttonPanel, BorderLayout.NORTH);
setupMainFrame();
}
void setupMainFrame()
{
Toolkit tk;
Dimension d;
tk = Toolkit.getDefaultToolkit();
d = tk.getScreenSize();
setLayout(new FlowLayout());
setTitle("Work Orders");
setSize(d.width/2, d.height/2);
setLocation(d.width/4, d.height/4);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("ADD"))
{
System.out.println("ADD");
new MyDialog();
}
else if(e.getActionCommand().equals("EDIT"))
{
System.out.println("EDIT");
new MyDialog(workOrderToEdit);
}
}
}
class MyDialog extends JDialog implements ActionListener
{
JPanel buttonPanel, fieldPanel;
JButton button1, button2, button3, button4;
GroupLayout layout;
WorkOrder workOrderToEdit;
String[] comboTypes = { "Sales", "Hardware", "Electronics" };
JComboBox<String> comboTypesList;
public MyDialog()
{
Container cp;
button1 = new JButton("SAVE");
button1.addActionListener(this);
button1.setActionCommand("SAVE");
button2 = new JButton("CANCEL");
button2.addActionListener(this);
button2.setActionCommand("CANCEL");
button2.setVerifyInputWhenFocusTarget(false);
button3 = new JButton("SAVE AND NEW");
button3.addActionListener(this);
button3.setActionCommand("SAVE AND NEW");
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(button2);
buttonPanel.add(button1);
buttonPanel.add(button3);
fieldPanel = setFields();
cp = getContentPane();
cp.add(fieldPanel, BorderLayout.NORTH);
cp.add(buttonPanel, BorderLayout.SOUTH);
setTitle("Add New Work Order");
setupMainFrame();
}
public MyDialog(WorkOrder w)
{
Container cp;
button1 = new JButton("SAVE");
button1.addActionListener(this);
button1.setActionCommand("SAVE");
button2 = new JButton("CANCEL");
button2.addActionListener(this);
button2.setActionCommand("CANCEL");
button2.setVerifyInputWhenFocusTarget(false);
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(button2);
buttonPanel.add(button1);
fieldPanel = setFields();
getContentPane().add(fieldPanel, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
setTitle("Edit Work Order");
setupMainFrame();
}
void setupMainFrame()
{
Toolkit tk;
Dimension d;
tk = Toolkit.getDefaultToolkit();
d = tk.getScreenSize();
setLayout(new FlowLayout());
setSize(d.width/3, d.height/3);
setLocation(d.width/3, d.height/3);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModal(true);
setVisible(true);
}
JPanel setFields()
{
GroupLayout layout;
JPanel p;
JLabel label1, label2, label3, label4, label5;
JTextField text1, text2, text3, text4, text5;
String[] comboTypes = { "-Select-" ,"Sales", "Hardware", "Electronics" };
comboTypesList = new JComboBox<>(comboTypes);
comboTypesList.addActionListener(this);
label1 = new JLabel("Name: ");
label2 = new JLabel("Department: ");
label3 = new JLabel("Date of request: ");
label4 = new JLabel("Date request was fulfilled: ");
label5 = new JLabel("Billing rate: ");
text1 = new JTextField(20);
text1.setInputVerifier(new NameVerifier());
text2 = new JTextField(20);
text3 = new JTextField(20);
text4 = new JTextField(20);
text5 = new JTextField(20);
p = new JPanel();
layout = new GroupLayout(p);
p.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
hGroup.addGroup(layout.createParallelGroup().addComponent(label1).addComponent(label2).addComponent(label3).addComponent(label4).addComponent(label5));
hGroup.addGroup(layout.createParallelGroup().addComponent(text1).addComponent(comboTypesList).addComponent(text3).addComponent(text4).addComponent(text5));
layout.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label1).addComponent(text1));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label2).addComponent(comboTypesList));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label3).addComponent(text3));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label4).addComponent(text4));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label5).addComponent(text5));
layout.setVerticalGroup(vGroup);
return(p);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("SAVE"))
{
System.out.println("SAVED");
dispose();
}
else if(e.getActionCommand().equals("CANCEL"))
{
System.out.println("CANCELED");
dispose();
}
else if(e.getActionCommand().equals("SAVE AND NEW"))
{
System.out.println("SAVED AND NEW");
}
}
}
class WorkOrder
{
String name;
int department;
Object dateRequested;
Object dateFulfilled;
String description;
double billingRate;
}
class NameVerifier extends InputVerifier
{
public boolean verify(JComponent input)
{
String str;
boolean isValid;
int score;
str = ((JTextField)input).getText().trim();
if(str.equals(""))
{
isValid = false;
JOptionPane.showMessageDialog(input.getParent(), "Name field is blank.", "ERROR", JOptionPane.ERROR_MESSAGE);
}
else
{
isValid = true;
}
return(isValid);
}
}
The problem is that if I leave a field blank and I tab to the next field, the error message pops up.
Don't use an InputVerifier. The purpose of the InputVerifier is to validate a text field when it loses focus.
I would like to make it so that all blank fields are valid until the user clicks SAVE.
Add your validation logic (for all the fields) to the ActionListener of the "Save" button.
So you would use the InputVerifier on each text field to validate the format of the data entered (when the data is entered). For example, for the "billing rate" you would verify that the value is a double number, the date fields contain a valid date.
Then in the "Save" listener you validate that all fields contain data. So if the data is in a valid format and all fields contain data, then you know the forum can be submitted for processing.

Can't seem to get .remove to work

So for a class that I am currently taking I need to create an ATM System. So, I decided to have 2 panels. A main panel, where all of the processes take place, and an options panel, where the options are listed for the user. The problem, as mentioned above, is that I can't seem to get the main panel to be removed so I can actually replace it with the panel for, say the create account screen. In fact, all that happens is that the terminal window shows. Completely blank. As far as I have checked, the buttons event is firing and it even gets past the remove function.
In any event, I can't seem to figure out what the problem is, perhaps it is because the button being pressed is also being removed with the panel. Here's the related code.
public class AccountSystem extends JFrame implements ActionListener
{
public static Account currentuser = new Account(); //This is so that the methods know which account is currently logged in so they can perform operations on it.
public static int count=0;
public static Account acc[] = new Account[1000];
public static String parts[] = new String[3];
private JButton login, logout, createacc, deposit1, deposit2, withdraw1, withdraw2, transfer1, transfer2, nevermind;
private JPanel options, mainarea, titlecard;
private JTextField username, password, transfer, depositarea, withdrawarea, retypearea;
private JLabel userprompt, depositprompt, withdrawpromt, balancedisp, passwordprompt, mainmessage, title;
private String newuser, newpass, newpassconfirm;
BorderLayout borderlayout;
GridLayout gridlayout;
public AccountSystem()
{
borderlayout = new BorderLayout();
borderlayout.setHgap(5);
borderlayout.setVgap(5);
//Establishing our buttons here.
JButton login = new JButton("Login");
login.addActionListener(this);
JButton createacc = new JButton("New Account");
createacc.addActionListener(this);
//Establishing our panels here.
JPanel options = new JPanel();
JPanel mainarea = new JPanel();
JPanel titlecard = new JPanel();
//Establishing our JLabel here.
JLabel userprompt = new JLabel("Username: ");
JLabel passwordprompt = new JLabel("Password: ");
JLabel title = new JLabel(" LOGIN ");
//Establishing our textfields here.
JTextField username = new JTextField(20);
JTextField password = new JTextField(20);
JTextField transfer = new JTextField(20);
JTextField withdrawarea = new JTextField(20);
//Building the GUI here.
titlecard.setSize(500,50);
titlecard.setLocation (0,0);
mainarea.setSize(300,450);
mainarea.setLocation(0,50);
options.setSize(150,450);
options.setLocation(300,50);
titlecard.add(title);
mainarea.add(userprompt);
mainarea.add(username);
mainarea.add(passwordprompt);
mainarea.add(password);
mainarea.add(login);
mainarea.add(createacc);
getContentPane().setLayout(null);
getContentPane().add(titlecard);
getContentPane().add(mainarea);
getContentPane().add(options);
}
}
public void actionPerformed (ActionEvent e)
{
if ((e.getActionCommand()).equals("Login"))
{
login();
}
else if ((e.getActionCommand()).equals("New Account"))
{
accountmaker();
}
else if ((e.getActionCommand()).equals("Deposit Funds"))
{
deposit();
}
else if ((e.getActionCommand()).equals("Withdraw Funds"))
{
withdraw();
}
else if ((e.getActionCommand()).equals("Withdraw"))
{
withdrawprocedure();
}
else if ((e.getActionCommand()).equals("Create Account"))
{
accountprocedure();
}
}
public void accountmaker() //This is the screen where the user creates the account they want to. Of course, something needed to be done to differentiate this screen and the login screen.
{
currentuser = null; //This is so that the program doesn't get somehow confused when dealing with multiple uses of the program.
getContentPane().remove(mainarea);
title.setText("Create New Account");
mainarea = new JPanel();
JLabel userprompt = new JLabel ("Username: ");
JLabel passwordprompt = new JLabel("Password: ");
JLabel retype = new JLabel ("Retype: "); //This is what makes it different from the login screen
createacc = new JButton ("Create Account");
createacc.addActionListener(this);
JButton nevermind = new JButton("Cancel");
nevermind.addActionListener(this);
JTextField username = new JTextField(20);
JTextField password = new JTextField(20);
retypearea = new JTextField(20);
mainarea.setSize(300,500);
mainarea.setLocation(0,0);
mainarea.add(userprompt);
mainarea.add(username);
mainarea.add(passwordprompt);
mainarea.add(password);
mainarea.add(retype);
mainarea.add(retypearea);
getContentPane().add(mainarea);
getContentPane().invalidate();
getContentPane().validate();
getContentPane().repaint();
}
And this is the Account class that the program uses.
public class Account
{
private String username;
private String password;
private double balance=0;
public void deposit (double deposit)
{
balance += deposit;
}
public void withdraw (double withdraw)
{
balance -= withdraw;
}
public void setBalance (double newbalance)
{
balance = newbalance;
}
public void setUsername (String newusername)
{
username = newusername;
}
public void setPassword (String newpassword)
{
password = newpassword;
}
public String getUsername ()
{
return username;
}
public double getbalance ()
{
return balance;
}
public String getpassword()
{
return password;
}
}
If I understand correctly.. you basically need to replace the main panel with account panel on certain event!
I have written example code (please modify it according to your project)
In this code.. I have created 4 panels namely
Component Panel: To hold all components
Main Panel: contains the label with text "Main Panel" and its border is painted RED
Account Panel: contains the label with text "Account Panel" and its border is painted GREEN
Option Panel: empty panel with its border is painted BLUE
Two buttons:
Account Button: Which should replace Main Panel with Account Panel
Main Button: Which should replace Account Panel with Main Panel
Using GridBagLayout, all you need to do is to place Main Panel and Account Panel at the same location i.e. gridx = 0 and gridy = 0 for both. At first Main Panel shall be displayed. On event "Account Button" set Main Panel's visibility false and Account Panels' true. For event "Main Button" do the vica versa. GridBagLayout is fantastic dynamic layout which manages the empty spacing by itslef without any distortion.
public class SwingSolution extends JFrame implements ActionListener
{
private JPanel componentPanel = null;
private JPanel mainPanel = null;
private JLabel mainLabel = null;
private JPanel optionPanel = null;
private JPanel accountPanel = null;
private JLabel accountLabel = null;
private JButton replaceToAccountPanel = null;
private JButton replaceToMainPanel = null;
private final static String MAIN_TO_ACCOUNT = "MainToAccount";
private final static String ACCOUNT_TO_MAIN = "AccountToMain";
public JPanel getComponentPanel()
{
if(null == componentPanel)
{
componentPanel = new JPanel();
GridBagLayout gridBagLayout = new GridBagLayout();
componentPanel.setLayout(gridBagLayout);
GridBagConstraints constraint = new GridBagConstraints();
constraint.insets = new Insets(10, 10, 10, 10);
mainPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 0;
mainPanel.setMinimumSize(new Dimension(100, 50));
mainPanel.setPreferredSize(new Dimension(100, 50));
mainPanel.setMaximumSize(new Dimension(100, 50));
mainPanel.setBorder(
BorderFactory.createLineBorder(Color.RED));
mainLabel = new JLabel("Main Panel");
mainPanel.add(mainLabel);
componentPanel.add(mainPanel, constraint);
accountPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 0;
accountPanel.setMinimumSize(new Dimension(100, 50));
accountPanel.setPreferredSize(new Dimension(100, 50));
accountPanel.setMaximumSize(new Dimension(100, 50));
accountPanel.setBorder(
BorderFactory.createLineBorder(Color.GREEN));
accountLabel = new JLabel("Account Panel");
accountPanel.add(accountLabel);
componentPanel.add(accountPanel, constraint);
optionPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 1;
optionPanel.setMinimumSize(new Dimension(100, 50));
optionPanel.setPreferredSize(new Dimension(100, 50));
optionPanel.setMaximumSize(new Dimension(100, 50));
optionPanel.setBorder(
BorderFactory.createLineBorder(Color.BLUE));
componentPanel.add(optionPanel, constraint);
replaceToAccountPanel = new JButton("Account Button");
replaceToAccountPanel.setName(MAIN_TO_ACCOUNT);
constraint.gridx = 0;
constraint.gridy = 2;
replaceToAccountPanel.setSize(new Dimension(800, 30));
replaceToAccountPanel.addActionListener(this);
componentPanel.add(replaceToAccountPanel, constraint);
replaceToMainPanel = new JButton("Main Button");
replaceToMainPanel.setName(ACCOUNT_TO_MAIN);
constraint.gridx = 1;
constraint.gridy = 2;
replaceToMainPanel.setMinimumSize(new Dimension(800, 30));
replaceToMainPanel.addActionListener(this);
componentPanel.add(replaceToMainPanel, constraint);
}
return componentPanel;
}
public void actionPerformed (ActionEvent evt)
{
JButton buttonClicked = (JButton) evt.getSource();
if(buttonClicked != null)
{
if(buttonClicked.getName().equals(MAIN_TO_ACCOUNT))
{
mainPanel.setVisible(false);
accountPanel.setVisible(true);
}
else if(buttonClicked.getName().equals(ACCOUNT_TO_MAIN))
{
mainPanel.setVisible(true);
accountPanel.setVisible(false);
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
SwingSolution main = new SwingSolution();
frame.setTitle("Simple example");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setContentPane(main.getComponentPanel());
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Categories

Resources