JTextField input and output - java

I'm trying to design a Mile to Nautical Mile calculator in Java.
I was able to create and run it okay through the console, but i'm having trouble learning how to do it in JFrames.
what im basically wanting to do is:
Have two text fields and a button, one text field miles and one for nautical miles, when you enter the amount into one then press the button the result will display in the other field.
I've pasted my code below
Not really sure what to do next
package Mile_Conversion;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class OwnWindow implements ActionListener{
public static void main(String[] args) {
MyJFrame();
}
public static void MyJFrame() {
//JLabel
JLabel start = new JLabel("Enter the amount below to calculate");
start.setBounds(/*x*/70, -65/*Y*/, 270, 150); // x, y, width, height x across, y down
JLabel milecon = new JLabel("Miles");
milecon.setBounds(154, 55, 50, 150);
JLabel nautcon = new JLabel("Nautical Miles");
nautcon.setBounds(135, -15, 150, 150);
//JTextField
JTextField miles = new JTextField();
miles.setBounds(100, 140, 150, 25);
JTextField nautical = new JTextField();
nautical.setBounds(100, 70, 150, 25);
double mile, nautmile;
/*
mile = nautmile * 0.868;
nautmile = mile * 1.150;
*/
//JButton
JButton convert = new JButton("Convert");
convert.setBounds(250, 200, 90, 25);
//JFrame
JFrame window = new JFrame("Milage Conversion");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 300);
window.setVisible(true);
window.setLayout(null);
window.setResizable(false);
window.add(start);
window.add(miles);
window.add(nautical);
window.add(convert);
window.add(milecon);
window.add(nautcon);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}

Welcome to the wonderful world of variable fonts, resolutions and DPI, where what it looks like on your screen will never match any one elses (okay, that's an exaggeration, but it feels like it :P)
In this world, layout managers are you friend. They will save you many, many, many hours of frustration and torment.
I'd recommend you have a read through;
Using Layout Managers
A Visual Guide to Layout Managers
This is my take on what you are trying to do...
public class TestConvertDistance {
public static void main(String[] args) {
new TestConvertDistance();
}
public TestConvertDistance() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DistancePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class DistancePane extends JPanel {
private JLabel lblInstruct;
private JLabel lblMiles;
private JLabel lblNauticalMiles;
private JTextField fldMiles;
private JTextField fldNauticalMiles;
private JButton btnCalculate;
public DistancePane() {
lblInstruct = new JLabel("Enter the amount below to calculate");
lblMiles = new JLabel("Miles");
lblNauticalMiles = new JLabel("Nautical Miles");
fldMiles = new JTextField(8);
fldNauticalMiles = new JTextField(8);
btnCalculate = new JButton("Convert");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(lblInstruct, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = 1;
add(lblMiles, gbc);
gbc.gridy++;
add(lblNauticalMiles, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
add(fldMiles, gbc);
gbc.gridy++;
add(fldNauticalMiles, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(btnCalculate, gbc);
btnCalculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do your calculation here...
}
});
}
}
}
Note, I've used GridBagLayout, this is one of the most powerful and complicated layout managers in the core API, so don't get worried if at first it seems confusion ;)

write your code for conversion inside actionPerformed method:
Take input from first JTextField miles
Parse it to int or float( as JTextFields getText() method returns String)
Do the conversion
set the converted value to the other JTextField nautical using nautical.setText(); method

Here is my version of it. It probably isn't perfect and doesn't have any exception handling:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class OwnWindow implements ActionListener
{
JLabel start;
JLabel milecon;
JLabel nautcon;
JTextField miles;
JTextField nautical;
JButton convert;
JFrame window;
double mile, nautmile;
public static void main(String[] args)
{
OwnWindow obj = new OwnWindow();
}
public OwnWindow()
{
start = new JLabel("Enter the amount below to calculate");
start.setBounds(/*x*/70, -65/*Y*/, 270, 150); // x, y, width, height x across, y down
milecon = new JLabel("Miles");
milecon.setBounds(154, 55, 50, 150);
nautcon = new JLabel("Nautical Miles");
nautcon.setBounds(135, -15, 150, 150);
miles = new JTextField();
miles.setBounds(100, 140, 150, 25);
nautical = new JTextField();
nautical.setBounds(100, 70, 150, 25);
convert = new JButton("Convert");
convert.setBounds(250, 200, 90, 25);
convert.addActionListener(this);
window = new JFrame("Milage Conversion");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 300);
window.setVisible(true);
window.setLayout(null);
window.setResizable(false);
window.add(start);
window.add(miles);
window.add(nautical);
window.add(convert);
window.add(milecon);
window.add(nautcon);
}
#Override
public void actionPerformed(ActionEvent e)
{
String strNaut = nautical.getText();
String strMile = miles.getText();
//this means the user wants to convert nautical to normal
if(strNaut.length() > 0)
{
nautmile = Double.parseDouble(strNaut);
miles.setText(nautmile*0.868 + "");
}
else if(strMile.length() > 0)
{
mile = Double.parseDouble(strMile);
nautical.setText(mile*1.150 + "");
}
}
}

Related

Java JFrame will not update inputted text

I am pretty new to java when compared to python, having only really using it for about 5 months, and up until 2 months ago only using it for android development. I want to learn more about java especially since I basically just skipped strait to the android dev stuff, and learned only what I needed for whatever project I was working on in that. To help me learn, I decided to learn to make a GUI with swing and a simple calculator. I did it in an hour or two, not counting learning swing, and for a very first non-android java program I'm pretty happy with it
the problem i'm having tho, is that when you input 2 numbers, click a button to perform a calculation, then change the numbers and do it again, the program will still use the original numbers, despite them no longer being there
It does read when there are no numbers or a missing number in the input, but just won't use the new numbers for any calculations.
here is the entire program, sorry for the poorly named variables and generally bad code
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class calc implements ActionListener {
private JLabel num1;
private JLabel num2;
private JLabel lans;
private JFrame frame;
private JButton add;
private JButton sub;
private JButton mult;
private JButton div;
private JPanel panel;
private JTextField tnum1;
private JTextField tnum2;
public calc() {
panel = new JPanel();
frame = new JFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
panel.setLayout(null);
num1 = new JLabel("1st Number");
num1.setBounds(20, 20, 80, 25);
panel.add(num1);
num2 = new JLabel("2nd Number");
num2.setBounds(20, 50, 80, 25);
panel.add(num2);
tnum1 = new JTextField();
tnum1.setBounds(100, 20, 80, 25);
panel.add(tnum1);
tnum2 = new JTextField();
tnum2.setBounds(100, 50, 80, 25);
panel.add(tnum2);
add = new JButton("+");
add.setBounds(20, 100, 50, 40);
add.addActionListener(this);
panel.add(add);
sub = new JButton("-");
sub.setBounds(80, 100, 50, 40);
sub.addActionListener(this);
panel.add(sub);
mult = new JButton("×");
mult.setBounds(140, 100, 50, 40);
mult.addActionListener(this);
panel.add(mult);
div = new JButton("÷");
div.setBounds(200, 100, 50, 40);
div.addActionListener(this);
panel.add(div);
lans = new JLabel("");
lans.setBounds(120, 150, 150, 25);
panel.add(lans);
frame.setVisible(true);
}
public static void main(String[] args) {
new calc();
}
#Override
public void actionPerformed(ActionEvent e) {
if (!tnum1.getText().isEmpty() && !tnum2.getText().isEmpty()) {
String snum1 = tnum1.getText();
String snum2 = tnum1.getText();
Double fnum1 = Double.valueOf(snum1);
Double fnum2 = Double.valueOf(snum2);
if (e.getSource() == add) {
Double nans = fnum1 + fnum2;
lans.setText(String.valueOf(nans));
} else if (e.getSource() == sub) {
Double nans = fnum1 - fnum2;
lans.setText(String.valueOf(nans));
} else if (e.getSource() == mult) {
Double nans = fnum1 * fnum2;
lans.setText(String.valueOf(nans));
} else if (e.getSource() == div) {
Double nans = fnum1 / fnum2;
lans.setText(String.valueOf(nans));
}
} else if (!tnum1.getText().isEmpty()) {
lans.setText("No number 2");
} else if (!tnum2.getText().isEmpty()) {
lans.setText("No number 1");
} else {
lans.setText("enter 2 numbers");
}
}
}
yea I know the variables are a bit confusing, but i'm not super familiar with naming conventions yet and i figured since this was a program that I was only using to learn a few select things I didn't really need to use them, especially since I was not planning on actually posting this anywhere.
Edit: im blind, took the first number twice instead of taking both numbers
so I think I found your problem. The only thing you need to change is this.
int snum1 = Integer.parseInt(tnum1.getText());
int snum2 = Integer.parseInt(tnum2.getText());
This portion should go in the actionPerformed. I think the only problem you had was that you used the first variable two times and not the first and the second to do your math.
I rearranged your code because I wanted to explain a few principles about Swing development.
Here's the GUI I created.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method call ensures that all Swing components are created and executed on the Event Dispatch Thread.
Absolute positioning of Swing components is painful to do and not conducive to the various operating systems and monitor resolutions that people use. I used a GridBagLayout for the main JPanel and a FlowLayout for the button JPanel. Sure, the code looks more complicated. But I didn't have to calculate any component size or location. The Swing layout managers do this for me.
I added a couple of JFrame methods to give the GUI a title and position it on the screen according to the operating system.
I broke up the GUI creation code into methods, so I could focus on one part of the GUI at a time.
Here's the code.
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class SimpleCalculatorGUI implements ActionListener {
private JLabel lans;
private JFrame frame;
private JButton add;
private JButton sub;
private JButton mult;
private JButton div;
private JTextField tnum1;
private JTextField tnum2;
public SimpleCalculatorGUI() {
frame = new JFrame();
frame.setTitle("Calculator");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1d;
JLabel num1 = new JLabel("1st Number");
panel.add(num1, gbc);
gbc.gridx++;
tnum1 = new JTextField(10);
panel.add(tnum1, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel num2 = new JLabel("2nd Number");
panel.add(num2, gbc);
gbc.gridx++;
tnum2 = new JTextField(10);
panel.add(tnum2, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 2;
panel.add(createButtonPanel(), gbc);
gbc.gridy++;
lans = new JLabel(" ");
lans.setHorizontalAlignment(JLabel.CENTER);
panel.add(lans, gbc);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
add = new JButton("+");
add.addActionListener(this);
panel.add(add);
sub = new JButton("-");
sub.addActionListener(this);
panel.add(sub);
mult = new JButton("×");
mult.addActionListener(this);
panel.add(mult);
div = new JButton("÷");
div.addActionListener(this);
panel.add(div);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SimpleCalculatorGUI();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (!tnum1.getText().isEmpty()
&& !tnum2.getText().isEmpty()) {
String snum1 = tnum1.getText();
String snum2 = tnum2.getText();
Double fnum1 = Double.valueOf(snum1);
Double fnum2 = Double.valueOf(snum2);
if (e.getSource() == add) {
Double nans = fnum1 + fnum2;
lans.setText(String.valueOf(nans));
} else if (e.getSource() == sub) {
Double nans = fnum1 - fnum2;
lans.setText(String.valueOf(nans));
} else if (e.getSource() == mult) {
Double nans = fnum1 * fnum2;
lans.setText(String.valueOf(nans));
} else if (e.getSource() == div) {
Double nans = fnum1 / fnum2;
lans.setText(String.valueOf(nans));
}
} else if (!tnum1.getText().isEmpty()) {
lans.setText("No number 2");
} else if (!tnum2.getText().isEmpty()) {
lans.setText("No number 1");
} else {
lans.setText("Enter 2 numbers");
}
}
}
the problem with your code is that you used tnum1.getText() tow times instead of tnum2.getText()
you just need to change the third line in actionPerformed(e) to String snum2 = tnum2.getText(); and it will work

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

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

Java JTable column header not showing using DefaultModel

Like the title said, the hearder name is just not showing up. i tried many options like using a JScrollPane. and fallowed many guide on this forum but no help. I really wanted to get resolve problem by myself but i have tried everything and out of option.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.ScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.JScrollPane;
import javax.swing.JScrollBar;
public class Adminpage extends JPanel {
private JFrame frame;
static String ID[]={"name","Username","Password"};
static DefaultTableModel model;
private JTextField NametextField;
private JTextField UsertextField;
private JTextField PasstextField;
private JTable table;
private JScrollPane scroll;
/**
* Create the panel.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 497, 545);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblAdminstratorPortal = new JLabel("Adminstrator Portal");
lblAdminstratorPortal.setFont(new Font("Tahoma", Font.BOLD, 20));
lblAdminstratorPortal.setBounds(109, 26, 218, 25);
frame.getContentPane().add(lblAdminstratorPortal);
JButton btnNewButton = new JButton("Add Librarian");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//model= (DefaultTableModel)table.getModel();
//model.addColumn("name");
//model.addColumn("Username");
//model.addColumn("Password");
model.addRow(new Object[]{NametextField.getText(),UsertextField.getText(),PasstextField.getText()});
}
});
btnNewButton.setBounds(10, 62, 108, 35);
frame.getContentPane().add(btnNewButton);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDelete.setBounds(130, 62, 108, 35);
frame.getContentPane().add(btnDelete);
JButton btnViewLibrarian = new JButton("View Librarian");
btnViewLibrarian.setBounds(245, 62, 108, 35);
frame.getContentPane().add(btnViewLibrarian);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
}
});
btnLogout.setBounds(363, 62, 108, 35);
frame.getContentPane().add(btnLogout);
//model= (DefaultTableModel)table.getModel();
JLabel lblName = new JLabel("Name");
lblName.setBounds(21, 144, 60, 14);
frame.getContentPane().add(lblName);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(21, 195, 60, 14);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(21, 250, 60, 14);
frame.getContentPane().add(lblPassword);
NametextField = new JTextField();
NametextField.setBounds(119, 141, 119, 20);
frame.getContentPane().add(NametextField);
NametextField.setColumns(10);
UsertextField = new JTextField();
UsertextField.setColumns(10);
UsertextField.setBounds(119, 192, 119, 20);
frame.getContentPane().add(UsertextField);
PasstextField = new JTextField();
PasstextField.setColumns(10);
PasstextField.setBounds(119, 247, 119, 20);
frame.getContentPane().add(PasstextField);
table = new JTable();
table.setBounds(10, 304, 461, 189);
frame.getContentPane().add(table);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Adminpage() {
database();
setLayout(null);
initialize();
model= (DefaultTableModel)table.getModel();
model.addColumn("name");
model.addColumn("Username");
model.addColumn("Password");
}
public void database(){
try {
Class.forName("sun.jdbc.odbc.JdbsOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Games");
Statement st = con.createStatement();
String getquery = ("Select* from Games");
ResultSet rs= st.executeQuery(getquery);
while(rs.next()){
System.out.println(rs.getString(2));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
You're adding the JTable directly to the GUI. Instead, yes you need to embed the JTable into the viewport of a JScrollPane and then add the JScrollPane to the GUI.
For example:
table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
// table.setBounds(10, 304, 461, 189);
scrollPane.setBounds(10, 304, 461, 189); // This is bad, but will leave for now
// frame.getContentPane().add(table);
frame.getContentPane().add(scrollPane);
Also, you're harming your GUI by using null layouts and absolute positioning, as this can interfere with a component's ability to show itself fully and correctly, to achieve its own preferred size. Much better is to learn and use the layout managers.
For instance, when I run your program on my platform, I see:
Note how the buttons do not show their full texts due to their not being allowed to achieve their preferred sizes.
For example, using BoxLayout with some nested JPanels, one using GridLayout(1, 0, 5, 0) for one row, variable number of columns, and a 5 point horizontal gap between components, and another nested JPanel using GridBagLayout, for placement of JTextFields and JLabels, and some "wrapper" JPanels using default FlowLayout to center components within them...
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class AdminPage2 extends JPanel {
private static final long serialVersionUID = 1L;
public static final String TITLE = "Administrator Portal";
private static final Font TITLE_FONT = new Font("Tahoma", Font.BOLD, 20);
private static final String[] COL_NAMES = {"Name", "User Name", "Password"};
private int txtFieldCols = 20;
private JTextField nameField = new JTextField(txtFieldCols);
private JTextField userNameField = new JTextField(txtFieldCols);
private JPasswordField passwordField = new JPasswordField(txtFieldCols);
private DefaultTableModel tableModel = new DefaultTableModel(COL_NAMES, 0);
private JTable table = new JTable(tableModel);
private JScrollPane tableScrollPane = new JScrollPane(table);
public AdminPage2() {
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(TITLE_FONT);
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
// of course you'd add ActionListeners or Actions to your buttons
buttonPanel.add(new JButton("Add Library"));
buttonPanel.add(new JButton("Delete"));
buttonPanel.add(new JButton("View Library"));
buttonPanel.add(new JButton("Logout"));
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Name:"), createGbc(0, 0));
textFieldPanel.add(nameField, createGbc(1, 0));
textFieldPanel.add(new JLabel("User Name:"), createGbc(0, 1));
textFieldPanel.add(userNameField, createGbc(1, 1));
textFieldPanel.add(new JLabel("Password:"), createGbc(0, 2));
textFieldPanel.add(passwordField, createGbc(1, 2));
JPanel wrapTfPanel = new JPanel();
wrapTfPanel.add(textFieldPanel);
Dimension scrollPanePrefSz = tableScrollPane.getPreferredSize();
int w = scrollPanePrefSz.width;
int h = scrollPanePrefSz.height / 2;
scrollPanePrefSz = new Dimension(w, h);
tableScrollPane.setPreferredSize(scrollPanePrefSz);
// put together main JPanel components
int ebGap = 4;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(Box.createVerticalStrut(5));
add(titlePanel);
add(Box.createVerticalStrut(5));
add(buttonPanel);
add(Box.createVerticalStrut(5));
add(wrapTfPanel);
add(Box.createVerticalStrut(5));
add(tableScrollPane);
}
// create constraints to use when adding component to GridBagLayout
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
int in = 10;
int leftIn = x == 0 ? 4 * in : in;
gbc.insets = new Insets(in, leftIn, in, in);
return gbc;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
AdminPage2 mainPanel = new AdminPage2();
JFrame frame = new JFrame("Administrator Page");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Which displays as:
Regarding your questions:
but new question why give the scrollpane a bound instead of the table itself
The JScrollPane holds the JTable within it, and so if you use null layouts (which you shouldn't), and you're adding this JTable-containing JScrollPane to the GUI, you must set its bounds. Much better though is to use layout managers as I've outlined above. It makes it much easier to modify the GUI later and to debug it now.
and why adding the scrollpane into the panel instead of the table.
Because that's how JScrollPanes work. They don't add scrollbars to a component but rather nest the component itself, here the JTable, within the JScrollPane's viewport. Please read the JScrollPane Tutorial (see link) to see the details on this.
A further note on the power of layout managers. Say you want to add a new JLabel / JTextField combination, one that accepts a password hint, and say the JTextField's name is passwordHint. If you were using null layouts and absolute positioning, you'd have to set the bounds of your new JLabel and JTextField, but you'd also have to change the bounds of all components below and to the right of it, and would have to re-set the size of the GUI manually. If your GUI is very complex, this can lead to bugs and a lot of frustration.
If you used the layout managers above however, all you'd need to do would be to add two lines of code to the textFieldPanel JPanel creational code as shown below with the obvious comments:
// original textFieldPanel creational code
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Name:"), createGbc(0, 0));
textFieldPanel.add(nameField, createGbc(1, 0));
textFieldPanel.add(new JLabel("User Name:"), createGbc(0, 1));
textFieldPanel.add(userNameField, createGbc(1, 1));
textFieldPanel.add(new JLabel("Password:"), createGbc(0, 2));
textFieldPanel.add(passwordField, createGbc(1, 2));
// !! ****** these lines added ******
textFieldPanel.add(new JLabel("Password Hint:"), createGbc(0, 3));
textFieldPanel.add(passwordHint, createGbc(1, 3));
This results in a perfect placement of the new components without adversely affecting the old:

Java JPanel and JLabel's

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

Multiple JPanel Java Application Windows

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

Categories