Window always opens blank even though code is written - java

I am making a program which will open a class GUI called "Menu" when correct login info is put into a text field password field and a button called "login" is pressed. The problem is that the Menu window will open blank, not displaying what I have programmed into the Menu.
This is my code for Login class,
package ems;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.SystemColor;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login extends JFrame implements ActionListener{
private JFrame loginFrame;
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.loginFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
loginFrame = new JFrame();
loginFrame.setTitle("Login");
loginFrame.setBounds(100, 100, 450, 300);
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginFrame.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(112, 116, 74, 16);
loginFrame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(112, 165, 74, 16);
loginFrame.getContentPane().add(lblPassword);
usernameField = new JTextField();
usernameField.setBounds(198, 110, 134, 28);
loginFrame.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(198, 159, 134, 28);
loginFrame.getContentPane().add(passwordField);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog(loginFrame, "Login successful.");
loginFrame.setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog(loginFrame, "Login unsuccessful.");
}
}
});
btnLogin.setBounds(238, 210, 90, 30);
loginFrame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(108, 210, 90, 30);
loginFrame.getContentPane().add(btnExit);
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.setBounds(91, 86, 258, 163);
loginFrame.getContentPane().add(panel);
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(26, 23, 418, 16);
loginFrame.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
loginFrame.getContentPane().add(panel_1);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
This is the code for the Menu class,
package ems;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import ems.Login;
public class Menu extends Login implements ActionListener{
private JFrame menuFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.menuFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
menuFrame = new JFrame();
menuFrame.setTitle("Menu");
menuFrame.setBounds(100, 100, 450, 300);
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuFrame.getContentPane().setLayout(null);
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(64, 22, 331, 16);
menuFrame.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
menuFrame.getContentPane().add(panel_1);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuFrame.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
btnLogout.setBounds(307, 222, 117, 29);
menuFrame.getContentPane().add(btnLogout);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(10, 222, 117, 29);
menuFrame.getContentPane().add(btnExit);
}
}
Both of these classes are under a package called ems.
I am very new to programming and help would be greatly appreciated.
Thank you

You are creating another JFrame inside of Login and Menu, which is wrong, theres also no need that Menu extends Login
Here is the fixed version for Login:
package ems;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setTitle("Login");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(112, 116, 74, 16);
this.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(112, 165, 74, 16);
this.getContentPane().add(lblPassword);
usernameField = new JTextField();
usernameField.setBounds(198, 110, 134, 28);
this.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(198, 159, 134, 28);
this.getContentPane().add(passwordField);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog(Login.this, "Login successful.");
Login.this.setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog(Login.this, "Login unsuccessful.");
}
}
});
btnLogin.setBounds(238, 210, 90, 30);
this.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(108, 210, 90, 30);
this.getContentPane().add(btnExit);
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.setBounds(91, 86, 258, 163);
this.getContentPane().add(panel);
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(26, 23, 418, 16);
this.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
this.getContentPane().add(panel_1);
}
}
And for Menu
package ems;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Menu extends JFrame{
private static final long serialVersionUID = 1L;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setTitle("Menu");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(64, 22, 331, 16);
this.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
this.getContentPane().add(panel_1);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.this.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
btnLogout.setBounds(307, 222, 117, 29);
this.getContentPane().add(btnLogout);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(10, 222, 117, 29);
this.getContentPane().add(btnExit);
}
}

Still looking, but:
menuFrame.getContentPane().add(lblLoginToThe);
The content pane isn't a container, you can't add multiple things to it. You need to put everything in a panel (note panel != pane) and then add one panel to the content pane.
Also don't call setBounds() directly, use a layout manager. That's another reason you could be seeing nothing: all your components are drawn outside of the window or some other similar error. Layout managers will fix that.
EDIT: And as Edwardth said you have a habit of declaring your classes to be a thing (like JFrame) and then creating a second JFrame inside the initialize method. Don't do that.
public class Login extends JFrame implements ActionListener{
...
private void initialize() {
loginFrame = new JFrame(); // BAD!
The JFrame was already made when you declared that Login extends JFrame you don't need a second frame.
Edwardth got the answer before me so go ahead and study his example and then mark his answer correct. Ask in the comments below if you have further questions.
Here's my example of the Login class, without the setBounds().
class Login extends JFrame implements ActionListener{
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setTitle("Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblUsername = new JLabel("Username");
JLabel lblPassword = new JLabel("Password");
usernameField = new JTextField();
usernameField.setColumns(10);
passwordField = new JPasswordField();
JPanel loginPanel = new JPanel( new GridLayout( 0,2 ) );
loginPanel.add( lblUsername );
loginPanel.add( usernameField );
loginPanel.add( lblPassword );
loginPanel.add( passwordField );
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog( Login.this, "Login successful.");
setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog( Login.this, "Login unsuccessful.");
}
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.add( btnLogin );
panel.add( btnExit );
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.add( lblLoginToThe );
Box topBox = Box.createVerticalBox();
topBox.add( panel_1 );
topBox.add( loginPanel );
topBox.add( panel );
add( topBox );
pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
And the Main class:
class Menu extends JFrame {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setTitle("Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box topBox = Box.createVerticalBox();
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
topBox.add( lblLoginToThe ); // **********
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
topBox.add( panel_1 ); // *************
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.this.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
topBox.add( btnLogout ); //****************
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
topBox.add( btnExit );
add( topBox );
pack();
}
}

Related

calling a JPanel from another JPanel in a window

I have a login and a register panel and a window to hold all the panels. What I am trying to do is to go to the login panel when the register button is pressed. But it does not work. The method that I use would work if the login panel is inside the window but when it is in its own class it doesn't. Can someone please let me know how to do this?
Here is my code for the Window
package userInterface;
import java.awt.*;
import java.awt.EventQueue;
import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import company.CompanySys;
import javax.swing.*;
import java.awt.CardLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
public class FrontEnd {
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
private static FrontEnd front = new FrontEnd();
private JFrame frame;
private final JLayeredPane layeredPane = new JLayeredPane();
public final RegisterPanel registerPan = new RegisterPanel();
public final LoginPanel loginPan = new LoginPanel();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrontEnd window = new FrontEnd();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
private FrontEnd() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setFrame();
this.setLayout();
this.addPanels();
}
/**
* Setting up the main frame
*/
private void setFrame() {
frame = new JFrame();
frame.setBounds(100, 100, 900, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
layeredPane.setBounds(0, 0, 900, 700);
frame.getContentPane().add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
}
/**
* Setting Layout
*/
public void setLayout() {
// frame.getContentPane().add(layeredPane, "name_2578740971832500");
// layeredPane.setLayout(new CardLayout(0, 0));
}
public void SetSizeandLocation() {
this.registerPan.setBounds(10, 10, 900, 700);
layeredPane.setLayer(loginPan, 0);
this.loginPan.setBounds(10, 10, 900, 700);
}
/**
* Set visibility of the components
*/
private void setVisibility() {
// this.registerPan.setVisible(true);
// this.loginPan.setVisible(true);
}
/**
* Adding panels to the window
*/
private void addPanels() {
layeredPane.add(registerPan);
layeredPane.add(loginPan);
}
public static FrontEnd getFront() {
return front;
}
/**
* Switching Panels
* #param panel
*/
public void switchPanels(JPanel panel) {
layeredPane.removeAll();
layeredPane.add(panel);
layeredPane.repaint();
layeredPane.revalidate();
}
public LoginPanel getLoginPan() {
return this.loginPan;
}
}
Here is the code for Register Panel
package userInterface;
import company.*;
import javax.swing.*;
import java.awt.event.*;
public class RegisterPanel extends JPanel implements ActionListener{
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
FrontEnd front = FrontEnd.getFront();
// Input fields
private JTextField usernameTextField = new JTextField();
private JPasswordField passwordField1 = new JPasswordField();
private JPasswordField passwordField2 = new JPasswordField();
// Labels
private JLabel usernameLabel = new JLabel("Username");
private JLabel password1Label = new JLabel("Password");
private JLabel password2Label = new JLabel("Password");
// Buttons
private JButton registerButton = new JButton("REGISTER");
private JButton cancelButton = new JButton("CANCEL");
private JButton haveAccount = new JButton("Already have an account? Login");
private JButton clearButton = new JButton("CLEAR");
// Others
private JCheckBox showPasswordCheckBox = new JCheckBox("Show Password");
/**
* Create the panel.
*/
public RegisterPanel() {
setLayout(null);
this.addComponents();
this.setSizeandLocations();
this.addActionEvent();
}
/**
* Methods
*/
// Set size and location of the components
public void setSizeandLocations() {
// Labels
usernameLabel.setBounds(312, 106, 64, 14);
password1Label.setBounds(324, 175, 64, 14);
password2Label.setBounds(312, 237, 64, 14);
// Input Fields
usernameTextField.setBounds(493, 103, 96, 20);
passwordField1.setBounds(493, 173, 97, 17);
passwordField2.setBounds(494, 234, 96, 20);
passwordField1.setEchoChar('*');
passwordField2.setEchoChar('*');
//Buttons
registerButton.setBounds(337, 301, 89, 23);
cancelButton.setBounds(479, 301, 89, 23);
haveAccount.setBounds(366, 363, 196, 23);
clearButton.setBounds(606, 301, 89, 23);
// Others
showPasswordCheckBox.setBounds(493, 261, 141, 23);
}
// Add all components to the panel
public void addComponents() {
// Add Labels
add(usernameLabel);
add(password1Label);
add(password2Label);
// Add input fields
add(usernameTextField);
add(passwordField1);
add(passwordField2);
// Add Buttons
add(registerButton);
add(cancelButton);
add(haveAccount);
add(clearButton);
// Others
add(showPasswordCheckBox);
}
/**
* Adding Action listener
*/
public void addActionEvent() {
this.registerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
front.switchPanels(front.getLoginPan());
}
});
this.cancelButton.addActionListener(this);
this.haveAccount.addActionListener(this);
this.clearButton.addActionListener(this);
this.showPasswordCheckBox.addActionListener(this);
}
/**
* Main method of the panel
* #param args
*/
public static void main(String args[]) {
RegisterPanel frame = new RegisterPanel();
frame.setVisible(true);
frame.setBounds(10, 10, 900, 500);
}
/**
* Adding the functionality to the components
*/
#Override
public void actionPerformed(ActionEvent e) {
String usr = this.usernameTextField.getText();
String pass1 = String.valueOf(this.passwordField1.getPassword());
String pass2 = String.valueOf(this.passwordField2.getPassword());
// if (e.getSource() == this.registerButton) {
// if (sys.register(usr, pass1, pass2)) {
// // JOptionPane.showConfirmDialog(null, "Success", getName(), JOptionPane.DEFAULT_OPTION);
//
// front.switchPanels(front.getLoginPan());
// }
// else {
// JOptionPane.showConfirmDialog(null, "fail", getName(), JOptionPane.DEFAULT_OPTION);
// }
// }
if (e.getSource() == this.cancelButton) {
}
else if (e.getSource() == this.haveAccount) {
}
else if (e.getSource() == this.showPasswordCheckBox) {
if(this.showPasswordCheckBox.isSelected()) {
this.passwordField1.setEchoChar((char) 0);
this.passwordField2.setEchoChar((char) 0);
}
else {
this.passwordField1.setEchoChar('*');
this.passwordField2.setEchoChar('*');
}
}
else if (e.getSource() == this.clearButton) {
this.passwordField1.setText("");
this.passwordField2.setText("");
this.usernameTextField.setText("");
}
}
}
Here is code for login panel
package userInterface;
import company.CompanySys;
import javax.swing.*;
import java.awt.event.*;
public class LoginPanel extends JPanel implements ActionListener{
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
// Fields
private JTextField userNameTextField = new JTextField();;
private JPasswordField passwordField = new JPasswordField();;
// Labels
JLabel userNameLabel = new JLabel("Username");
JLabel passwordLabel = new JLabel("Password");
// Buttons
JButton cancelButton = new JButton("CANCEL");
JButton loginButton = new JButton("LOGIN");
JButton noAccountButton = new JButton("Don't have an acount? register");
JButton clearButton = new JButton("CLEAR");
// Others
JCheckBox showPassCheckBox = new JCheckBox("Show Password");
/**
* Constructor
*/
public LoginPanel() {
setLayout(null);
this.setSizeAndLocation();
this.addComponent();
this.addAction();
}
/**
* Setting size and location of the components
*/
public void setSizeAndLocation() {
// Labels
userNameLabel.setBounds(97, 52, 69, 14);
passwordLabel.setBounds(97, 88, 48, 14);
// TextFields
passwordField.setBounds(197, 85, 103, 20);
userNameTextField.setBounds(197, 49, 96, 20);
// Buttons
clearButton.setBounds(325, 146, 89, 23);
noAccountButton.setBounds(85, 196, 208, 23);
cancelButton.setBounds(209, 146, 89, 23);
loginButton.setBounds(85, 146, 89, 23);
// Others
showPassCheckBox.setBounds(197, 116, 130, 23);
}
/**
* Adding components to the Panel
*/
public void addComponent() {
// Labels
this.add(userNameLabel);
this.add(passwordLabel);
// TextFields
this.add(userNameTextField);
this.add(passwordField);
// Buttons
this.add(loginButton);
this.add(cancelButton);
this.add(noAccountButton);
this.add(clearButton);
// Others
this.add(showPassCheckBox);
}
/**
* Adding ActionListener to the interactive components
*/
public void addAction() {
// Buttons
this.clearButton.addActionListener(this);
this.cancelButton.addActionListener(this);
this.loginButton.addActionListener(this);
this.noAccountButton.addActionListener(this);
// Others
this.showPassCheckBox.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
}
public static void main(String args[]) {
LoginPanel frame = new LoginPanel();
frame.setVisible(true);
frame.setBounds(10, 10, 900, 700);
}
}
I have tried other ways too but it doesnt work!

How do I switch between panels using a CardLayout?

I have made a parentPanel that has a CardLayout on it, and under this I've made 4 more JPanel containers.
On the left side I have 4 buttons that when I press "Forside" (button) I want to switch to the panel on the card layout (Forside) and so on...
I've tried different youtube tutorials and tried to look on here without any success.
Everything I have tried has ended up with a NullPointerException
public class Main extends JFrame {
private JPanel contentPane;
int xx, xy;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setUndecorated(true); // Hides the jframe top bar
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 735, 506);
contentPane = new JPanel();
contentPane.setBackground(new Color(102, 102, 102));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panelLeft = new JPanel();
panelLeft.setBackground(new Color(51, 51, 51));
panelLeft.setForeground(Color.DARK_GRAY);
panelLeft.setBounds(0, 54, 150, 459);
contentPane.add(panelLeft);
panelLeft.setLayout(null);
JButton btnForside = new JButton("Forside");
btnForside.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnForside.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnForside.setForeground(Color.WHITE);
btnForside.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnForside.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Home_32px_1.png")));
btnForside.setContentAreaFilled(false);
btnForside.setBorderPainted(false);
btnForside.setBorder(null);
btnForside.setBounds(16, 60, 112, 30);
panelLeft.add(btnForside);
JButton btnDagbog = new JButton("Dagbog");
btnDagbog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDagbog.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnDagbog.setContentAreaFilled(false);
btnDagbog.setBorderPainted(false);
btnDagbog.setBorder(null);
btnDagbog.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnDagbog.setForeground(Color.WHITE);
btnDagbog.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Book_32px.png")));
btnDagbog.setBounds(16, 116, 112, 30);
panelLeft.add(btnDagbog);
JButton btnAftaler = new JButton("Aftaler");
btnAftaler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnAftaler.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAftaler.setContentAreaFilled(false);
btnAftaler.setBorderPainted(false);
btnAftaler.setBorder(null);
btnAftaler.setForeground(Color.WHITE);
btnAftaler.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnAftaler.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Planner_32px.png")));
btnAftaler.setBounds(16, 173, 112, 30);
panelLeft.add(btnAftaler);
JButton btnKontakt = new JButton("Kontakt");
btnKontakt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnKontakt.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnKontakt.setContentAreaFilled(false);
btnKontakt.setBorder(null);
btnKontakt.setBorderPainted(false);
btnKontakt.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnKontakt.setForeground(Color.WHITE);
btnKontakt.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Phone_32px.png")));
btnKontakt.setBounds(16, 231, 112, 30);
panelLeft.add(btnKontakt);
JPanel panelTop = new JPanel();
panelTop.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent arg0) {
int x = arg0.getXOnScreen(); // makes uggerhøj picture dragable
int y = arg0.getYOnScreen(); // makes uggerhøj picture dragable
Main.this.setLocation(x - xx, y - xy); // makes uggerhøj picture dragable
}
});
panelTop.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
xx = e.getX(); // makes uggerhøj picture dragable
xy = e.getY(); // makes uggerhøj picture dragable
}
});
panelTop.setBackground(new Color(51, 51, 51));
panelTop.setBounds(0, 0, 737, 60);
contentPane.add(panelTop);
panelTop.setLayout(null);
JButton btnX = new JButton("X");
btnX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnX.setRolloverIcon(null);
btnX.setFont(new Font("Tahoma", Font.BOLD, 18));
btnX.setFocusTraversalKeysEnabled(false);
btnX.setFocusPainted(false);
btnX.setBorderPainted(false);
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnX.setContentAreaFilled(false);
btnX.setForeground(SystemColor.activeCaption);
btnX.setBorder(null);
btnX.setBounds(615, 13, 97, 25);
panelTop.add(btnX);
JPanel parentPanel = new JPanel();
parentPanel.setBackground(Color.GRAY);
parentPanel.setBounds(148, 54, 569, 405);
contentPane.add(parentPanel);
parentPanel.setLayout(new CardLayout(0, 0));
JPanel Forside = new JPanel();
parentPanel.add(Forside, "name_1472174211097300");
Forside.setFocusable(false);
JButton btnTest = new JButton("test");
Forside.add(btnTest);
JPanel Dagbog = new JPanel();
parentPanel.add(Dagbog, "name_1472176236196000");
JLabel lblTest = new JLabel("dagbog");
Dagbog.add(lblTest);
JPanel Aftaler = new JPanel();
parentPanel.add(Aftaler, "name_1472177885026100");
JPanel Kontakt = new JPanel();
parentPanel.add(Kontakt, "name_1472179607862700");
}
}
I'd just want it so the right buttons leads to the right cards.
first of all please next time take #AndrewThompson advise about making a MCVE of your code and #camickr advise about the test and debug in little steps before going to the real code (this is the expert programming 101).
the CardLayout object switches between the content of the container via the method
CardLayout.show(Container parent, String name);
keep in mind when making navigation in your swing code DO-NOT make your Components fields in a method instead make it local variables (at least in your case the parentPanel and the CardLayout)
so in order to make your parentPanel switch between your 4 panels (sorry am not familiar with your language) i did a fairly refactored version of your code .
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class Main extends JFrame {
private JPanel contentPane;
int xx, xy;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setUndecorated(true); // Hides the jframe top bar
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 735, 506);
contentPane = new JPanel();
contentPane.setBackground(new Color(102, 102, 102));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Forside = new JPanel();
JPanel Dagbog = new JPanel();
JPanel Aftaler = new JPanel();
JPanel Kontakt = new JPanel();
JPanel panelLeft = new JPanel();
panelLeft.setBackground(new Color(51, 51, 51));
panelLeft.setForeground(Color.DARK_GRAY);
panelLeft.setBounds(0, 54, 150, 459);
contentPane.add(panelLeft);
panelLeft.setLayout(null);
JButton btnForside = new JButton("Forside");
btnForside.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setCardLayoutView("name_1472174211097300");
}
});
btnForside.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnForside.setForeground(Color.WHITE);
btnForside.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnForside.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Home_32px_1.png")));
btnForside.setContentAreaFilled(false);
btnForside.setBorderPainted(false);
btnForside.setBorder(null);
btnForside.setBounds(16, 60, 112, 30);
panelLeft.add(btnForside);
JButton btnDagbog = new JButton("Dagbog");
btnDagbog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472176236196000");
}
});
btnDagbog.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnDagbog.setContentAreaFilled(false);
btnDagbog.setBorderPainted(false);
btnDagbog.setBorder(null);
btnDagbog.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnDagbog.setForeground(Color.WHITE);
btnDagbog.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Book_32px.png")));
btnDagbog.setBounds(16, 116, 112, 30);
panelLeft.add(btnDagbog);
JButton btnAftaler = new JButton("Aftaler");
btnAftaler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472177885026100");
}
});
btnAftaler.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAftaler.setContentAreaFilled(false);
btnAftaler.setBorderPainted(false);
btnAftaler.setBorder(null);
btnAftaler.setForeground(Color.WHITE);
btnAftaler.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnAftaler.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Planner_32px.png")));
btnAftaler.setBounds(16, 173, 112, 30);
panelLeft.add(btnAftaler);
JButton btnKontakt = new JButton("Kontakt");
btnKontakt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472179607862700");
}
});
btnKontakt.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnKontakt.setContentAreaFilled(false);
btnKontakt.setBorder(null);
btnKontakt.setBorderPainted(false);
btnKontakt.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnKontakt.setForeground(Color.WHITE);
btnKontakt.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Phone_32px.png")));
btnKontakt.setBounds(16, 231, 112, 30);
panelLeft.add(btnKontakt);
JPanel panelTop = new JPanel();
panelTop.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent arg0) {
int x = arg0.getXOnScreen(); // makes uggerhøj picture dragable
int y = arg0.getYOnScreen(); // makes uggerhøj picture dragable
Main.this.setLocation(x - xx, y - xy); // makes uggerhøj picture dragable
}
});
panelTop.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
xx = e.getX(); // makes uggerhøj picture dragable
xy = e.getY(); // makes uggerhøj picture dragable
}
});
panelTop.setBackground(new Color(51, 51, 51));
panelTop.setBounds(0, 0, 737, 60);
contentPane.add(panelTop);
panelTop.setLayout(null);
JButton btnX = new JButton("X");
btnX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnX.setRolloverIcon(null);
btnX.setFont(new Font("Tahoma", Font.BOLD, 18));
btnX.setFocusTraversalKeysEnabled(false);
btnX.setFocusPainted(false);
btnX.setBorderPainted(false);
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnX.setContentAreaFilled(false);
btnX.setForeground(SystemColor.activeCaption);
btnX.setBorder(null);
btnX.setBounds(615, 13, 97, 25);
panelTop.add(btnX);
parentPanel = new JPanel();
parentPanel.setBackground(Color.GRAY);
parentPanel.setBounds(148, 54, 569, 405);
contentPane.add(parentPanel);
cardLayoutObject = new CardLayout(0, 0);
parentPanel.setLayout(cardLayoutObject);
parentPanel.add(Forside, "name_1472174211097300");
Forside.setFocusable(false);
JButton btnTest = new JButton("test");
Forside.add(btnTest);
parentPanel.add(Dagbog, "name_1472176236196000");
JLabel lblTest = new JLabel("dagbog");
Dagbog.add(lblTest);
parentPanel.add(Aftaler, "name_1472177885026100");
parentPanel.add(Kontakt, "name_1472179607862700");
}
private CardLayout cardLayoutObject;
private JPanel parentPanel;
private void setCardLayoutView(String viewName) {
cardLayoutObject.show(parentPanel, viewName);
}
}
and happy coding ^-^.

How to display multiple jpassword field in pop up in swing java?

I have 2 JTextField and 2 JPasswordField component in my swing java which frame looks as below:
When ShowAllDetails button is clicked, all the entered details is displayed in JtextArea as shown below:
Below is the code for the same:
package popUpTest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PopUpTest
{
private JFrame frame;
private JPasswordField passSourcePassword;
private JTextField txtSourceUserName;
private JTextField txtTargetUserName;
private JPasswordField passTargetPassword;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
PopUpTest window = new PopUpTest();
window.frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PopUpTest()
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 444, 403);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblSourceUserName = new JLabel("SourceUserName:");
lblSourceUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourceUserName.setBounds(15, 62, 170, 20);
frame.getContentPane().add(lblSourceUserName);
passSourcePassword = new JPasswordField();
passSourcePassword.setBounds(15, 153, 147, 26);
frame.getContentPane().add(passSourcePassword);
JLabel lblSourcePassword = new JLabel("SourcePassword:");
lblSourcePassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourcePassword.setBounds(15, 132, 147, 20);
frame.getContentPane().add(lblSourcePassword);
txtSourceUserName = new JTextField();
txtSourceUserName.setBounds(16, 81, 146, 26);
frame.getContentPane().add(txtSourceUserName);
txtSourceUserName.setColumns(10);
JLabel lblTargetUserName = new JLabel("TargetUserName:");
lblTargetUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetUserName.setBounds(240, 62, 170, 20);
frame.getContentPane().add(lblTargetUserName);
txtTargetUserName = new JTextField();
txtTargetUserName.setColumns(10);
txtTargetUserName.setBounds(241, 81, 146, 26);
frame.getContentPane().add(txtTargetUserName);
JLabel lblTargetPassword = new JLabel("TargetPassword:");
lblTargetPassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetPassword.setBounds(240, 132, 147, 20);
frame.getContentPane().add(lblTargetPassword);
passTargetPassword = new JPasswordField();
passTargetPassword.setBounds(240, 153, 147, 26);
frame.getContentPane().add(passTargetPassword);
JLabel lblEnterBelowDetails = new JLabel("Enter Below Details:");
lblEnterBelowDetails.setFont(new Font("Tahoma", Font.BOLD, 16));
lblEnterBelowDetails.setBounds(15, 26, 187, 20);
frame.getContentPane().add(lblEnterBelowDetails);
JTextArea textArea = new JTextArea();
textArea.setBounds(15, 252, 365, 85);
frame.getContentPane().add(textArea);
JButton btnShowAllDetails = new JButton("Show All Details:");
btnShowAllDetails.setBounds(15, 207, 226, 29);
frame.getContentPane().add(btnShowAllDetails);
btnShowAllDetails.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
textArea.append(txtSourceUserName.getText() + "\n");
textArea.append(passSourcePassword.getText() + "\n");
textArea.append(txtTargetUserName.getText() + "\n");
textArea.append(passTargetPassword.getText() + "\n");
}
});
}
}
Now instead of diplaying these 4 components on loading the main frame instead, i want to diplay these 4 components in a Pop up Window on click of a button as below:
Also on clicking of Show All Details button should work as before.(i.e. it should populate JtextArea with the values entered in Pop Up)
How can I achieve this?
I have gone through other blogs as well however didn't find to show such multiple JPasswordField/JTextField in popup.Any guidance would be highly appreciated.
Just add the new components (JTextFields and JPasswordFields) within a button listener and call repaint() and revalidate() on the frame after that.
Here is a solution without proper layout:
EDIT:
package popUpTest;
import java.awt.EventQueue;
import javax.swing.*;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PopUpTest
{
private JFrame frame;
private JPasswordField passSourcePassword;
private JTextField txtSourceUserName;
private JTextField txtTargetUserName;
private JPasswordField passTargetPassword;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
PopUpTest window = new PopUpTest();
window.frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PopUpTest()
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 444, 403);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton popUpButton = new JButton("Click to Show Pop Up To Enter Detail");
popUpButton.setBounds(15, 100, 365, 85);
popUpButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new MyDialog();
}
});
frame.getContentPane().add(popUpButton);
textArea = new JTextArea();
textArea.setBounds(15, 252, 365, 85);
frame.getContentPane().add(textArea);
JButton btnShowAllDetails = new JButton("Show All Details:");
btnShowAllDetails.setBounds(15, 207, 226, 29);
frame.getContentPane().add(btnShowAllDetails);
btnShowAllDetails.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
textArea.append(txtSourceUserName.getText() + "\n");
textArea.append(passSourcePassword.getText() + "\n");
textArea.append(txtTargetUserName.getText() + "\n");
textArea.append(passTargetPassword.getText() + "\n");
}
});
}
public JTextArea getTextArea() {
return textArea;
}
private class MyDialog extends JDialog {
private final JPasswordField passSourcePassword;
private final JTextField txtSourceUserName;
private final JTextField txtTargetUserName;
private final JPasswordField passTargetPassword;
public MyDialog() {
setSize(600, 500);
setLayout(null);
JLabel lblEnterBelowDetails = new JLabel("Enter Below Details:");
lblEnterBelowDetails.setFont(new Font("Tahoma", Font.BOLD, 16));
lblEnterBelowDetails.setBounds(15, 26, 187, 20);
add(lblEnterBelowDetails);
JLabel lblSourceUserName = new JLabel("SourceUserName:");
lblSourceUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourceUserName.setBounds(15, 62, 170, 20);
add(lblSourceUserName);
passSourcePassword = new JPasswordField();
passSourcePassword.setBounds(15, 153, 147, 26);
add(passSourcePassword);
JLabel lblSourcePassword = new JLabel("SourcePassword:");
lblSourcePassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourcePassword.setBounds(15, 132, 147, 20);
add(lblSourcePassword);
txtSourceUserName = new JTextField();
txtSourceUserName.setBounds(16, 81, 146, 26);
add(txtSourceUserName);
txtSourceUserName.setColumns(10);
JLabel lblTargetUserName = new JLabel("TargetUserName:");
lblTargetUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetUserName.setBounds(240, 62, 170, 20);
add(lblTargetUserName);
txtTargetUserName = new JTextField();
txtTargetUserName.setColumns(10);
txtTargetUserName.setBounds(241, 81, 146, 26);
add(txtTargetUserName);
JLabel lblTargetPassword = new JLabel("TargetPassword:");
lblTargetPassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetPassword.setBounds(240, 132, 147, 20);
add(lblTargetPassword);
passTargetPassword = new JPasswordField();
passTargetPassword.setBounds(240, 153, 147, 26);
add(passTargetPassword);
JButton publishButton = new JButton("Publish");
publishButton.setBounds(100, 200, 146, 26);
add(publishButton);
publishButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textArea.append(txtSourceUserName.getText() + "\n");
textArea.append(passSourcePassword.getText() + "\n");
textArea.append(txtTargetUserName.getText() + "\n");
textArea.append(passTargetPassword.getText() + "\n");
dispose();
}
});
setVisible(true);
}
}
}
By the way: try to read about layout managers as soon as possible, because absolute coordinates are a pain in the ass ;-)

How to make JButtons visible on a JPanel with an image as background

I've made a JPanel with a image as background. But while loading the JPanel first time the rest of the added components but the image are not visible. After rolling the mouse over the image, the buttons become visible. How to make the JButtons visible along with the image as background while loading the panel.
Here is the piece of my code:
contentPane = new JPanel();
contentPane.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
setContentPane(contentPane);
contentPane.setLayout(null);
homePanel.setBounds(10, 11, 959, 620);
homePanel.setLayout(null);
JPanel wizardPanel = new JPanel();
wizardPanel.setBounds(10, 295, 545, 336);
wizardPanel.setLayout(null);
homePanel.add(wizardPanel);
JLabel backgroundLabel;
try {
backgroundLabel = new JLabel(new ImageIcon(ImageIO.read(new File("images/nature.jpg"))));
backgroundLabel.setBounds(0, 0, 545, 336);
wizardPanel.add(backgroundLabel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(309, 95, 89, 23);
wizardPanel.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setBounds(309, 150, 89, 23);
wizardPanel.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("New button");
btnNewButton_2.setBounds(309, 212, 89, 23);
wizardPanel.add(btnNewButton_2);
It's a bad idea to place button over label. Better way is to paint image as panel background or to use JLayer. Here is an example for the first solution:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.LayoutManager;
import java.util.Objects;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class JImagePanel extends JPanel {
private final Image image;
private boolean scale;
public JImagePanel(Image anImage) {
image = Objects.requireNonNull(anImage);
}
public JImagePanel(Image anImage, LayoutManager aLayout) {
super(aLayout);
image = Objects.requireNonNull(anImage);
}
/**
* {#inheritDoc}
*/
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
final Image toDraw = scale? image.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH) : image;
g.drawImage(toDraw, 0, 0, this);
}
/**
* {#inheritDoc}
*/
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
} else {
return new Dimension(image.getWidth(this), image.getHeight(this));
}
}
public boolean isScale() {
return scale;
}
public void setScale(boolean scale) {
this.scale = scale;
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final JImagePanel p =
new JImagePanel(ImageIO.read(JImagePanel.class.getResource("myImage.png")), new FlowLayout());
p.setScale(true);
p.add(new JButton("Button"));
final JFrame frm = new JFrame("Image test");
frm.add(p);
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
A quick solution might be directly setting JFrame content pane to the image and adding your components to the content pane of this JFrame. Assuming your code is from the body of a JFrame class. My suggestion would more or less look like this:
JRootPane rootpane = new JRootPane();
JPanel contentPane = new JPanel();
contentPane.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
rootpane.setContentPane(contentPane);
contentPane.setLayout(null);
JPanel homePanel = new JPanel();
homePanel.setBounds(10, 11, 959, 620);
homePanel.setLayout(null);
JRootPane wizardPanel = new JRootPane();
wizardPanel.setBounds(10, 295, 545, 336);
wizardPanel.setLayout(null);
JLabel backgroundLabel;
try {
File f = new File("D:\\work\\eclipse\\workspace_eclipse_4.4.1\\trialExamples\\src\\main\\images\\nature.jpg");
backgroundLabel = new JLabel(new ImageIcon(ImageIO.read(f)));
backgroundLabel.setBounds(0, 0, 545, 336);
wizardPanel.setContentPane(backgroundLabel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(309, 95, 89, 23);
wizardPanel.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setBounds(309, 150, 89, 23);
wizardPanel.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("New button");
btnNewButton_2.setBounds(309, 212, 89, 23);
wizardPanel.getContentPane().add(btnNewButton_2);
homePanel.add(wizardPanel.getContentPane());
add(homePanel);
this is crazy !! I got it working by placing the JButtons initialization code block above the Image loading portion it works .....
package demo;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class demoframe extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1436190962490331120L;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
demoframe frame = new demoframe();
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(frame);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public demoframe() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 988, 678);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 501, 361);
contentPane.add(panel);
panel.setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(322, 112, 89, 23);
panel.add(btnNewButton);
JButton button = new JButton("New button");
button.setBounds(322, 172, 89, 23);
panel.add(button);
JButton button_1 = new JButton("New button");
button_1.setBounds(322, 244, 89, 23);
panel.add(button_1);
JLabel backgroundLabel;
try {
backgroundLabel = new JLabel(new ImageIcon(ImageIO.read(new File("images/nature.jpg"))));
backgroundLabel.setBounds(0, 0, 501, 361);
panel.add(backgroundLabel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JPanel panel_1 = new JPanel();
panel_1.setBounds(521, 11, 441, 361);
contentPane.add(panel_1);
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 383, 952, 246);
contentPane.add(panel_2);
}
}

Error with logic or repaint/revalidate Java JFrame

What I am trying to do is this,
when I enter the details it will validate if the textFiled is empty when a button is pressed, if it is empty it will display a message saying that.
Then it will move to the next textFile similar to many web based registration forms,
what I am trying to find out is why wont the message change?
Pasting this code into an ecilpse file and running it should display the simple frame and what I am trying to do.
The message displays on the bottom of the frame when the firstname field is empty,
can anyone explain why it doesn't show the next message when the firstname field containes text and the middlename contains no text?
Most of the logic is at the bottom of the code.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Color;
import javax.swing.UIManager;
import javax.swing.JPanel;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
public class start {
private JFrame frame;
private JTextField tfFirstname;
private JTextField tfMiddlenames;
private JTextField tfSurname;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
start window = new start();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public start() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 505, 429);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
final JPanel panelClientNew = new JPanel();
panelClientNew.setBackground(new Color(0, 102, 255));
panelClientNew.setBounds(10, 11, 469, 299);
frame.getContentPane().add(panelClientNew);
panelClientNew.setLayout(null);
JLabel lblFirstname = new JLabel("Firstname :");
lblFirstname.setHorizontalAlignment(SwingConstants.RIGHT);
lblFirstname.setVerticalAlignment(SwingConstants.BOTTOM);
lblFirstname.setForeground(new Color(255, 255, 255));
lblFirstname.setFont(new Font("Tahoma", Font.BOLD, 13));
lblFirstname.setBounds(10, 16, 163, 14);
panelClientNew.add(lblFirstname);
tfFirstname = new JTextField();
tfFirstname.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfFirstname.setBounds(177, 10, 282, 27);
panelClientNew.add(tfFirstname);
tfFirstname.setColumns(10);
JLabel lblMiddlenames = new JLabel("Middlenames :");
lblMiddlenames.setHorizontalAlignment(SwingConstants.RIGHT);
lblMiddlenames.setForeground(new Color(255, 255, 255));
lblMiddlenames.setFont(new Font("Tahoma", Font.BOLD, 13));
lblMiddlenames.setBounds(10, 47, 163, 14);
panelClientNew.add(lblMiddlenames);
tfMiddlenames = new JTextField();
tfMiddlenames.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfMiddlenames.setBounds(177, 41, 282, 27);
panelClientNew.add(tfMiddlenames);
tfMiddlenames.setColumns(10);
JLabel lblSurname = new JLabel("Surname :");
lblSurname.setHorizontalAlignment(SwingConstants.RIGHT);
lblSurname.setForeground(new Color(255, 255, 255));
lblSurname.setFont(new Font("Tahoma", Font.BOLD, 13));
lblSurname.setBounds(10, 78, 163, 14);
panelClientNew.add(lblSurname);
tfSurname = new JTextField();
tfSurname.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfSurname.setBounds(177, 72, 282, 27);
panelClientNew.add(tfSurname);
tfSurname.setColumns(10);
JButton btnAdd = new JButton("Add");
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
/*
*
*
*
*I am trying to create a message that validates on certain circumstances
*
*
*
*/
if(tfFirstname.getText().equals(null) || tfFirstname.getText().equals("") || tfFirstname.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Firstname :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else if (tfMiddlenames.getText().equals(null) || tfMiddlenames.getText().equals("") || tfMiddlenames.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Middlenames :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else if (tfSurname.getText().equals(null) || tfSurname.getText().equals("") || tfSurname.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Surname :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else {
//Validation has passed
}
}
});
btnAdd.setBounds(370, 265, 89, 23);
panelClientNew.add(btnAdd);
}
}
I recommend that you use an InputVerifier as this will verify that the contents of the JTextField are correct (any way that you wish to define this) before allowing you to even leave the JTextField. Now it won't stop you from pressing other JButtons and whatnot, so you'll need to take other precautions if you have a submit button. An example of a simple InputVerifier that checks to see if the JTextField is empty is shown below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class InputVerifierExample extends JPanel {
public static final Color WARNING_COLOR = Color.red;
private JTextField firstNameField = new JTextField(10);
private JTextField middleNameField = new JTextField(10);
private JTextField lastNameField = new JTextField(10);
private JTextField[] nameFields = {
firstNameField,
middleNameField,
lastNameField };
private JLabel warningLabel = new JLabel(" ");
public InputVerifierExample() {
warningLabel.setOpaque(true);
JPanel namePanel = new JPanel();
namePanel.add(new JLabel("Name:"));
MyInputVerifier verifier = new MyInputVerifier();
for (JTextField field : nameFields) {
field.setInputVerifier(verifier);
namePanel.add(field);
}
namePanel.add(new JButton(new SubmitBtnAction()));
setLayout(new BorderLayout());
add(namePanel, BorderLayout.CENTER);
add(warningLabel, BorderLayout.SOUTH);
}
private class SubmitBtnAction extends AbstractAction {
public SubmitBtnAction() {
super("Submit");
}
#Override
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
}
}
private class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
if (field.getText().trim().isEmpty()) {
warningLabel.setText("Please do not leave this field empty");
warningLabel.setBackground(WARNING_COLOR);
return false;
}
warningLabel.setText("");
warningLabel.setBackground(null);
return true;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("InputVerifier Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new InputVerifierExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
have look at DocumentListener,
on start_up to enable only first JTextField, if any (up to you) character was typed into first JTextField, then enable second JTextField, and so on...,
if you want to filtering, change or replace output came from keyboard the to use DocumentFilter
change background for example to Color.red (from DocumentListeners events), in the case that one of JTextFields contains incorect lenght, data e.g.
agree with HFOE about LayoutManagers

Categories