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);
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
I am new to Java and want to start with making simple user input fields without MySQL.
Until now I got two problems that I can't solve.
First of all, how to get inputs from JCheckBox and JRadioButton?
And I get these user inputs in console, but how to get it to show just below the registration form in panel?
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Login implements ActionListener {
private static JTextField nameText;
private static JTextField emailText;
private static JPasswordField passwordText;
private static JPasswordField confirmPasswordText;
public void loginForm() {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setTitle("Registration Form");
panel.setLayout(null);
JLabel headingLabel = new JLabel("REGISTRATION FORM");
headingLabel.setBounds(285, 25, 160, 25);
panel.add(headingLabel);
JLabel nameLabel = new JLabel("Name");
nameLabel.setBounds(150, 70, 80, 25);
panel.add(nameLabel);
nameText = new JTextField(20);
nameText.setBounds(270, 70, 165, 25);
panel.add(nameText);
JRadioButton maleButton = new JRadioButton("Male");
maleButton.setBounds(270, 100, 60, 25);
panel.add(maleButton);
JRadioButton femaleButton = new JRadioButton("Female");
femaleButton.setBounds(370, 100, 100, 25);
panel.add(femaleButton);
JLabel emailLabel = new JLabel("E-mail");
emailLabel.setBounds(150, 130, 80, 25);
panel.add(emailLabel);
emailText = new JTextField(20);
emailText.setBounds(270, 130, 165, 25);
panel.add(emailText);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(150, 160, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField();
passwordText.setBounds(270, 160, 165, 25);
panel.add(passwordText);
JLabel confirmPasswordLabel = new JLabel("Confirm password");
confirmPasswordLabel.setBounds(150, 190, 120, 25);
panel.add(confirmPasswordLabel);
confirmPasswordText = new JPasswordField();
confirmPasswordText.setBounds(270, 190, 165, 25);
panel.add(confirmPasswordText);
JCheckBox c1 = new JCheckBox("I agree to websites rules!");
c1.setBounds(260, 220, 200, 25);
panel.add(c1);
JButton button = new JButton("Submit");
button.setBounds(300, 260, 100, 25);
button.addActionListener(new Login());
panel.add(button);
JLabel success = new JLabel();
success.setBounds(260, 290, 300, 25);
panel.add(success);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String name = nameText.getText();
// String male = maleButton.getText();
// String female = femaleButton.getText();
String email = emailText.getText();
String password = passwordText.getText();
String confirmPassword = confirmPasswordText.getText();
// String c1 = String.valueOf(JCheckBox.getDefaultLocale());
System.out.println(name + ", " + email + ", " + password + ", " + confirmPassword);
}
}
Below code is a rewrite of your GUI application.
import java.awt.BorderLayout;
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.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Login {
private JCheckBox c1;
private JPasswordField confirmPasswordText;
private JPasswordField passwordText;
private JRadioButton femaleButton;
private JRadioButton maleButton;
private JTextArea textArea;
private JTextField emailText;
private JTextField nameText;
private void createAndDisplayGui() {
JFrame frame = new JFrame("Registration");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createHeading(), BorderLayout.PAGE_START);
frame.add(createForm(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JButton createButton(String text,
int mnemonic,
ActionListener listener) {
JButton button = new JButton(text);
button.setMnemonic(mnemonic);
button.addActionListener(listener);
return button;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton("Submit", KeyEvent.VK_S, this::submit));
return buttonsPanel;
}
private JPanel createForm() {
JPanel form = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets.bottom = 5;
gbc.insets.left = 10;
gbc.insets.right = 10;
gbc.insets.top = 0;
JLabel nameLabel = new JLabel("Name");
form.add(nameLabel, gbc);
gbc.gridx = 1;
nameText = new JTextField(16);
form.add(nameText, gbc);
gbc.gridy = 1;
form.add(createRadioButtons(), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
JLabel eMailLabel = new JLabel("E-mail");
form.add(eMailLabel, gbc);
gbc.gridx = 1;
emailText = new JTextField(16);
form.add(emailText, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
JLabel passwordLabel = new JLabel("Password");
form.add(passwordLabel, gbc);
gbc.gridx = 1;
passwordText = new JPasswordField(16);
form.add(passwordText, gbc);
gbc.gridx = 0;
gbc.gridy = 4;
JLabel confirmLabel = new JLabel("Confirm password");
form.add(confirmLabel, gbc);
gbc.gridx = 1;
confirmPasswordText = new JPasswordField(16);
form.add(confirmPasswordText, gbc);
gbc.gridx = 1;
gbc.gridy = 5;
c1 = new JCheckBox("I agree to websites rules!");
form.add(c1, gbc);
gbc.gridx = 1;
gbc.gridy = 6;
textArea = new JTextArea(2, 30);
textArea.setEditable(false);
textArea.setFocusable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
form.add(scrollPane, gbc);
return form;
}
private JPanel createHeading() {
JPanel heading = new JPanel();
JLabel label = new JLabel("REGISTRATION FORM");
label.setFont(label.getFont().deriveFont(Font.BOLD, 14.0f));
heading.add(label);
return heading;
}
private JPanel createRadioButtons() {
JPanel radioButtons = new JPanel();
ButtonGroup group = new ButtonGroup();
maleButton = new JRadioButton("Male");
maleButton.setSelected(true);
radioButtons.add(maleButton);
group.add(maleButton);
femaleButton = new JRadioButton("Female");
radioButtons.add(femaleButton);
group.add(femaleButton);
return radioButtons;
}
private void submit(ActionEvent event) {
textArea.setText("");
String name = nameText.getText();
textArea.append(name);
String gender;
if (maleButton.isSelected()) {
gender = "male";
}
else {
gender = "female";
}
textArea.append(", " + gender);
String email = emailText.getText();
textArea.append(", " + email);
String password = new String(passwordText.getPassword());
textArea.append(", " + password);
String confirmPassword = new String(confirmPasswordText.getPassword());
textArea.append(", " + confirmPassword);
textArea.append(", " + c1.isSelected());
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new Login().createAndDisplayGui());
}
}
Usually you use a layout manager rather than setting it to null. Refer to Laying Out Components Within a Container
You need to group JRadioButtons in a ButtonGroup to ensure that only one can be selected. Refer to How to Use Buttons, Check Boxes, and Radio Buttons
Method getText is deprecated for JPasswordField. Refer to How to Use Password Fields.
I chose to display the user inputs in a JTextArea in a JScrollPane but there are other options. Refer to Using Text Components and How to Use Scroll Panes.
Since Java 8, the ActionListener interface can be implemented via a method reference.
How do I add a break to put my "Make pokemon" buttons and textarea not in the same row as my "Pokemon choice." I'm trying to put an empty JLabel, but I don't think it works.
public class PokemonPanel extends JPanel {
private JLabel lTitle = new JLabel("Pokemon");
private JLabel lMsg = new JLabel(" ");
private JButton bDone = new JButton(" Make Pokemon ");
private JButton bClear = new JButton(" Clear ");
private JPanel topSubPanel = new JPanel();
private JPanel centerSubPanel = new JPanel();
private JPanel bottomSubPanel = new JPanel();
private GUIListener listener = new GUIListener();
private Choice chSpe = new Choice();
private JLabel lEmp = new JLabel(" ");
private PokemonGUILizylf st;
private final int capacity = 10;
private PokemonGUILizylf[ ] stArr = new PokemonGUILizylf[capacity];
private int count = 0;
private String sOut = new String("");
private JTextArea textArea = new JTextArea(400, 500);
private JTextArea textArea2 = new JTextArea(400, 500);
private JScrollPane scroll = new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public PokemonPanel() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(400, 500));
topSubPanel.setBackground(Color.cyan);
centerSubPanel.setBackground(Color.white);
bottomSubPanel.setBackground(Color.white);
topSubPanel.add(lTitle);
this.add("North", topSubPanel);
JLabel lSpe = new JLabel("Pokemon Available: ");
JLabel lEmp = new JLabel(" ");
JLabel lNew = new JLabel("New Pokemon: ");
//add choices to the choice dropdown list
chSpe.add("Choose");
chSpe.add("Bulbasaur");
chSpe.add("Venusaur");
chSpe.add("Ivysaur");
chSpe.add("Squirtle");
chSpe.add("Wartortle");
chSpe.add("Blastoise");
chSpe.add("Charmander");
chSpe.add("Charmeleon");
chSpe.add("Charizard");
centerSubPanel.add(lSpe);
centerSubPanel.add(chSpe);
centerSubPanel.add(lEmp);
centerSubPanel.add(bDone);
centerSubPanel.add(lNew);
textArea.setPreferredSize(new Dimension(500, 200));
textArea.setEditable(false);
textArea2.setPreferredSize(new Dimension(500, 200));
textArea2.setEditable(false);
textArea.setBackground(Color.white);
textArea.setEditable(false);
scroll.setBorder(null);
centerSubPanel.add(scroll); //add scrollPane to panel, textArea inside.
scroll.getVerticalScrollBar().setPreferredSize(new Dimension(10, 0));
add("Center", centerSubPanel);
bottomSubPanel.add(lMsg);
bDone.addActionListener(listener); //add listener to button
bottomSubPanel.add(bClear);
bClear.addActionListener(listener); //add listener to button
//add bottomSubPanel sub-panel to South area of main panel
add("South", bottomSubPanel);
}
This is what my GUI looks like:
enter image description here
But it should show like this:
enter image description here
Can someone explain to me how I can do that?
Use a different layout manager (other then default FlowLayout which JPanel uses)
See Laying Out Components Within a Container for more details.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new PokemonPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PokemonPanel extends JPanel {
private JLabel lTitle = new JLabel("Pokemon");
// private JLabel lMsg = new JLabel(" ");
private JButton bDone = new JButton("Make Pokemon ");
private JButton bClear = new JButton("Clear");
private JPanel topSubPanel = new JPanel();
private JPanel centerSubPanel = new JPanel(new GridBagLayout());
private JPanel bottomSubPanel = new JPanel();
// private GUIListener listener = new GUIListener();
private JComboBox<String> chSpe = new JComboBox<>();
private JLabel lEmp = new JLabel(" ");
// private PokemonGUILizylf st;
private final int capacity = 10;
// private PokemonGUILizylf[] stArr = new PokemonGUILizylf[capacity];
// private int count = 0;
// private String sOut = new String("");
// private JTextArea textArea = new JTextArea(400, 500);
// private JTextArea textArea2 = new JTextArea(400, 500);
//
// private JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
// JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public PokemonPanel() {
this.setLayout(new BorderLayout());
// this.setPreferredSize(new Dimension(400, 500));
topSubPanel.setBackground(Color.cyan);
centerSubPanel.setBackground(Color.white);
bottomSubPanel.setBackground(Color.white);
topSubPanel.add(lTitle);
this.add("North", topSubPanel);
JLabel lSpe = new JLabel("Pokemon Available: ");
JLabel lNew = new JLabel("New Pokemon: ");
//add choices to the choice dropdown list
DefaultComboBoxModel<String> chSpeModel= new DefaultComboBoxModel<>();
chSpeModel.addElement("Choose");
chSpeModel.addElement("Bulbasaur");
chSpeModel.addElement("Venusaur");
chSpeModel.addElement("Ivysaur");
chSpeModel.addElement("Squirtle");
chSpeModel.addElement("Wartortle");
chSpeModel.addElement("Blastoise");
chSpeModel.addElement("Charmander");
chSpeModel.addElement("Charmeleon");
chSpeModel.addElement("Charizard");
chSpe.setModel(chSpeModel);
centerSubPanel.setBorder(new EmptyBorder(4, 4, 4, 4));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.LINE_END;
centerSubPanel.add(lSpe, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
centerSubPanel.add(chSpe);
gbc.anchor = GridBagConstraints.NORTH;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy++;
centerSubPanel.add(bDone, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
centerSubPanel.add(lNew, gbc);
gbc.gridx++;
gbc.gridheight = gbc.REMAINDER;
centerSubPanel.add(new JScrollPane(new JTextArea(10, 10)), gbc);
// textArea.setEditable(false);
// textArea2.setEditable(false);
//
// textArea.setBackground(Color.white);
// textArea.setEditable(false);
// scroll.setBorder(null);
// centerSubPanel.add(scroll); //add scrollPane to panel, textArea inside.
// scroll.getVerticalScrollBar().setPreferredSize(new Dimension(10, 0));
add("Center", centerSubPanel);
// bottomSubPanel.add(lMsg);
// bDone.addActionListener(listener); //add listener to button
bottomSubPanel.add(bClear);
// bClear.addActionListener(listener); //add listener to button
//add bottomSubPanel sub-panel to South area of main panel
add("South", bottomSubPanel);
}
}
}
Also, avoid using setPreferredSize, let the layout managers do their job. In the example I'm used insets (from GridBagConstraints) and an EmptyBorder to add some additional space around the components
Also, be careful of using AWT components (ie Choice), they don't always play nicely with Swing. In this case, you should be using JComboBox
I want to access JTextField but I can't because its in another class. My GUI and my ActionListener class are separated but I want to access the JTextField from another class and I have problem doing so. Sorry that the code is quite lenghty, when I run this it gives me nullpointer exception. How should I access the JTextField from the BusinessLogic class? Here is my code:
BankApp class:
import java.awt.CardLayout;
import static java.awt.Component.CENTER_ALIGNMENT;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class BankApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
BankGUI object1;
object1 = new BankGUI();
object1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
object1.setSize(600, 400);
object1.setLocationRelativeTo(null);
object1.setVisible(true);
}
});
}
}
BankGUI:
import java.awt.*;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
public class BankGUI extends JFrame {
private static CardLayoutBankNavigationController controller;
public static JTextField NameField;
public BankGUI() {
super("Banking App");
CardLayout layout = new CardLayout();
setLayout(layout);
controller = new CardLayoutBankNavigationController(getContentPane(), layout);
add("Main Menu", createMainMenu());
add("Register", RegisterView("Register"));
add("Login", LoginView("Login"));
add("About", About("About"));
add("Exit", otherView("Exit"));
controller.setView("Main Menu");
}
public static JPanel About(String named) {
JPanel About= new JPanel(new GridBagLayout());
JTextArea AboutTextArea = new JTextArea(8,35);
JButton MainMenuButton = new JButton("Back");
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10,10,10,10);
gbc.anchor = GridBagConstraints.CENTER;
AboutTextArea.setWrapStyleWord(true);
AboutTextArea.setEditable(false);
AboutTextArea.setLineWrap(true);
AboutTextArea.setFont(new Font("Serif", Font.PLAIN, 22));
AboutTextArea.setText("This is a banking app made by Velizar Mitrev. "
+ "\nIts created only for learning purposes and its my first GUI application. "
+ "Its application that simulates online banking applications where you create account "
+ "and in the account you have your money. "
+ "\nHave Fun with it!");
gbc.gridx = 0;
gbc.gridy = 0;
About.add(AboutTextArea, gbc);
MainMenuButton.setFocusable(false);
MainMenuButton.setFont(new Font("Serif", Font.PLAIN, 24));
gbc.gridx = 0;
gbc.gridy = 1;
About.add(MainMenuButton, gbc);
////////////////
ButtonListener actionListener = new ButtonListener(controller, null);
MainMenuButton.addActionListener(actionListener);
return About;
}
///////////////////////////////////////////////////////
public static JPanel RegisterView(String named) {
JPanel Register = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10,15,10,15);
gbc.anchor = GridBagConstraints.WEST;
JLabel Name;
JLabel Surname;
JTextField SurnameField;
JLabel Password;
JPasswordField PasswordField;
JLabel ConfirmPassword;
JPasswordField ConfirmPasswordField;
JLabel Email;
JTextField EmailField;
JButton RegisterButton;
JButton MainMenuButton;
Name= new JLabel("Name:");
Name.setFont(new Font("Serif", Font.PLAIN, 24));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0;
gbc.weighty = 1;
Register.add((Name), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
NameField = new JTextField(15);
NameField.setFont(new Font("Serif",Font.PLAIN,20));
Register.add(NameField, gbc);
Surname = new JLabel("Surname:");
Surname.setFont(new Font("Serif", Font.PLAIN, 24));
gbc.gridx = 0;
gbc.gridy = 1;
Register.add((Surname), gbc);
SurnameField = new JTextField(15);
SurnameField.setFont(new Font("Serif",Font.PLAIN,20));
gbc.gridx = 1;
gbc.gridy = 1;
Register.add(SurnameField, gbc);
Password = new JLabel("Password:");
Password.setFont(new Font("Serif", Font.PLAIN, 24));
gbc.gridx = 0;
gbc.gridy = 2;
Register.add((Password), gbc);
PasswordField = new JPasswordField(15);
PasswordField.setFont(new Font("Serif",Font.PLAIN,20));
gbc.gridx = 1;
gbc.gridy = 2;
Register.add(PasswordField, gbc);
ConfirmPassword = new JLabel("Confirm password:");
ConfirmPassword.setFont(new Font("Serif", Font.PLAIN, 22));
gbc.gridx = 0;
gbc.gridy = 3;
Register.add((ConfirmPassword), gbc);
ConfirmPasswordField = new JPasswordField(15);
ConfirmPasswordField.setFont(new Font("Serif",Font.PLAIN,20));
gbc.gridx = 1;
gbc.gridy = 3;
Register.add(ConfirmPasswordField, gbc);
Email = new JLabel("Email:");
Email.setFont(new Font("Serif", Font.PLAIN, 24));
gbc.gridx = 0;
gbc.gridy = 4;
Register.add((Email), gbc);
EmailField = new JTextField(15);
EmailField.setFont(new Font("Serif",Font.PLAIN,20));
gbc.gridx = 1;
gbc.gridy = 4;
Register.add(EmailField, gbc);
MainMenuButton = new JButton("Back");
MainMenuButton.setFont(new Font("Serif", Font.PLAIN, 24));
MainMenuButton.setPreferredSize(new Dimension(120, 40));
MainMenuButton.setFocusable(false);
gbc.gridx = 0;
gbc.gridy = 5;
Register.add((MainMenuButton), gbc);
RegisterButton = new JButton("Register");
RegisterButton.setFont(new Font("Serif", Font.PLAIN, 24));
RegisterButton.setPreferredSize(new Dimension(150, 40));
RegisterButton.setFocusable(false);
gbc.gridx = 1;
gbc.gridy = 5;
Register.add(RegisterButton, gbc);
////////////////
ButtonListener actionListener = new ButtonListener(controller, null);
MainMenuButton.addActionListener(actionListener);
RegisterButton.addActionListener(actionListener);
return Register;
}
public static JPanel LoginView(String named) {
JPanel Login= new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10,15,20,15);
gbc.anchor = GridBagConstraints.NORTH;
JLabel Name;
JLabel Password;
JTextField NameField;
JPasswordField PasswordField;
JButton LoginButton;
JButton MainMenuButton;
Name = new JLabel("Name:");
Name.setFont(new Font("Serif", Font.PLAIN, 24));
gbc.gridx = 0;
gbc.gridy = 0;
Login.add(Name, gbc);
NameField = new JTextField(15);
NameField.setFont(new Font("Serif",Font.PLAIN,20));
gbc.gridx = 1;
gbc.gridy = 0;
Login.add(NameField, gbc);
Password = new JLabel("Password:");
Password.setFont(new Font("Serif", Font.PLAIN, 24));
gbc.gridx = 0;
gbc.gridy = 1;
Login.add(Password, gbc);
PasswordField = new JPasswordField(15);
PasswordField.setFont(new Font("Serif",Font.PLAIN,20));
gbc.gridx = 1;
gbc.gridy = 1;
Login.add(PasswordField, gbc);
MainMenuButton = new JButton("Back");
MainMenuButton.setFont(new Font("Serif", Font.PLAIN, 24));
MainMenuButton.setPreferredSize(new Dimension(120, 40));
MainMenuButton.setFocusable(false);
gbc.gridx = 0;
gbc.gridy = 2;
Login.add(MainMenuButton, gbc);
LoginButton = new JButton("Login");
LoginButton.setFont(new Font("Serif", Font.PLAIN, 24));
LoginButton.setPreferredSize(new Dimension(120, 40));
LoginButton.setFocusable(false);
gbc.gridx = 1;
gbc.gridy = 2;
Login.add(LoginButton, gbc);
ButtonListener actionListener = new ButtonListener(controller, null);
MainMenuButton.addActionListener(actionListener);
LoginButton.addActionListener(actionListener);
return Login;
}
////////////////////////////////////////////////////////
public static JPanel otherView(String named) {
JPanel view = new JPanel();
view.setLayout(new BoxLayout(view, BoxLayout.PAGE_AXIS));
JButton mainMenu = new JButton("Main Menu");
view.add(mainMenu);
ButtonListener actionListener = new ButtonListener(controller, null);
mainMenu.addActionListener(actionListener);
return view;
}
public static JPanel createMainMenu() {
JPanel menu = new JPanel();
menu.setLayout(new BoxLayout(menu, BoxLayout.PAGE_AXIS));
menu.add(Box.createRigidArea(new Dimension(0, 10)));
JLabel IntroText = new JLabel("Banking Application");
IntroText.setMaximumSize(new Dimension(280, 60));
IntroText.setFont(new Font("Serif", Font.PLAIN, 34));
IntroText.setAlignmentX(CENTER_ALIGNMENT);
menu.add(IntroText);
menu.add(Box.createRigidArea(new Dimension(0, 20)));
JButton CreateAccount = new JButton("Register");
CreateAccount.setMaximumSize(new Dimension(200, 50));
CreateAccount.setFont(new Font("Serif", Font.PLAIN, 24));
CreateAccount.setAlignmentX(CENTER_ALIGNMENT);
CreateAccount.setFocusable(false);
CreateAccount.setActionCommand("CreateAccount");
menu.add(CreateAccount);
menu.add(Box.createRigidArea(new Dimension(0, 20)));
JButton LoginAccount = new JButton("Login");
LoginAccount.setMaximumSize(new Dimension(200, 50));
LoginAccount.setFont(new Font("Serif", Font.PLAIN, 24));
LoginAccount.setAlignmentX(CENTER_ALIGNMENT);
LoginAccount.setFocusable(false);
LoginAccount.setActionCommand("LoginAccount");
menu.add(LoginAccount);
menu.add(Box.createRigidArea(new Dimension(0, 20)));
JButton AboutButton = new JButton("About");
AboutButton.setMaximumSize(new Dimension(200, 50));
AboutButton.setFont(new Font("Serif", Font.PLAIN, 24));
AboutButton.setAlignmentX(CENTER_ALIGNMENT);
AboutButton.setFocusable(false);
menu.add(AboutButton);
menu.add(Box.createRigidArea(new Dimension(0, 20)));
JButton ExitButton = new JButton("Exit");
ExitButton.setMaximumSize(new Dimension(200, 50));
ExitButton.setFont(new Font("Serif", Font.PLAIN, 24));
ExitButton.setAlignmentX(CENTER_ALIGNMENT);
ExitButton.setFocusable(false);
menu.add(ExitButton);
ButtonListener actionListener = new ButtonListener(controller, null);
CreateAccount.addActionListener(actionListener);
LoginAccount.addActionListener(actionListener);
AboutButton.addActionListener(actionListener);
ExitButton.addActionListener(actionListener);
return menu;
}
public JTextField getTextField() {
return NameField;
}
}
Here is my ActionListener class:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonListener implements ActionListener {
private BankNavigationController controller;
BankGUI gui;
BusinessLogic BL;
public ButtonListener(BankNavigationController controller, BankGUI gui) {
this.gui = gui;
this.controller = controller;
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand() == "CreateAccount"){
controller.setView("Register");
}
if(e.getActionCommand() == "LoginAccount"){
controller.setView("Login");
}
if(e.getActionCommand() == "Back"){
controller.setView("Main Menu");
}
if(e.getActionCommand() == "About"){
controller.setView("About");
}
if(e.getActionCommand() == "Exit"){
System.exit(0);
}
if(e.getActionCommand() == "Exit"){
System.exit(0);
}
if(e.getActionCommand() == "Register")
{
BL.registerAccount(gui);
}
}
}
This is my CardLayout:
import java.awt.*;
public class CardLayoutBankNavigationController implements
BankNavigationController {
private Container parent;
private CardLayout layout;
public CardLayoutBankNavigationController(Container parent, CardLayout layout) {
this.parent = parent;
this.layout = layout;
}
#Override
public void setView(String command) {
layout.show(parent, command);
}
}
This is the BankNavigationInterface
public interface BankNavigationController {
public void setView(String command);
}
And this is the BusinessLogic class:
import java.util.HashMap;
import java.util.Map;
public class BusinessLogic {
Map<String, UserAccount> UserAccounts = new HashMap<String, UserAccount>();
public BusinessLogic(BankGUI gui){
}
public void registerAccount(BankGUI gui){
System.out.println(gui.getTextField());
}
}
My question is how should I access the JTextFields that are in BankGUI from BusinessLogic?
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);
}
I am trying to create a simple email client and the bottom of the body is being cut-off. If I add a horizontal scroll bar, it does not appear, and the bottom of the Vertical scroll bar does not appear either.
Here is my code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
#SuppressWarnings("serial")
public class gui extends JFrame{
gui(String title, int x, int y){
super(title);
setSize(x,y);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
}
public void addElements(){
Font size30 = new Font(null, Font.PLAIN, 30);
JPanel pnl = new JPanel();
Container contentPane = getContentPane();
//--- User Info ---//
JPanel userInfo = new JPanel();
JLabel userLabel = new JLabel("Username: ");
JTextField userField = new JTextField(12);
userInfo.add(userLabel);
userInfo.add(userField);
JLabel passLabel = new JLabel("Password: ");
JTextField passField = new JTextField(10);
userInfo.add(passLabel);
userInfo.add(passField);
JLabel serverLabel = new JLabel("Mail Server: ");
JTextField serverField = new JTextField(10);
userInfo.add(serverLabel);
userInfo.add(serverField);
JLabel portLabel = new JLabel("Server Port: ");
JTextField portField = new JTextField(3);
userInfo.add(portLabel);
userInfo.add(portField);
//--- To: CC: and Subject Fields ---//
JPanel msgInfo = new JPanel();
JLabel toLabel = new JLabel("To: ");
JTextField toField = new JTextField(30);
msgInfo.add(toLabel);
msgInfo.add(toField);
JLabel subLabel = new JLabel("Subject: ");
JTextField subField = new JTextField(30);
msgInfo.add(subLabel);
msgInfo.add(subField);
//--- Body ---//
JPanel bodyPnl = new JPanel(new BorderLayout(10,10));
JLabel bodyLabel = new JLabel("Body");
bodyLabel.setFont(size30);
JTextArea bodyField = new JTextArea(30,70);
bodyField.setLineWrap(true);
bodyField.setWrapStyleWord(true);
JScrollPane bodyScroll = new JScrollPane(bodyField);
bodyScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
bodyScroll.setBounds(getX(), getY(), bodyField.getWidth(), bodyField.getHeight());
bodyPnl.add("South",bodyScroll);
pnl.add(userInfo);
pnl.add(msgInfo);
pnl.add(bodyLabel);
pnl.add(bodyScroll);
contentPane.add("North", pnl);
setVisible(true);
}
}
In my main class I am just creating a new gui and then calling the addElements() function.
FlowLayout doesn't "wrap" well. Consider a different layout, GridBagLayout for example...
Also, stop "trying" to force a size onto your UI, you don't have enough control over the factors which affect sizing to do this.
Instead, rely on the layout managers and API functionality. For example, instead of calling setSize on your frame, call pack...I would have posted soon, but it took me this long to find that call...I was scratching my head wondering why the UI wouldn't layout the way I expected...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class Test extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Test frame = new Test("Testing", 400, 400);
}
});
}
Test(String title, int x, int y) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addElements();
pack();
setVisible(true);
// setResizable(false);
}
public void addElements() {
Font size30 = new Font(null, Font.PLAIN, 30);
//--- User Info ---//
JPanel userInfo = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 4, 2);
gbc.gridx = 0;
gbc.gridy = 0;
JLabel userLabel = new JLabel("Username: ");
JTextField userField = new JTextField(12);
userInfo.add(userLabel, gbc);
gbc.gridx++;
userInfo.add(userField, gbc);
JLabel passLabel = new JLabel("Password: ");
JTextField passField = new JTextField(10);
gbc.gridx++;
userInfo.add(passLabel, gbc);
gbc.gridx++;
userInfo.add(passField, gbc);
JLabel serverLabel = new JLabel("Mail Server: ");
JTextField serverField = new JTextField(10);
gbc.gridx++;
userInfo.add(serverLabel, gbc);
gbc.gridx++;
userInfo.add(serverField, gbc);
JLabel portLabel = new JLabel("Server Port: ");
JTextField portField = new JTextField(3);
gbc.gridx++;
userInfo.add(portLabel, gbc);
gbc.gridx++;
userInfo.add(portField, gbc);
gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 4, 2);
gbc.gridx = 0;
gbc.gridy = 0;
//--- To: CC: and Subject Fields ---//
JPanel msgInfo = new JPanel(new GridBagLayout());
JLabel toLabel = new JLabel("To: ");
JTextField toField = new JTextField(30);
msgInfo.add(toLabel, gbc);
gbc.gridx++;
msgInfo.add(toField, gbc);
JLabel subLabel = new JLabel("Subject: ");
JTextField subField = new JTextField(30);
gbc.gridx++;
msgInfo.add(subLabel, gbc);
gbc.gridx++;
msgInfo.add(subField, gbc);
//--- Body ---//
// JPanel bodyPnl = new JPanel(new GridBagLayout());
// gbc = new GridBagConstraints();
// gbc.insets = new Insets(2, 2, 4, 2);
// gbc.gridx = 0;
// gbc.gridy = 0;
JLabel bodyLabel = new JLabel("Body");
bodyLabel.setHorizontalAlignment(JLabel.CENTER);
bodyLabel.setFont(size30);
JTextArea bodyField = new JTextArea(30, 70);
bodyField.setLineWrap(true);
bodyField.setWrapStyleWord(true);
JScrollPane bodyScroll = new JScrollPane(bodyField);
bodyScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
// bodyScroll.setBounds(getX(), getY(), bodyField.getWidth(), bodyField.getHeight());
setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(userInfo, gbc);
gbc.gridy++;
add(msgInfo, gbc);
gbc.gridy++;
gbc.insets = new Insets(10, 10, 4, 10);
add(bodyLabel, gbc);
gbc.gridy++;
gbc.insets = new Insets(4, 10, 10, 10);
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(bodyScroll, gbc);
}
}
The problem is because of FlowLayout Manager is being used. I have solved your problem with a different layout manager.
Before posting the solution here are some tips that you should follow
Change your class name. It should be in camel-case
Try to call pack() instead of setSize() as it will handle it automatically. When I replaced your setSize() with pack(), it was showing a awkward looking GUI which proves your layout and adding elements were not proper.
Font size30 = new Font(null, Font.PLAIN, 30);
JPanel pnl = new JPanel();
pnl.setLayout(new BoxLayout(pnl,BoxLayout.Y_AXIS));
Container contentPane = getContentPane();
//--- User Info ---//
JPanel userInfo = new JPanel();
JLabel userLabel = new JLabel("Username: ");
JTextField userField = new JTextField(12);
userInfo.add(userLabel);
userInfo.add(userField);
JLabel passLabel = new JLabel("Password: ");
JTextField passField = new JTextField(10);
userInfo.add(passLabel);
userInfo.add(passField);
JLabel serverLabel = new JLabel("Mail Server: ");
JTextField serverField = new JTextField(10);
userInfo.add(serverLabel);
userInfo.add(serverField);
JLabel portLabel = new JLabel("Server Port: ");
JTextField portField = new JTextField(3);
userInfo.add(portLabel);
userInfo.add(portField);
//--- To: CC: and Subject Fields ---//
JPanel msgInfo = new JPanel();
JLabel toLabel = new JLabel("To: ");
JTextField toField = new JTextField(30);
msgInfo.add(toLabel);
msgInfo.add(toField);
JLabel subLabel = new JLabel("Subject: ");
JTextField subField = new JTextField(30);
msgInfo.add(subLabel);
msgInfo.add(subField);
//--- Body ---//
JLabel bodyLabel = new JLabel("Body");
bodyLabel.setFont(size30);
JTextArea bodyField = new JTextArea(30,70);
bodyField.setLineWrap(true);
bodyField.setWrapStyleWord(true);
JScrollPane bodyScroll = new JScrollPane(bodyField);
bodyScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
bodyScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
pnl.add(userInfo);
pnl.add(msgInfo);
pnl.add(bodyLabel);
pnl.add(bodyScroll);
contentPane.add(pnl);
setVisible(true);
pack();