Error with logic or repaint/revalidate Java JFrame - java

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

Related

java.sql.SQLIntegrityConstraintViolationException: Column 'prenom' cannot be null

I'm new in Java programming so that's why I'm here seeking your kind help stackoverflowers.
I have this problem which I could not find the solution on internet, I hope someone could inform me where is my mistake and how can I fix it.
My problem is that when I try to insert the data, everything goes fine, the window opens, I can insert the data, button looks just fine.
But it gives me this message
java.sql.SQLIntegrityConstraintViolationException: Column 'prenom' cannot be null
Which I assume was a problem with php mySQL, then I changed all variables to NULL, activating the button "Null" for all of them.
It then WORKED, but all informations were saved as "null" in my database, which didn't really solve my problem.
My goal is to insert data (name, lastname, phone, email) into a data base (php mySQL) through eclipse. I did a program which I'm obliged to use window builder to insert that data, so graphical user interface MUST be used
What I expect to happen is to save data normally. Like, name = Mike, lastname = Tyson, phone = +55555, email = mtyson#gmail.com
And it shows in my database, not null message.
Thank you everyone
package interfaceGraphique;
import accesBaseDeDonnees.ClientsBDD;
import entites.Clients;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Color;
public class InterfaceClients extends JFrame {
static InterfaceClients window;
private JPanel contentPane;
private JTextField txtPrenom;
private JTextField txtNom;
private JTextField txtTelephone;
private JTextField txtEmail;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InterfaceClients frame = new InterfaceClients();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public InterfaceClients() {
setBackground(new Color(0, 0, 0));
setOpacity(1.0f);
setTitle("Ajouter un client");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Enregistrer");
btnNewButton.addActionListener(new ActionListener() {
private AbstractButton labelResult;
#Override
public void actionPerformed(ActionEvent e) {
String prenom = txtPrenom.getText();
String nom = txtNom.getText();
String telephone = txtTelephone.getText();
String email = txtEmail.getText();
Clients Clients = new Clients(prenom, nom, telephone, email);
ClientsBDD clientsBDD = new ClientsBDD();
Connection cn = clientsBDD.makeConnection();
clientsBDD.insert(Clients, cn);
clientsBDD.closeConnection(cn);
//labelResult = null;
//labelResult.setText("Client ajoute avec succes");
}
});
btnNewButton.setBounds(45, 227, 112, 23);
contentPane.add(btnNewButton);
txtPrenom = new JTextField();
txtPrenom.setBounds(124, 39, 258, 20);
contentPane.add(txtPrenom);
txtPrenom.setColumns(10);
txtNom = new JTextField();
txtNom.setColumns(10);
txtNom.setBounds(124, 82, 258, 20);
contentPane.add(txtNom);
txtTelephone = new JTextField();
txtTelephone.setColumns(10);
txtTelephone.setBounds(124, 125, 258, 20);
contentPane.add(txtTelephone);
txtEmail = new JTextField();
txtEmail.setColumns(10);
txtEmail.setBounds(124, 166, 258, 20);
contentPane.add(txtEmail);
JLabel lblNewLabel = new JLabel("Prenom");
lblNewLabel.setBounds(45, 42, 67, 14);
contentPane.add(lblNewLabel);
JLabel lblMarque = new JLabel("Nom");
lblMarque.setBounds(45, 85, 46, 14);
contentPane.add(lblMarque);
JLabel lblNewLabel_1_1 = new JLabel("Telephone");
lblNewLabel_1_1.setBounds(45, 128, 67, 14);
contentPane.add(lblNewLabel_1_1);
JLabel lblNewLabel_1_1_1 = new JLabel("Email");
lblNewLabel_1_1_1.setBounds(45, 169, 89, 14);
contentPane.add(lblNewLabel_1_1_1);
JLabel labelResult = new JLabel("");
labelResult.setBounds(194, 229, 227, 16);
contentPane.add(labelResult);
}
}

I am trying to make a registration form with JAVA, but I can't run my code

I have this code and I can't get it to run. I'm new with JAVA. I was trying to make a login and registration form with JAVA swing, and I finished designing GUI part and I also connected the code with mySQL database. But I don't know why that I can't run the code. I tried debugging it, but can't find the bug. I am using eclipse and I also referenced mySQL jar.
Please let me know, if I'm doing anything wrong. Thank you for the help :)
package login_register_form;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.sql.*;
import javax.swing.JComboBox;
public class RegisterPage implements ActionListener{
JFrame frame;
String[] position = {"Admin", "Manager", "Assistant"};
JTextField firstName;
JTextField lastName;
JTextField userName;
JTextField email;
JPasswordField password;
JPasswordField confirmPW;
JButton registerButton;
JButton cancelButton;
JComboBox jobPosition = new JComboBox(position);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RegisterPage window = new RegisterPage();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application. Calling methods from constructor
*/
public RegisterPage() {
createWindow();
initialize();
actionEvent();
}
/**
* Create a main window
*/
public void createWindow() {
frame = new JFrame();
frame.setTitle("Registration Page");
frame.getContentPane().setBackground(Color.GRAY);
frame.setBounds(100, 100, 1113, 806);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
// panel: orange colored background
JPanel panel = new JPanel();
panel.setBackground(new Color(255,165,0,200));
panel.setBounds(300, 150, 500, 472);
frame.getContentPane().add(panel);
panel.setLayout(null);
// label: scaled background
JLabel background = new JLabel("");
background.setBounds(6, 6, 1100, 772);
ImageIcon icon = new ImageIcon(this.getClass().getResource("/background.jpg"));
Image img = icon.getImage();
Image imgScale = img.getScaledInstance(background.getWidth(), background.getHeight(), Image.SCALE_SMOOTH);
ImageIcon scaledIcon = new ImageIcon(imgScale);
background.setIcon(scaledIcon);
frame.getContentPane().add(background);
// title: "Register Page"
JLabel registerPage = new JLabel("Register Page");
registerPage.setFont(new Font("Lucida Grande", Font.BOLD, 19));
registerPage.setBounds(182, 40, 135, 29);
panel.add(registerPage);
// input: first name
firstName = new JTextField();
firstName.setBounds(145, 76, 210, 32);
panel.add(firstName);
firstName.setColumns(10);
// input: last name
lastName = new JTextField();
lastName.setBounds(145, 120, 210, 32);
panel.add(lastName);
lastName.setColumns(10);
// input: user name
userName = new JTextField();
userName.setBounds(145, 164, 210, 32);
panel.add(userName);
userName.setColumns(10);
// input: password
password = new JPasswordField();
password.setBounds(145, 208, 210, 32);
panel.add(password);
// input: confirm password
confirmPW = new JPasswordField();
confirmPW.setBounds(145, 252, 210, 32);
panel.add(confirmPW);
// input: email
email = new JTextField();
email.setBounds(145, 296, 210, 32);
panel.add(email);
email.setColumns(10);
// input: position
jobPosition.setBounds(145, 340, 210, 32);
panel.add(jobPosition);
// button: cancel
JButton cancelButton = new JButton("Cancel");
cancelButton.setBounds(109, 400, 117, 40);
panel.add(cancelButton);
// button: register
JButton registerButton = new JButton("Register");
registerButton.setBounds(275, 400, 117, 40);
panel.add(registerButton);
// label: first name
JLabel fName = new JLabel("First Name");
fName.setBounds(36, 84, 85, 16);
panel.add(fName);
// label: last name
JLabel lName = new JLabel("Last Name");
lName.setBounds(36, 128, 85, 16);
panel.add(lName);
// label: user name
JLabel uName = new JLabel("User Name");
uName.setBounds(36, 172, 85, 16);
panel.add(uName);
// label: password
JLabel pWord = new JLabel("Password");
pWord.setBounds(36, 216, 85, 16);
panel.add(pWord);
// label: re-password
JLabel cPW = new JLabel("Re-Password");
cPW.setBounds(36, 260, 85, 16);
panel.add(cPW);
// label: email
JLabel eMail = new JLabel("Email");
eMail.setBounds(36, 304, 85, 16);
panel.add(eMail);
// label: position
JLabel position = new JLabel("Position");
position.setBounds(36, 347, 101, 16);
panel.add(position);
}
public void actionEvent() {
// Adding action listener to buttons
registerButton.addActionListener(this);
cancelButton.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==registerButton) {
try {
//Creating Connection Object
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase","root", "root");
//Prepared Statement
PreparedStatement Pstatement=connection.prepareStatement("insert into student value(?,?,?,?,?,?)");
// Specifying the values of it's parameter
Pstatement.setString(1, firstName.getText());
Pstatement.setString(2, lastName.getText());
Pstatement.setString(3, userName.getText());
Pstatement.setString(4, password.getText());
Pstatement.setString(5, confirmPW.getText());
Pstatement.setString(6, email.getText());
Pstatement.setString(7, jobPosition.getSelectedItem().toString());
//Checking for the password match
if (password.getText().equalsIgnoreCase(confirmPW.getText())) {
// Executing query
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Registered Successfully");
} else {
JOptionPane.showMessageDialog(null, "Password did not match");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if (e.getSource()==cancelButton) {
// Clearing Fields
firstName.setText("");
lastName.setText("");
userName.setText("");
password.setText("");
confirmPW.setText("");
email.setText("");
jobPosition.setSelectedItem("Admin");
}
}
}

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 ;-)

Exported GUI project won't open/run, exported using eclipse oxygen Java

I've been having trouble with exporting my GUI project from Eclipse Oxygen. At first I tried exporting my project by going to export>Runnable Jar File>Main Class, but when I try and open my program nothing shows up. Then I tried opening the GUI inside its own class by specifying a Main method in there, and I keep getting the error that I put in the title. Any help would be appreciated. I'll post both of my classes here.
Also I used WindowBuilder plugin to build my GUI.
Main class
package me.iran.cryptotracker;
import java.util.ArrayList;
import lombok.Getter;
import me.iran.cryptotracker.window.Window;
public class CryptoTracker {
private static SaveFile saveFile = new SaveFile();
private static ReadFile readFile = new ReadFile();
#Getter
public static ArrayList<Crypto> allCrypto = new ArrayList<Crypto>();
public static void main(String[] args) {
readFile.openFile();
readFile.readFile();
readFile.closeFile();
saveFile.openFile();
saveFile.updateFile();
saveFile.closeFile();
Window.open();
}
}
Window1 Class
package me.iran.cryptotracker.window;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import lombok.Getter;
import me.iran.cryptotracker.Crypto;
import me.iran.cryptotracker.CryptoTracker;
import me.iran.cryptotracker.ReadFile;
import me.iran.cryptotracker.SaveFile;
public class Window {
static #Getter
private JFrame frame;
#Getter
private static JTable table;
/**
* Launch the application.
*/
public static void open() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Window() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBackground(Color.DARK_GRAY);
frame.getContentPane().setBackground(Color.DARK_GRAY);
frame.setBounds(100, 100, 571, 622);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table = new JTable();
table.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
table.setBackground(new Color(169, 169, 169));
Object columnName[] = {"Name", "Date", "Initial Price", "Stock", "URL"};
DefaultTableModel model = new DefaultTableModel(columnName, 0);
model.addRow(columnName);
for(Crypto crypto : CryptoTracker.allCrypto) {
String name = crypto.getName();
String date = crypto.getDate();
double initial = crypto.getInitialPrice();
double amount = crypto.getAmount();
String url = crypto.getUrl();
Object[] data = {name, date, initial + "", amount + "", url};
model.addRow(data);
}
SpringLayout springLayout = new SpringLayout();
springLayout.putConstraint(SpringLayout.NORTH, table, 37, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, table, 30, SpringLayout.WEST, frame.getContentPane());
springLayout.putConstraint(SpringLayout.SOUTH, table, 478, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, table, 464, SpringLayout.WEST, frame.getContentPane());
frame.getContentPane().setLayout(springLayout);
table.setModel(model);
frame.getContentPane().add(table);
JButton btnAdd = new JButton("Add Currency");
springLayout.putConstraint(SpringLayout.NORTH, btnAdd, -48, SpringLayout.SOUTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, btnAdd, 0, SpringLayout.WEST, table);
springLayout.putConstraint(SpringLayout.SOUTH, btnAdd, -25, SpringLayout.SOUTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, btnAdd, 150, SpringLayout.WEST, frame.getContentPane());
frame.getContentPane().add(btnAdd);
btnAdd.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
AddWindow.open();
}
});
}
public static void updateTable(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
Object columnName[] = {"Name", "Date", "Initial Price", "Stock", "URL"};
model.addRow(columnName);
for(Crypto crypto : CryptoTracker.allCrypto) {
String name = crypto.getName();
String date = crypto.getDate();
double initial = crypto.getInitialPrice();
double amount = crypto.getAmount();
String url = crypto.getUrl();
Object[] data = {name, date, initial + "", amount + "", url};
model.addRow(data);
}
table.setModel(model);
}
}
Window 2 Class
package me.iran.cryptotracker.window;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import me.iran.cryptotracker.Crypto;
import me.iran.cryptotracker.CryptoTracker;
import me.iran.cryptotracker.SaveFile;
public class AddWindow {
private JFrame frame;
private JTextField txtName;
private JTextField txtDate;
private JTextField txtCost;
private JTextField txtAmount;
private JTextField txtURL;
private SaveFile saveFile = new SaveFile();
public static void open() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddWindow window = new AddWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AddWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.getContentPane().setLayout(null);
txtName = new JTextField();
txtName.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtName.setBounds(107, 11, 138, 20);
frame.getContentPane().add(txtName);
txtName.setColumns(10);
txtDate = new JTextField();
txtDate.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtDate.setColumns(10);
txtDate.setBounds(107, 44, 138, 20);
frame.getContentPane().add(txtDate);
txtCost = new JTextField();
txtCost.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtCost.setColumns(10);
txtCost.setBounds(107, 75, 138, 20);
frame.getContentPane().add(txtCost);
txtAmount = new JTextField();
txtAmount.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtAmount.setColumns(10);
txtAmount.setBounds(107, 106, 138, 20);
frame.getContentPane().add(txtAmount);
txtURL = new JTextField();
txtURL.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtURL.setColumns(10);
txtURL.setBounds(107, 137, 138, 20);
frame.getContentPane().add(txtURL);
JLabel lblName = new JLabel("Name");
lblName.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblName.setBounds(22, 11, 46, 14);
frame.getContentPane().add(lblName);
JLabel lblDate = new JLabel("Date");
lblDate.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblDate.setBounds(22, 44, 46, 14);
frame.getContentPane().add(lblDate);
JLabel lblInitialCost = new JLabel("Initial Cost");
lblInitialCost.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblInitialCost.setBounds(22, 75, 75, 14);
frame.getContentPane().add(lblInitialCost);
JLabel lblAmount = new JLabel("Amount");
lblAmount.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblAmount.setBounds(22, 106, 63, 14);
frame.getContentPane().add(lblAmount);
JLabel lblUrl = new JLabel("URL");
lblUrl.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblUrl.setBounds(22, 137, 46, 14);
frame.getContentPane().add(lblUrl);
final JLabel lblError = new JLabel("");
lblError.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblError.setBounds(278, 59, 284, 102);
frame.getContentPane().add(lblError);
JButton btnAddCurrency = new JButton("Add Currency");
btnAddCurrency.setBounds(355, 11, 138, 38);
frame.getContentPane().add(btnAddCurrency);
frame.setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 588, 211);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnAddCurrency.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(!txtName.getText().isEmpty() && !txtDate.getText().isEmpty() && !txtURL.getText().isEmpty() && !txtCost.getText().isEmpty() && !txtAmount.getText().isEmpty()) {
String name = txtName.getText();
String date = txtDate.getText();
String url = txtURL.getText();
try {
double initial = Double.parseDouble(txtCost.getText());
double amount = Double.parseDouble(txtAmount.getText());
CryptoTracker.allCrypto.add(new Crypto(name, date, url, initial, amount));
saveFile.openFile();
saveFile.updateFile();
saveFile.closeFile();
frame.setVisible(false);
Window.getFrame().setVisible(true);
Window.updateTable(Window.getTable());
} catch(Exception exc) {
lblError.setText("You have not entered a number in the Initial Cost and/or Amount field");
}
}
}
});
}
}
Turns out that winrar does not like runnable jar files. I had tried Right Clicking the file and running it as a java application SE binary, but it would not work. So after #Adam Horvath mentioned that it worked for him I set the exported jar to default java jar and it opened up just fine.

Window always opens blank even though code is written

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();
}
}

Categories