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?
Related
I am currently trying to include a JTable to my JPanel. I was not having any problems with my code previously until I started to code the table. Sometimes when I run my program everything will appear, sometimes just the panels appear, and sometimes/majority of the time nothing will appear. I just don't understand why it is not consistent. There are no errors in the console. I have included below my ViewPage.java, Page.java, and Main.java.
`
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ViewPage extends Page implements ActionListener
{
JPanel panel1, panel2, panel3;
JLabel searchLabel, repairsLabel, dateLabel;
JButton goButton, recentButton, oldestButton, homeButton;
JComboBox dropDown;
JTextField textField;
JTable tabel;
JScrollPane scrollpane;
public ViewPage()
{
panel1 = new JPanel();
panel1.setBackground(Color.blue);
panel1.setBounds(0,0,1280,120);
panel2 = new JPanel();
panel2.setBackground(Color.green);
panel2.setBounds(0,120,1280,480);
panel3 = new JPanel();
panel3.setBackground(Color.red);
panel3.setBounds(0,600,1280,120);
//Panel 1 components
repairsLabel = new JLabel("Repairs");
repairsLabel.setFont(new Font("Serif", Font.BOLD, 50));
searchLabel = new JLabel("Search :");
searchLabel.setFont(new Font("Serif", Font.PLAIN, 25));
goButton = new JButton("GO");
goButton.setFocusable(false);
goButton.addActionListener(this);
textField = new JTextField();
String[] filters = {" ", "customerID", "First_Name", "Last_Name"};
dropDown = new JComboBox(filters);
dropDown.addActionListener(this);
panel1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 0);
gbc.weightx = 5.5;
gbc.gridx = 0;
gbc.gridy = 0;
panel1.add(repairsLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0.5;
gbc.gridx = 1;
gbc.gridy = 0;
panel1.add(searchLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 50);
gbc.weightx = 3;
gbc.gridx = 2;
gbc.gridy = 0;
panel1.add(dropDown, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 50);
gbc.gridx = 3;
gbc.gridy = 0;
gbc.ipadx = 100;
panel1.add(textField, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 100);
gbc.gridx = 4;
gbc.gridy = 0;
gbc.ipadx = 1;
panel1.add(goButton, gbc);
//Panel 2 components
panel2.setLayout(new GridBagLayout());
String[][] data = new String[50][8];
String[] headings = {"customer_ID", "Date", "First Name", "Last Name", "Phone #", "OS", "PC Type", "Problem"};
JTable table = new JTable(data, headings);
table.setEnabled(false);
table.setPreferredScrollableViewportSize(new Dimension(1000,400));
table.setFillsViewportHeight(true);
scrollpane = new JScrollPane(table);
panel2.add(scrollpane);
//Panel 3 componets
panel3.setLayout(new GridBagLayout());
GridBagConstraints gbc2 = new GridBagConstraints();
dateLabel = new JLabel("Date Filter: ");
dateLabel.setFont(new Font("Serif", Font.PLAIN, 25));
recentButton = new JButton("Most Recent");
oldestButton = new JButton("Oldest");
homeButton = new JButton("Home");
gbc2.fill = GridBagConstraints.HORIZONTAL;
gbc2.insets = new Insets(1, 10, 1, 0);
gbc2.weightx = 5.5;
gbc2.gridx = 0;
gbc2.gridy = 0;
panel3.add(dateLabel, gbc);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == dropDown)
{
System.out.println(dropDown.getSelectedItem());
}
}
}
`
`
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
public abstract class Page
{
private final static int pageWidth = 1280;
private final static int pageHeight = 720;
protected JFrame frame;
public Page()
{
frame = new JFrame();
frame.setTitle("Computer Repair Store");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(pageWidth, pageHeight);
frame.setLayout(null);
frame.setVisible(true);
}
public int getpageWidth()
{
return pageWidth;
}
public int getpageHeight()
{
return pageHeight;
}
}
`
`
public class Main {
public static void main(String[] args) {
ViewPage viewPage = new ViewPage();
}
}
`
Ouput:
enter image description here
This is what I am expecting to output which has only appeared 2-3 times out of the 50 times I have tried running the program.
enter image description here
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.
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);
}
I'd like to ask something about GridBagLayout because whenever I try to put the lblStudentID under lblName it just makes an output wherein it stays in the right side of lblName
import javax.swing.*;
import java.awt.*;
public class Student extends JPanel {
JLabel picture;
JLabel lblStudentID = new JLabel("Student ID:");
JLabel lblName = new JLabel("Name:");
JLabel lblProg = new JLabel("Program:");
JLabel lblGen = new JLabel("Gender:");
JPanel panel = new JPanel();
JRadioButton rbtn1 = new JRadioButton("Male");
JRadioButton rbtn2 = new JRadioButton("Female");
JComboBox cmbProg = new JComboBox();
TextField txtStudentID = new TextField();
TextField txtName = new TextField();
GridBagConstraints gbc = new GridBagConstraints();
public void setName() {
}
public Student() {
setLayout(new GridBagLayout());
picture = new JLabel(createImageIcon("images/student.jpg"));
picture.setSize(100, 100);
add(picture);
add(lblName, gbc);
gbc.gridx = 0;
gbc.gridy = 0;
add(txtName, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
add(lblStudentID, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
add(txtStudentID, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Student");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
// Display the window.
Student LoginPane = new Student();
LoginPane.setOpaque(true); // content panes must be opaque
LoginPane.setLayout(new FlowLayout());
LoginPane.setBackground(Color.white);
frame.setContentPane(LoginPane);
frame.setVisible(true);
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Student.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
First you change the GridBagConstraints too late.
gbc.gridx = 0;
gbc.gridy = 0;
add(lblName,gbc);
gbc.gridx = 1;
gbc.gridy = 0;
add(txtName,gbc);
gbc.gridx = 0;
gbc.gridy = 1;
add(lblStudentID,gbc);
gbc.gridx = 1;
gbc.gridy = 1;
add(txtStudentID,gbc);
Second you change the layout back to FlowLayout of your LoginPane.
Edit
I have stripped-down your code. Maybe this will help you:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.TextField;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Student extends JPanel {
private static final long serialVersionUID = 8923497527096438302L;
private JLabel picture;
private JLabel lblStudentID = new JLabel("Student ID:");
private JLabel lblName = new JLabel("Name:");
TextField txtStudentID = new TextField();
TextField txtName = new TextField();
public Student() {
setLayout(new BorderLayout());
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setBackground(Color.WHITE);
JPanel formPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
formPanel.setOpaque(false);
picture = new JLabel(createImageIcon("images/student.jpg"));
picture.setPreferredSize(new Dimension(100, 100));
picture.setBorder(BorderFactory.createLineBorder(Color.black));
gbc.fill = GridBagConstraints.BOTH;
gbc.gridy = 0;
formPanel.add(picture, gbc);
gbc.gridy = 1;
gbc.gridwidth = 1;
formPanel.add(lblName, gbc);
gbc.gridy = 1;
gbc.weightx = 1;
formPanel.add(txtName, gbc);
gbc.weightx = 0;
gbc.gridy = 2;
formPanel.add(lblStudentID, gbc);
gbc.gridy = 2;
formPanel.add(txtStudentID, gbc);
add(formPanel, BorderLayout.PAGE_START);
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Student");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
// Display the window.
new Student().setBackground(Color.white);
frame.setContentPane(new Student());
frame.setVisible(true);
}
protected static ImageIcon createImageIcon(String path) {
URL imgURL = Student.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
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();