Multiple JPanel Java Application Windows - java

Edited to make the code work
This might get closed a a dupe, anyway.
I'm trying to create an application for an assignment. I could just do the easy thing and use multiple JFrames but I don't want to do that.
I want an application with a login screen, a customer screen and an admin screen. I though I could just use JPanels and swap them as required, I can remove the login panel but can't add the customer panel.
Curently, the application starts as expected with the login JPanel
But when I click on ok, it's supposed to close the JPanel and open the customer Jpanel, instead it just closes the login panel.
package projFlight;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.BorderLayout;
import javax.swing.UIManager;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class GUIMain {
GUIMainEvent event = new GUIMainEvent(this);
JFrame frame;
GUILoginScreen login = new GUILoginScreen();
GUICustomerScreen custScreen = new GUICustomerScreen();
/**
* Launch the application.
*/
public static void main(String[] args) {
GUIMain window = new GUIMain();
window.frame.setVisible(true);
}
/**
* Create the application.
*/
public GUIMain() {
setLookAndFeel();
initialize();
controller.start();
}
// The thread controlling changes of panels in the main window.
private Thread controller = new Thread() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.getContentPane().add(login);
addLogo(login);
frame.revalidate();
}
});
}
};
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.BLUE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
frame.setBounds(100, 100, 406, 473);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void addLogo(JPanel panel) {
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("C:\\Users\\Phil\\workspace\\projFlight\\Pictures\\WolfLogo.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//The below line was causing the issue
//frame.getContentPane().setLayout(null);
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
picLabel.setBounds(0, 0, 170, 128);
panel.add(picLabel);
//frame.getContentPane().add(login);
login.btnOk.addActionListener(event); //These also shouldn't be here
login.btnCancel.addActionListener(event); //These also shouldn't be here
}
// method to set the look and feel of the GUI
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception exc) {
// ignore error
}
}
}
/**
*
*/
package projFlight;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;
/**
* #author Phil
*
*/
public class GUIMainEvent implements ActionListener{
GUIMain gui;
GUIMainEvent(GUIMain in) {
gui = in;
}
#Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
Object source = event.getSource();
if (source == gui.login.btnOk) {
gui.frame.getContentPane().remove(gui.login);
gui.frame.repaint();
gui.frame.getContentPane().add(gui.custScreen);
gui.custScreen.setVisible(true);
gui.frame.repaint();
gui.frame.revalidate();
} else if (source == gui.login.btnCancel) {
System.exit(0);
}
}
}
package projFlight;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.JPasswordField;
import javax.swing.JButton;
public class GUILoginScreen extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
JTextField tboUsername;
JPasswordField passwordField;
JButton btnOk;
JButton btnCancel;
/**
* Create the panel.
*/
public GUILoginScreen() {
setBackground(Color.DARK_GRAY);
setLayout(null);
setLookAndFeel();
JLabel lblUsername = new JLabel("Username");
lblUsername.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
lblUsername.setBounds(77, 170, 109, 35);
add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
lblPassword.setBounds(77, 235, 109, 35);
add(lblPassword);
tboUsername = new JTextField();
tboUsername.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
tboUsername.setBounds(77, 203, 241, 31);
add(tboUsername);
tboUsername.setColumns(10);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
passwordField.setBounds(77, 268, 241, 31);
add(passwordField);
btnOk = new JButton("OK");
btnOk.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
btnOk.setBounds(77, 349, 109, 35);
add(btnOk);
btnCancel = new JButton("Cancel");
btnCancel.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
btnCancel.setBounds(209, 349, 109, 35);
add(btnCancel);
}
// method to set the look and feel of the GUI
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception exc) {
// ignore error
}
}
}
package projFlight;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
public class GUICustomerScreen extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Create the panel.
*/
String firstName = "Phil";
public GUICustomerScreen() {
setLayout(null);
JLabel lblHello = new JLabel("Hello " + firstName);
lblHello.setFont(new Font("Segoe UI Black", Font.ITALIC, 14));
lblHello.setBounds(184, 11, 107, 27);
add(lblHello);
}
}

I though I could just use JPanels and swap them as required,
You can use a CardLayout to do this.
Check out the section from the Swing tutorial on How to Use CardLayout for a working demo.

You should not use a multiple JFrame. You will encounter a lot of error. Try this use JDialog for your login frame and use GridBagLayout to make your components flexible. setBounds it not flexible sometimes it make components crumbled.
GridBagLayout: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
Sample Code
public class Login extends JDialog{
MainLoginFrame mainloginframe = new MainLoginFrame();
//Constructor
public Login(){
setSize(330,150);
setTitle("Login Sample");
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
getContentPane().add(mainloginframe);
}
public class MainLoginFrame extends JPanel{
//Create Labels
JLabel usernameLabel = new JLabel("Username:");
JLabel passwordLabel = new JLabel("Password:");
//Create TextField
JTextField usernameTextField = new JTextField(10);
JPasswordField passwordPasswordField = new JPasswordField(10);
//Create Button
JButton loginButton = new JButton("Login");
JButton clearButton = new JButton("Clear");
JButton exitButton = new JButton("Exit");
//Create ComboBox
String[] selectUser = {"Administrator","Registrar"};
JComboBox listUser = new JComboBox(selectUser);
//Constraints
GridBagConstraints usernameLabelConstraints = new GridBagConstraints();
GridBagConstraints passwordLabelConstraints = new GridBagConstraints();
GridBagConstraints userTypeConstraints = new GridBagConstraints();
GridBagConstraints usernameTfConstraints = new GridBagConstraints();
GridBagConstraints passwordPfConstraints = new GridBagConstraints();
GridBagConstraints loginConstraints = new GridBagConstraints();
GridBagConstraints clearConstraints = new GridBagConstraints();
GridBagConstraints exitConstraints = new GridBagConstraints();
//Constructor
public MainLoginFrame(){
setLayout(new GridBagLayout());
usernameLabelConstraints.anchor = GridBagConstraints.LINE_START;
usernameLabelConstraints.weightx = 0.5;
usernameLabelConstraints.weighty = 0.5;
add(usernameLabel,usernameLabelConstraints);
passwordLabelConstraints.anchor = GridBagConstraints.LINE_START;
passwordLabelConstraints.weightx = 0.5;
passwordLabelConstraints.weighty = 0.5;
passwordLabelConstraints.gridx = 0;
passwordLabelConstraints.gridy = 1;
add(passwordLabel,passwordLabelConstraints);
usernameTfConstraints.anchor = GridBagConstraints.LINE_START;
usernameTfConstraints.weightx = 0.5;
usernameTfConstraints.weighty = 0.5;
usernameTfConstraints.gridx = 1;
usernameTfConstraints.gridy = 0;
add(usernameTextField,usernameTfConstraints);
passwordPfConstraints.anchor = GridBagConstraints.LINE_START;
passwordPfConstraints.weightx = 0.5;
passwordPfConstraints.weighty = 0.5;
passwordPfConstraints.gridx = 1;
passwordPfConstraints.gridy = 1;
add(passwordPasswordField,passwordPfConstraints);
userTypeConstraints.anchor = GridBagConstraints.LINE_START;
userTypeConstraints.weightx = 0.5;
userTypeConstraints.weighty = 0.5;
userTypeConstraints.gridx = 1;
userTypeConstraints.gridy = 2;
add(listUser,userTypeConstraints);
loginConstraints.anchor = GridBagConstraints.LINE_START;
loginConstraints.weightx = 0.5;
loginConstraints.weighty = 0.5;
loginConstraints.gridx = 1;
loginConstraints.gridy = 3;
add(loginButton,loginConstraints);
clearConstraints.anchor = GridBagConstraints.LINE_START;
clearConstraints.weightx = 0.5;
clearConstraints.weighty = 0.5;
clearConstraints.gridx = 2;
clearConstraints.gridy = 3;
add(clearButton,clearConstraints);
exitConstraints.anchor = GridBagConstraints.LINE_START;
exitConstraints.weightx = 0.5;
exitConstraints.weighty = 0.5;
exitConstraints.gridx = 3;
exitConstraints.gridy = 3;
add(exitButton,exitConstraints);
}

Related

Is there a way to save Strings after the program closes?

I'm trying to make a banking system GUI and I've done well so far but I've run into quite the roadblock. I want to be able to log in, but only if you've previously created an account, but I'm not sure if it's even possible to run my create account class and save the information received for future use since the program will close. I assume it's not possible as I'd need a place to store the username and password for future use, such as a server or something, but I thought I'd ask to see if maybe there was something I could do with an array or something. (P.S. I know I shouldn't use .setLayout(null) but this is just a fun first solo coding project I'm trying to do and I don't understand what people say about it so I'll learn about it later)
Here is my code so far:
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.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class CreateAccount{
private JPanel panel;
private JFrame frame;
private JLabel username;
private JLabel title;
private JLabel passwordLabel;
private JLabel confirmPasswordLabel;
private JLabel alreadyLoggedIn;
private JTextField usernameText;
private JPasswordField passwordText;
private JPasswordField confirmPasswordText;
private JButton confirmButton;
private JButton alreadyLoggedInButton;
private JLabel failureLabel;
public CreateAccount()
{
panel = new JPanel();
frame = new JFrame();
frame.setSize(500,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(panel);
panel.setLayout(null);
Clicklistener click = new Clicklistener();
title = new JLabel("Create New Account");
title.setFont(new Font("Serif", Font.BOLD, 18));
title.setBounds(150,10,200, 25);
panel.add(title);
username = new JLabel("New Username:");
username.setBounds(40,50,100,25);;
username.setFont(new Font("Serif", Font.BOLD, 14));
panel.add(username);
passwordLabel = new JLabel("Create Password:");
passwordLabel.setBounds(30,90,150,25);
passwordLabel.setFont(new Font("Serif", Font.BOLD, 14));
panel.add(passwordLabel);
confirmPasswordLabel = new JLabel("Confirm Password:");
confirmPasswordLabel.setBounds(18,130,150,25);
confirmPasswordLabel.setFont(new Font("Serif", Font.BOLD, 14));
panel.add(confirmPasswordLabel);
alreadyLoggedIn = new JLabel("Already logged in?");
alreadyLoggedIn.setBounds(28,225,200,25);
panel.add(alreadyLoggedIn);
usernameText = new JTextField();
usernameText.setBounds(160,53,225,25);
panel.add(usernameText);
passwordText = new JPasswordField();
passwordText.setBounds(160,93,225,25);
panel.add(passwordText);
confirmPasswordText = new JPasswordField();
confirmPasswordText.setBounds(160,133,225,25);
panel.add(confirmPasswordText);
confirmButton = new JButton("Confirm Login");
confirmButton.setBounds(205,190,125,25);
confirmButton.addActionListener(click);
panel.add(confirmButton);
alreadyLoggedInButton = new JButton("Login Here");
alreadyLoggedInButton.setBounds(140,225, 125,25);
alreadyLoggedInButton.addActionListener(click);
panel.add(alreadyLoggedInButton);
failureLabel = new JLabel("");
failureLabel.setBounds(175,160,400,25);
panel.add(failureLabel);
frame.setVisible(true);
}
public String getUsername() {
return usernameText.getText();
}
public String getPassword() {
return passwordText.getText();
}
private class Clicklistener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String password = passwordText.getText();
String confirmedPassword = confirmPasswordText.getText();
if ((password.equals(confirmedPassword)) && (e.getSource() == confirmButton))
{
frame.dispose();
//call Home Page
}
else if(!password.equals(confirmedPassword)) {
failureLabel.setText("Passwords don't match. Try Again!");
}
if (e.getSource() == alreadyLoggedInButton)
{
frame.dispose();
new Login();
}
}
}
}
My Login class code:
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.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Login {
private JFrame frame;
private JPanel panel;
private JLabel userLabel;
private JTextField userText;
private JLabel passwordLabel;
private JPasswordField passwordText;
private JButton button;
private JLabel success;
public Login(){
panel = new JPanel();
frame = new JFrame();
frame.setSize(350,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.setLayout(null);
userLabel = new JLabel("Username:");
userLabel.setBounds(10, 20, 80, 25); // x , y , width , height
panel.add(userLabel);
userText = new JTextField();
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
passwordLabel = new JLabel("Password:");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField();
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);
button = new JButton("Login");
button.setBounds(135,80,80,25);
button.addActionListener(new Clicklistener());
panel.add(button);
success = new JLabel("");
success.setBounds(10,110,300,25);
panel.add(success);
success.setText("");
frame.setVisible(true);
}
private class Clicklistener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if ((e.getSource() == button))
{
frame.dispose();
}
}
}
}

How to make with JTextField and JButton a menu with name filling functions?

So i am trying to make a Panel where the player configures the names of the players in a local board game.
I want them to be able to add players between 2 and 6 so by default i have made the panel show up 2 JTextField boxes for them to add names and under the second one there is a "+" button to add an extra player. But i dont know how to do that and how to perform such action, when the user presses the "+" button a new JTextField pops up for the player to add a new player name.
I am providing the code i am using for this particular panel but it is necessary i can provide the whole code for my window. Any help is appreciated and thanks in advance.
private void setLocalPanel() {
GridBagConstraints c = new GridBagConstraints();
// localButtonsPanel config
localButtonsPanel = new JPanel(new GridLayout(0, 1, 0, 10));
localButtonsPanel.setOpaque(false);
// nameBox1 config
nameBox1 = new JTextField("Player name");
nameBox1.setBackground(new Color(255, 255, 255));
nameBox1.setEditable(true);
c.ipady = 10;
localButtonsPanel.add(nameBox1, c);
// nameBox2 config
nameBox2 = new JTextField("Player name");
nameBox2.setBackground(new Color(255, 255, 255));
nameBox2.setEditable(true);
localButtonsPanel.add(nameBox2, c);
// + config
extraBtn = new JButton("+");
extraBtn.setForeground(new Color(255, 255, 255));
extraBtn.setFont(new Font("Segoe Script", Font.BOLD,40));
extraBtn.setOpaque(false);
extraBtn.setContentAreaFilled(false);
extraBtn.setBorderPainted(false);
extraBtn.setFocusPainted(false);
localButtonsPanel.add(extraBtn, new GridBagConstraints());
c.gridy = 0;
localPanel.add(localButtonsPanel, c);
// startBtn config
startBtn = new JButton("Start");
startBtn.setForeground(new Color(255, 255, 255));
startBtn.setFont(new Font("Segoe Script", Font.BOLD,40));
startBtn.setOpaque(false);
startBtn.setContentAreaFilled(false);
startBtn.setBorderPainted(false);
startBtn.setFocusPainted(false);
c.gridy = 1;
localPanel.add(startBtn, c);
// localBackBtn config
localBackBtn = new JButton("Back");
localBackBtn.setForeground(new Color(255, 255, 255));
localBackBtn.setFont(new Font("Segoe Script", Font.BOLD,40));
localBackBtn.setOpaque(false);
localBackBtn.setContentAreaFilled(false);
localBackBtn.setBorderPainted(false);
localBackBtn.setFocusPainted(false);
c.gridy = 2;
localPanel.add(localBackBtn, c);
setLocalActions();
}
private void setLocalActions() {
// startBtn config
startBtn.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
startBtn.setForeground(new Color(200, 210, 10));
startBtn.setText("> Start <");
}
public void mouseExited(MouseEvent e) {
startBtn.setForeground(new Color(255, 255, 255));
startBtn.setText("Start");
}
public void mouseClicked(MouseEvent e) {
// nameBox1.getText()
// nameBox2.getText()
localPanel.setVisible(false);
gamePanel.setVisible(true);
}
});
// localBackBtn config
localBackBtn.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
localBackBtn.setForeground(new Color(200, 210, 10));
localBackBtn.setText("> Back <");
}
public void mouseExited(MouseEvent e) {
localBackBtn.setForeground(new Color(255, 255, 255));
localBackBtn.setText("Back");
}
public void mouseClicked(MouseEvent e) {
localPanel.setVisible(false);
playPanel.setVisible(true);
}
});
}
PS. the localPanel has a GridBagLayout.
You need to add an ActionListener to a JButton and not a MouseListener. Refer to How to Use Buttons.
When the + button is clicked, you want to add a new JTextField to the JPanel that contains the fields that allow the user to enter a player's name.
Here is code, adapted from the code in your question, that adds a JTextField when the user clicks the + button. Notes about the code appear after it.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class PlayGame implements ActionListener, Runnable {
private static final int MAX_PLAYERS = 6;
private static final String BACK = "Back";
private static final String PLUS = "+";
private static final String START = "Start";
private ArrayList<JTextField> playerNameTextFields;
private GridBagConstraints gbc;
private JFrame frame;
private JPanel localButtonsPanel;
public PlayGame() {
playerNameTextFields = new ArrayList<>();
}
#Override // java.lang.Runnable
public void run() {
showGui();
}
#Override // java.awt.event.ActionListener
public void actionPerformed(ActionEvent event) {
String actionCommand = event.getActionCommand();
switch (actionCommand) {
case BACK:
// Add code to execute when user clicks 'Back' button.
break;
case PLUS:
addPlayerNameTextField();
localButtonsPanel.revalidate();
localButtonsPanel.repaint();
if (playerNameTextFields.size() >= MAX_PLAYERS) {
((JButton) event.getSource()).setEnabled(false);
}
break;
case START:
// Add code to execute when user clicks 'Start' button.
break;
default:
System.out.println("Not implemented: " + actionCommand);
}
}
private void addPlayerNameTextField() {
JTextField playerNameTextField = new JTextField(10);
playerNameTextField.setName("player" + playerNameTextFields.size());
playerNameTextFields.add(playerNameTextField);
gbc.gridy++;
localButtonsPanel.add(playerNameTextField, gbc);
}
private JPanel createLocalPanel() {
JPanel localPanel = new JPanel(new GridBagLayout());
localPanel.setOpaque(false);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets.top = 10;
localButtonsPanel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = -1;
gbc.insets.top = 10;
localButtonsPanel.setPreferredSize(new Dimension(120, 200));
localButtonsPanel.setOpaque(false);
addPlayerNameTextField();
addPlayerNameTextField();
localPanel.add(localButtonsPanel, c);
c.gridy = 1;
JButton extraBtn = new JButton(PLUS);
extraBtn.setFont(new Font("Segoe Script", Font.BOLD,40));
extraBtn.setForeground(Color.WHITE);
extraBtn.setContentAreaFilled(false);
extraBtn.setBorderPainted(false);
extraBtn.setFocusPainted(false);
extraBtn.addActionListener(this);
extraBtn.setToolTipText("Add another player");
localPanel.add(extraBtn, c);
c.gridy = 2;
JButton startBtn = new JButton(START);
startBtn.setForeground(Color.WHITE);
startBtn.setFont(new Font("Segoe Script", Font.BOLD,40));
startBtn.setContentAreaFilled(false);
startBtn.setBorderPainted(false);
startBtn.setFocusPainted(false);
startBtn.addActionListener(this);
localPanel.add(startBtn, c);
JButton localBackBtn = new JButton(BACK);
localBackBtn.setForeground(Color.WHITE);
localBackBtn.setFont(new Font("Segoe Script", Font.BOLD,40));
localBackBtn.setContentAreaFilled(false);
localBackBtn.setBorderPainted(false);
localBackBtn.setFocusPainted(false);
localBackBtn.addActionListener(this);
c.gridy = 3;
localPanel.add(localBackBtn, c);
return localPanel;
}
private void showGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.DARK_GRAY);
frame.add(createLocalPanel(), BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* Start here.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new PlayGame());
}
}
Note that when you call setContentAreaFilled(false) on a JButton, there is no need to also call setOpaque(false).
Instead of new java.awt.Color(255, 255, 255) you can use the constant WHITE in class java.awt.Color.
GridLayout and GridBagLayout are not the same. Refer to Laying Out Components Within a Container
Rather than use a background image like you have done, I simply set the background color to dark gray.

Java JPanel and JLabel's

I am trying to create 2 sets of JLabels, one set would include a name and the second set would include values. The values get pulled from a database and get displayed to the second set of JLabels.
I cant seem how to line up the 2 sets of JLabels so that the set with the names would be on the left side of the panel and the set with the values would be directly to the right. I know my gridlayout has a factor in it I just dont know what it should be.
package Frames;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import Application.Main;
public class AccountFrame extends JPanel implements PropertyChangeListener, ActionListener {
private static JFrame accountFrame;
private JLabel firstNameLabel;
private JLabel lastNameLabel;
private JLabel dobLabel;
private JLabel emailLabel;
private JLabel usernameLabel;
private JLabel passwordLabel;
private static String firstNameLabelText = "First Name: ";
private static String lastNameLabelText = "Last Name: ";
private static String dobLabelText = "Date Of Birth: ";
private static String emailLabelText = "Email: ";
private static String usernameLabelText = "Username: ";
private static String passwordLabelText = "Password: ";
private static JButton editButton;
private static JButton closeButton;
public AccountFrame() {
super(new BorderLayout());
firstNameLabel = new JLabel(firstNameLabelText);
firstNameLabel.setForeground(Color.WHITE);
firstNameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
lastNameLabel = new JLabel(lastNameLabelText);
lastNameLabel.setForeground(Color.WHITE);
lastNameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
dobLabel = new JLabel(dobLabelText);
dobLabel.setForeground(Color.WHITE);
dobLabel.setFont(new Font("Andalus", Font.BOLD, 18));
emailLabel = new JLabel(emailLabelText);
emailLabel.setForeground(Color.WHITE);
emailLabel.setFont(new Font("Andalus", Font.BOLD, 18));
usernameLabel = new JLabel(usernameLabelText);
usernameLabel.setForeground(Color.WHITE);
usernameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
passwordLabel = new JLabel(passwordLabelText);
passwordLabel.setForeground(Color.WHITE);
passwordLabel.setFont(new Font("Andalus", Font.BOLD, 18));
editButton = new JButton("Edit");
editButton.setBackground(new Color(129,13,13));
editButton.setForeground(Color.WHITE);
editButton.setFocusPainted(false);
editButton.setFont(new Font("Andalus", Font.BOLD, 18));
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//EDIT ACCOUNT INFORMATION.
}
});
closeButton = new JButton("Close");
closeButton.setBackground(new Color(129,13,13));
closeButton.setForeground(Color.WHITE);
closeButton.setFocusPainted(false);
closeButton.setFont(new Font("Andalus", Font.BOLD, 18));
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
accountFrame.dispose();
}
});
TitledBorder accountPanelBorder = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.WHITE), "Account", TitledBorder.CENTER , TitledBorder.TOP, new Font("Andalus", Font.BOLD, 18));
accountPanelBorder.setTitleColor(Color.WHITE);
//this is where the labels need to have values
//added on to the string to get values from the current character.
JPanel accountPanel = new JPanel(new GridLayout(0, 1));
accountPanel.add(firstNameLabel, BorderLayout.WEST);
accountPanel.add(lastNameLabel, BorderLayout.WEST);
accountPanel.add(dobLabel, BorderLayout.WEST);
accountPanel.add(emailLabel, BorderLayout.WEST);
accountPanel.add(usernameLabel, BorderLayout.WEST);
accountPanel.add(passwordLabel, BorderLayout.WEST);
accountPanel.setBackground(new Color(82,80,80));
accountPanel.setBorder(accountPanelBorder);
accountPanel.setPreferredSize(new Dimension(400,200));
// JPanel accountValuesPanel = new JPanel(new GridLayout(0, 1));
// accountValuesPanel.add(firstNameValue);
// accountValuesPanel.setBackground(new Color(82,80,80));
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttons.add(editButton);
buttons.add(closeButton);
buttons.setBackground(new Color(82,80,80));
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
setBackground(new Color(82,80,80));
add(accountPanel, BorderLayout.WEST);
add(buttons, BorderLayout.SOUTH);
// add(accountValuesPanel, BorderLayout.LINE_END);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
public static void createAndShowGUI() {
accountFrame = new JFrame("OVERRATED");
accountFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
accountFrame.setBackground(Color.red);
accountFrame.add(new AccountFrame());
accountFrame.setVisible(true);
accountFrame.pack();
accountFrame.setLocationRelativeTo(null);
accountFrame.setTitle("OVERRATED");
accountFrame.setResizable(false);
//startupFrame.setIconImage(new ImageIcon().getImage());
JFrame.setDefaultLookAndFeelDecorated(false);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
AccountFrame a = new AccountFrame();
a.createAndShowGUI();
}
}
First of all, even though your accountPanel layout is gridLayout, you have used it is BorderLayout:
JPanel accountPanel = new JPanel(new GridLayout(0, 1));
accountPanel.add(firstNameLabel, BorderLayout.WEST); // BorderLayout.WEST wrong
My suggestion, You should use gridbaglayout for it. GridbagLayout may look difficult to learn but it is actually quite logic.
I have changed your code a little bit.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
#SuppressWarnings("serial")
public class AccountFrame extends JPanel implements PropertyChangeListener,
ActionListener {
private static JFrame accountFrame;
private JTextField firstNameTextField, lastNameTextField, dobTextField,
emailTextField, userNameTextField;
private JPasswordField passwordPasswordField;
private JLabel firstNameLabel;
private JLabel lastNameLabel;
private JLabel dobLabel;
private JLabel emailLabel;
private JLabel usernameLabel;
private JLabel passwordLabel;
private static String firstNameLabelText = "First Name: ";
private static String lastNameLabelText = "Last Name: ";
private static String dobLabelText = "Date Of Birth: ";
private static String emailLabelText = "Email: ";
private static String usernameLabelText = "Username: ";
private static String passwordLabelText = "Password: ";
private static JButton editButton;
private static JButton closeButton;
public AccountFrame() {
super(new BorderLayout());
firstNameLabel = new JLabel(firstNameLabelText);
firstNameLabel.setForeground(Color.WHITE);
firstNameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
lastNameLabel = new JLabel(lastNameLabelText);
lastNameLabel.setForeground(Color.WHITE);
lastNameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
dobLabel = new JLabel(dobLabelText);
dobLabel.setForeground(Color.WHITE);
dobLabel.setFont(new Font("Andalus", Font.BOLD, 18));
emailLabel = new JLabel(emailLabelText);
emailLabel.setForeground(Color.WHITE);
emailLabel.setFont(new Font("Andalus", Font.BOLD, 18));
usernameLabel = new JLabel(usernameLabelText);
usernameLabel.setForeground(Color.WHITE);
usernameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
passwordLabel = new JLabel(passwordLabelText);
passwordLabel.setForeground(Color.WHITE);
passwordLabel.setFont(new Font("Andalus", Font.BOLD, 18));
// lets create JTextFields and a JPasswordField
firstNameTextField = new JTextField(20);
lastNameTextField = new JTextField(20);
dobTextField = new JTextField(20);
emailTextField = new JTextField(20);
userNameTextField = new JTextField(20);
passwordPasswordField = new JPasswordField(20);
editButton = new JButton("Edit");
editButton.setBackground(new Color(129, 13, 13));
editButton.setForeground(Color.WHITE);
editButton.setFocusPainted(false);
editButton.setFont(new Font("Andalus", Font.BOLD, 18));
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// EDIT ACCOUNT INFORMATION.
}
});
closeButton = new JButton("Close");
closeButton.setBackground(new Color(129, 13, 13));
closeButton.setForeground(Color.WHITE);
closeButton.setFocusPainted(false);
closeButton.setFont(new Font("Andalus", Font.BOLD, 18));
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
accountFrame.dispose();
}
});
TitledBorder accountPanelBorder = BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.WHITE), "Account",
TitledBorder.CENTER, TitledBorder.TOP, new Font("Andalus",
Font.BOLD, 18));
accountPanelBorder.setTitleColor(Color.WHITE);
// this is where the labels need to have values
// added on to the string to get values from the current character.
JPanel accountPanel = new JPanel(new GridBagLayout());
accountPanel.setBackground(new Color(82, 80, 80));
accountPanel.setBorder(accountPanelBorder);
accountPanel.setPreferredSize(new Dimension(400, 200));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(0, 0, 0, 0);
// lets add labels and textfields
// 1. row
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(firstNameLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(firstNameTextField, gbc);
// 2. row
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(lastNameLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(lastNameTextField, gbc);
// 3. row
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(dobLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(dobTextField, gbc);
// 4. row
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(emailLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(emailTextField, gbc);
// 5. row
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(usernameLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(userNameTextField, gbc);
// 6. row
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(passwordLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(passwordPasswordField, gbc);
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttons.add(editButton);
buttons.add(closeButton);
buttons.setBackground(new Color(82, 80, 80));
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
setBackground(new Color(82, 80, 80));
add(accountPanel, BorderLayout.WEST);
add(buttons, BorderLayout.SOUTH);
// add(accountValuesPanel, BorderLayout.LINE_END);
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event dispatch thread.
*/
public static void createAndShowGUI() {
accountFrame = new JFrame("OVERRATED");
accountFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
accountFrame.setBackground(Color.red);
accountFrame.add(new AccountFrame());
accountFrame.pack();
accountFrame.setTitle("OVERRATED");
accountFrame.setResizable(false);
accountFrame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
AccountFrame a = new AccountFrame();
a.createAndShowGUI();
}
}
Your issue is that your GridLayout only has 1 column. You need to create your GridLayout like this: new GridLayout(0, 2). Below is a small runnable example that lays out pairs of JLabels right next to each other.
public static void main(String[] args) {
JFrame f = new JFrame("Good day");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 250);
JPanel panel = new JPanel(new GridLayout(0, 2));
JLabel left = new JLabel("Foo");
JLabel right = new JLabel(("Bar"));
JLabel hello = new JLabel("Hello");
JLabel world = new JLabel("World");
panel.add(left);
panel.add(right);
panel.add(hello);
panel.add(world);
f.add(panel);
f.setVisible(true);
}

my japplet compiles, but it comes up as blank in applet viewer

import javax.swing.BoxLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
public class LoginApplet extends JApplet { /**
*
*/
private static final long serialVersionUID = 1L;
JLabel titlePage;
JLabel[] txt;
JTextField[] jtf;
JButton accept, decline;
JPanel jp1, jp2, jp3;
public void init(){
setSize(400,400);
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
String[] labeltxt = {"Username", "Password"};
titlePage = new JLabel("Create New Account");
txt = new JLabel[2];
jtf = new JTextField[2];
accept = new JButton("Create");
decline = new JButton("Decline");
jp1 = new JPanel();
jp2 = new JPanel(new GridBagLayout());
jp3 = new JPanel();
for(int i=0; i<labeltxt.length; i++) {
txt[i] = new JLabel();
txt[i].setText(labeltxt[i]);
jp2.add(txt[i], firstCol);
jtf[i] = new JTextField();
jtf[i].setPreferredSize(new Dimension(300, 20));
jp2.add(jtf[i], lastCol);
}
jp1.add(titlePage);
jp3.add(accept);
jp3.add(decline);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp1);
content.add(jp2);
content.add(jp3);
}
public void setVisible(boolean b) {
// TODO Auto-generated method stub
}
}
Hi guys.. This code I have posted up is from class LoginApplet which gets called by an ActionPerformed from another class.... I had no problem with it set as JFrame (the rubric for this assignment was in JApplet). Now when I converted it to JApplet problems show up. I am not familiar with JApplet, and is there anything wrong with the code showing up as blank when ran?
Get rid of
public void setVisible(boolean b) {
// TODO Auto-generated method stub
}
It's preventing the applet from thinking it's visible...

JTextField input and output

I'm trying to design a Mile to Nautical Mile calculator in Java.
I was able to create and run it okay through the console, but i'm having trouble learning how to do it in JFrames.
what im basically wanting to do is:
Have two text fields and a button, one text field miles and one for nautical miles, when you enter the amount into one then press the button the result will display in the other field.
I've pasted my code below
Not really sure what to do next
package Mile_Conversion;
import java.awt.*;
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.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class OwnWindow implements ActionListener{
public static void main(String[] args) {
MyJFrame();
}
public static void MyJFrame() {
//JLabel
JLabel start = new JLabel("Enter the amount below to calculate");
start.setBounds(/*x*/70, -65/*Y*/, 270, 150); // x, y, width, height x across, y down
JLabel milecon = new JLabel("Miles");
milecon.setBounds(154, 55, 50, 150);
JLabel nautcon = new JLabel("Nautical Miles");
nautcon.setBounds(135, -15, 150, 150);
//JTextField
JTextField miles = new JTextField();
miles.setBounds(100, 140, 150, 25);
JTextField nautical = new JTextField();
nautical.setBounds(100, 70, 150, 25);
double mile, nautmile;
/*
mile = nautmile * 0.868;
nautmile = mile * 1.150;
*/
//JButton
JButton convert = new JButton("Convert");
convert.setBounds(250, 200, 90, 25);
//JFrame
JFrame window = new JFrame("Milage Conversion");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 300);
window.setVisible(true);
window.setLayout(null);
window.setResizable(false);
window.add(start);
window.add(miles);
window.add(nautical);
window.add(convert);
window.add(milecon);
window.add(nautcon);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
Welcome to the wonderful world of variable fonts, resolutions and DPI, where what it looks like on your screen will never match any one elses (okay, that's an exaggeration, but it feels like it :P)
In this world, layout managers are you friend. They will save you many, many, many hours of frustration and torment.
I'd recommend you have a read through;
Using Layout Managers
A Visual Guide to Layout Managers
This is my take on what you are trying to do...
public class TestConvertDistance {
public static void main(String[] args) {
new TestConvertDistance();
}
public TestConvertDistance() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DistancePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class DistancePane extends JPanel {
private JLabel lblInstruct;
private JLabel lblMiles;
private JLabel lblNauticalMiles;
private JTextField fldMiles;
private JTextField fldNauticalMiles;
private JButton btnCalculate;
public DistancePane() {
lblInstruct = new JLabel("Enter the amount below to calculate");
lblMiles = new JLabel("Miles");
lblNauticalMiles = new JLabel("Nautical Miles");
fldMiles = new JTextField(8);
fldNauticalMiles = new JTextField(8);
btnCalculate = new JButton("Convert");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(lblInstruct, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = 1;
add(lblMiles, gbc);
gbc.gridy++;
add(lblNauticalMiles, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
add(fldMiles, gbc);
gbc.gridy++;
add(fldNauticalMiles, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(btnCalculate, gbc);
btnCalculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do your calculation here...
}
});
}
}
}
Note, I've used GridBagLayout, this is one of the most powerful and complicated layout managers in the core API, so don't get worried if at first it seems confusion ;)
write your code for conversion inside actionPerformed method:
Take input from first JTextField miles
Parse it to int or float( as JTextFields getText() method returns String)
Do the conversion
set the converted value to the other JTextField nautical using nautical.setText(); method
Here is my version of it. It probably isn't perfect and doesn't have any exception handling:
import java.awt.*;
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.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class OwnWindow implements ActionListener
{
JLabel start;
JLabel milecon;
JLabel nautcon;
JTextField miles;
JTextField nautical;
JButton convert;
JFrame window;
double mile, nautmile;
public static void main(String[] args)
{
OwnWindow obj = new OwnWindow();
}
public OwnWindow()
{
start = new JLabel("Enter the amount below to calculate");
start.setBounds(/*x*/70, -65/*Y*/, 270, 150); // x, y, width, height x across, y down
milecon = new JLabel("Miles");
milecon.setBounds(154, 55, 50, 150);
nautcon = new JLabel("Nautical Miles");
nautcon.setBounds(135, -15, 150, 150);
miles = new JTextField();
miles.setBounds(100, 140, 150, 25);
nautical = new JTextField();
nautical.setBounds(100, 70, 150, 25);
convert = new JButton("Convert");
convert.setBounds(250, 200, 90, 25);
convert.addActionListener(this);
window = new JFrame("Milage Conversion");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 300);
window.setVisible(true);
window.setLayout(null);
window.setResizable(false);
window.add(start);
window.add(miles);
window.add(nautical);
window.add(convert);
window.add(milecon);
window.add(nautcon);
}
#Override
public void actionPerformed(ActionEvent e)
{
String strNaut = nautical.getText();
String strMile = miles.getText();
//this means the user wants to convert nautical to normal
if(strNaut.length() > 0)
{
nautmile = Double.parseDouble(strNaut);
miles.setText(nautmile*0.868 + "");
}
else if(strMile.length() > 0)
{
mile = Double.parseDouble(strMile);
nautical.setText(mile*1.150 + "");
}
}
}

Categories