Set button size smaller in Java Swing - java

I am trying to implement a GUI in Java Swing; but I am stuck on the button size, which I am trying to make smaller. I have tried to use setSize, setPrefferedSize and setmaximumSize, but nothing worked. Any ideas?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.*;
import javax.swing.border.Border;
public class WorkStationGUI extends JFrame implements ActionListener {
JButton Worker1Process1;
JButton Worker1Process2;
JButton StopWorking;
// JScrollPane scrollList;
JTextArea OrderList;
JTextArea ProductList;
JTextField orders;
JTextField products;
JTextField Worker1;
JTextField Worker2;
private HashMap<String, Order> OrdersList;
private HashMap<String, Product> ProductsList;
public WorkStationGUI(HashMap<String, Order> orders, HashMap<String, Product> Products) {
this.OrdersList = orders;
this.ProductsList = Products;
setTitle("Work Station");
setupEastandWest();
setupSouthPanel();
pack();
setVisible(true);
}
private JLabel createOneLabel(String s, Color c) {
Font f = new Font(Font.SANS_SERIF, Font.BOLD, 18);
JLabel label = new JLabel(s, JLabel.CENTER);
label.setFont(f);
label.setBackground(c);
label.setOpaque(true);
return label;
}
private void setupEastandWest() {
// search panel contains label, text field and button
JPanel Panel = new JPanel();
Worker1Process1 = new JButton("Worker 1");
Worker1Process1.setPreferredSize(new Dimension(10, 10));
Panel.add(Worker1Process1);
Worker1 = new JTextField(20);
Worker1Process1.setPreferredSize(new Dimension(90, 90));
Worker1.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
Worker1.setEditable(false);
Panel.setLayout(new GridLayout(2, 1));
Panel.add(Worker1);
JPanel Panel2 = new JPanel();
Worker1Process2 = new JButton("Worker 2");
Panel2.add(Worker1Process2);
Worker2 = new JTextField(20);
Worker2.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
Worker2.setEditable(false);
Panel2.setLayout(new GridLayout(2, 1));
Panel2.add(Worker2);
Panel.setLayout(new GridLayout(2, 2));
this.add(Panel, BorderLayout.EAST);
this.add(Panel2, BorderLayout.WEST);
// this.add(Panel2, BorderLayout.SOUTH);
}
private void setupSouthPanel() {
JPanel Panel = new JPanel();
orders = new JTextField(1);
orders.setBackground(Color.LIGHT_GRAY);
Panel.add(orders);
JPanel Panel2 = new JPanel();
products = new JTextField(1);
Panel.add(products);
products.setBackground(Color.LIGHT_GRAY);
Panel.setLayout(new GridLayout(2, 2));
this.add(Panel, BorderLayout.CENTER);
this.add(Panel2, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
}
}

You are using GridLayout which will cause the component to take up all container space, relative to the grid. It's not really the best choice for buttons. You might try using a FlowLayout, or GridBagLayout instead.
Also, you are setting the layout manager AFTER you are setting the JButton on the panel.

Related

GUI JPanel & frame layout

I want to ask some question about Java GUI, especially on JPanel syntax. I'm really confused how to configure the panel exactly, try to use BorderLayout, and GridLayout, but it still doesn't meet my requirement.
I want to make form like below:
Current Result:
From the image, I need to configure that 2 points
The padding / margin between Input Panel and the Button Panel
The Padding / margin between tablePanel and the inputPanel
Code
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
public class manageForm extends JFrame {
//Vector<String> header=new Vector<String>();
//Vector<Vector<String>>data=new Vector<Vector<String>>();
DefaultTableModel defaultTableModel;
JTable table;
JScrollPane scrollPane;
JLabel titleLabel=new JLabel("Manage Handphone");
JTable hpTable = new JTable();
JLabel idLabel = new JLabel("ID");
JLabel nameLabel = new JLabel("Name");
JLabel priceLabel = new JLabel("Price");
JLabel weightLabel = new JLabel("Weight");
JLabel cableLabel = new JLabel("Cable Length");
JLabel typeLabel = new JLabel("Type");
JTextField idtxt = new JTextField();
JTextField nametxt = new JTextField();
JTextField pricetxt = new JTextField();
JTextField weighttxt = new JTextField();
JTextField cabletxt = new JTextField();
JComboBox typeBox = new JComboBox();
JButton insertBtn = new JButton("INSERT");
JButton updateBtn = new JButton("UPDATE");
JButton deleteBtn = new JButton("DELETE");
JButton confirmBtn = new JButton("CONFIRM");
JButton cancelBtn = new JButton("CANCEL");
String header[] = {"ID","Name","Type","Price","Weight","Cable Length"};
String data[][] = {
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"},
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"},
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"}
};
public manageForm() {
JPanel headerPanel = new JPanel();
JPanel tablePanel = new JPanel();
tablePanel.setBorder(new EmptyBorder(0,0,0,0));
JPanel inputPanel = new JPanel(new GridLayout(6,2));
inputPanel.setBorder(new EmptyBorder(20,10,20,10));
//inputPanel.setBorder(new LineBorder(Color.black));
JPanel buttonPanel = new JPanel(new GridLayout(1,5));
buttonPanel.setBorder(new EmptyBorder(100,20,100,20));
JPanel footerPanel = new JPanel(new GridLayout (2,1,0,0));
headerPanel.add(titleLabel);
inputPanel.add(idLabel);
inputPanel.add(idtxt);
inputPanel.add(nameLabel);
inputPanel.add(nametxt);
inputPanel.add(priceLabel);
inputPanel.add(pricetxt);
inputPanel.add(weightLabel);
inputPanel.add(weighttxt);
inputPanel.add(cableLabel);
inputPanel.add(cabletxt);
inputPanel.add(typeLabel);
inputPanel.add(typeBox);
buttonPanel.add(confirmBtn);
buttonPanel.add(cancelBtn);
buttonPanel.add(insertBtn);
buttonPanel.add(updateBtn);
buttonPanel.add(deleteBtn);
footerPanel.add(inputPanel);
footerPanel.add(buttonPanel);
/*
JPanel panel0=new JPanel();
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
JPanel panel3=new JPanel();
JPanel panel4=new JPanel();
JPanel panel5=new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
panel1.setLayout(new GridLayout(1, 6));
panel2.setLayout(new GridLayout(1, 2));
panel2.add(idLabel);
panel2.add(idtxt);
panel3.setLayout(new GridLayout(1, 2));
panel3.add(nameLabel);
panel3.add(nametxt);
panel4.setLayout(new GridLayout(1, 2));
panel4.add(priceLabel);
panel4.add(pricetxt);
panel5.setLayout(new GridLayout(1, 2));
panel5.add(weightLabel);
panel5.add(weighttxt);
panel6.setLayout(new GridLayout(1, 2));
panel6.add(cableLabel);
panel6.add(cabletxt);
panel7.setLayout(new GridLayout(1, 2));
panel7.add(typeLabel);
panel7.add(typeBox);
panel8.setLayout(new GridLayout(1, 5));
mainPanel.add(panel0);
mainPanel.add(panel1);
mainPanel.add(panel2);
mainPanel.add(panel3);
mainPanel.add(panel4);
mainPanel.add(panel5);
mainPanel.add(panel6);
mainPanel.add(panel7);
mainPanel.add(panel8);
*/
/*
header.add("ID");
header.add("Name");
header.add("Type");
header.add("Price");
header.add("Weight");
header.add("Cable Length");
*/
defaultTableModel=new DefaultTableModel(data, header);
hpTable =new JTable(defaultTableModel);
scrollPane=new JScrollPane(hpTable);
// tablePanel.add(scrollPane);
setLayout(new BorderLayout(0,5));
setTitle("Manage Form");
setSize(800,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
add(headerPanel,BorderLayout.NORTH);
add(scrollPane,BorderLayout.CENTER);
add(footerPanel,BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
new manageForm();
}
}
How exactly to manage the panel layout to meet our requirement?
I have tried EmptyBorder, but the result, it's only making a big space between the other panel.
Use GridBagLayout it is a powerful and best fit to your requirement. It is arranges the components in a horizontal and vertical manner.
You can put component in a grid using cells and rows. As a example:
read more - GridBagLayout
Strongly disagree with the suggestion to use GridBagLayout. That layout is basically a punchline for any Swing programmer.
If you're going to be programming Swing, do yourself a huge favor and use MiGLayout. It's the layout manager that Swing should have built-in.

Populating JTextFields with object data taken from selected comboBox item

I'll try to explain the problem as best i can.
Basically what I have is a system that takes in customer data (Customer is an object) and then adds it to an array. I have that working no problems. What I'm trying to get working is that I also have an option that should enable the user to edit a customers details. The way I'm trying to implement this is; in a separate GUI, I have a comboBox which will be populated with all of the customers first names that are currently in the arrayList. This also works.
Here is my problem - what I want to happen is that when one of the customers first names is chosen from the comboBox, it should find that object, and then fill out the JTextFields with its respective data, e.g. that customers first name should pop into the first name textField and his second name into the second name TextField etc..
I cant figure out this problem so any help is appreciated!
This is only one of a few classes, the rest of which work.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.MaskFormatter;
import javax.swing.JLabel;
import java.awt.SystemColor;
import java.text.ParseException;
import java.util.ArrayList;
import java.awt.Font;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.UIManager;
import java.awt.GridLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
public class editCustomers extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
ArrayList<Customers> customerList;
private MaskFormatter mask = null;
/**
* Create the frame.
*/
public editCustomers(ArrayList<Customers> aList) {
customerList = aList;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 700, 600);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(6, 0, 0, 0));
JPanel panel_12 = new JPanel();
panel.add(panel_12);
panel_12.setLayout(new BorderLayout(0, 0));
JLabel lblSelectACustomer = new JLabel("Select a Customer to Edit");
panel_12.add(lblSelectACustomer, BorderLayout.WEST);
JComboBox comboBox = new JComboBox();
//comboBox.setModel(new DefaultComboBoxModel());
for (Customers temp : customerList) {
comboBox.addItem(temp.getfName());
}
panel_12.add(comboBox, BorderLayout.EAST);
JPanel panel_3 = new JPanel();
panel.add(panel_3);
panel_3.setLayout(new BorderLayout(0, 0));
JLabel lbl1 = new JLabel("Edit Customers First Name");
lbl1.setVerticalAlignment(SwingConstants.TOP);
Dimension d = lbl1.getPreferredSize();
lbl1.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_3.add(lbl1, BorderLayout.WEST);
JPanel panel_8 = new JPanel();
panel_3.add(panel_8, BorderLayout.CENTER);
textField = new JTextField();
panel_8.add(textField);
textField.setColumns(30);
JPanel panel_4 = new JPanel();
panel.add(panel_4);
panel_4.setLayout(new BorderLayout(0, 0));
JLabel lbl2 = new JLabel("Edit Customers Second Name");
lbl2.setVerticalAlignment(SwingConstants.TOP);
lbl2.getPreferredSize();
lbl2.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_4.add(lbl2, BorderLayout.WEST);
JPanel panel_9 = new JPanel();
panel_4.add(panel_9, BorderLayout.CENTER);
textField_1 = new JTextField();
panel_9.add(textField_1);
textField_1.setColumns(30);
JPanel panel_5 = new JPanel();
panel.add(panel_5);
panel_5.setLayout(new BorderLayout(0, 0));
JLabel lbl3 = new JLabel("Edit Customers Address");
lbl3.setVerticalAlignment(SwingConstants.TOP);
lbl3.getPreferredSize();
lbl3.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_5.add(lbl3, BorderLayout.WEST);
JPanel panel_10 = new JPanel();
panel_5.add(panel_10, BorderLayout.CENTER);
textField_2 = new JTextField();
panel_10.add(textField_2);
textField_2.setColumns(30);
JPanel panel_6 = new JPanel();
panel.add(panel_6);
panel_6.setLayout(new BorderLayout(0, 0));
JLabel lbl4 = new JLabel("Edit Customers Date of Birth");
lbl4.setVerticalAlignment(SwingConstants.TOP);
lbl4.getPreferredSize();
lbl4.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_6.add(lbl4, BorderLayout.WEST);
JPanel panel_11 = new JPanel();
panel_6.add(panel_11, BorderLayout.CENTER);
textField_3 = new JTextField();
try {
mask = new MaskFormatter("##/##/####");
mask.setPlaceholderCharacter(' ');
} catch (ParseException e) {
e.printStackTrace();
}
JFormattedTextField textField_3 = new JFormattedTextField(mask);
textField_3.setText("dd/mm/yyyy");
panel_11.add(textField_3);
textField_3.setColumns(30);
JPanel panel_2 = new JPanel();
panel.add(panel_2);
panel_2.setLayout(new BorderLayout(0, 0));
JPanel panel_7 = new JPanel();
panel_2.add(panel_7, BorderLayout.CENTER);
JButton btnConfirm = new JButton("Confirm");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel_7.add(btnConfirm);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
panel_7.add(btnCancel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(SystemColor.activeCaption);
contentPane.add(panel_1, BorderLayout.NORTH);
JLabel lblEditACurrent = new JLabel("Edit a Current Customer");
lblEditACurrent.setForeground(Color.BLACK);
lblEditACurrent.setFont(new Font("Arial", Font.PLAIN, 19));
lblEditACurrent.setBackground(UIManager.getColor("InternalFrame.activeTitleBackground"));
panel_1.add(lblEditACurrent);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
editCustomers frame = new editCustomers(new ArrayList<Customers>());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
You can try something like this ....
Change line 63 - 67 as following. Put the customers into the combobox instead of just names.
JComboBox<Customer> comboBox = new JComboBox<>();
//comboBox.setModel(new DefaultComboBoxModel());
for (Customers temp : customerList) {
comboBox.addItem(temp);
}
Then implement an ActionListener for the combobox as following.
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Customer customer = comboBox.getSelectedItem();
// Use the above customer object's fields to populate your text fields
}
});

Looking for a simple way to change text in a JTextField with a button click

I'm trying to get the action listener and button called French to change the text in the Output field to say Bonjour but many errors come up in the console when I click the button. I would like to do this in as few lines as possible.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
public class TranslatorFrame {
public static void main(String[] args) {
JFrame Words = new JFrame("Greetings Translator");
Words.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Did some research to find the line so the program
//would appear in the center of the screen
Font Font1 = new Font("SansSerif",Font.BOLD,40);
JPanel WorkSpace = new JPanel();
JTextField Instructions = new JTextField("Enter \"Hello\" Here: ");
JTextField Input = new JTextField();
JPanel Center = new JPanel();
Center.setBackground(Color.lightGray);
Center.add(Instructions, BorderLayout.EAST);
Center.add(Input, BorderLayout.WEST);
JTextField Output = new JTextField("");
Output.setFont(Font1);
Output.setPreferredSize(new Dimension(195, 100));
JTextField Header = new JTextField();
Header.setPreferredSize(new Dimension(195, 100));
Input.setPreferredSize(new Dimension(150,50));
Input.setFont(Font1);
Instructions.setPreferredSize(new Dimension(375,50));
Instructions.setBackground(Color.cyan);
//set the back ground color of my Instructions field so that it wouldn't
//look so gray and boring. There don't seem to be many preset colors to choose from.
Instructions.setFont(Font1);
Instructions.setEditable(false);
JPanel ButtonsArea = new JPanel();
ButtonsArea.setBackground(Color.lightGray);
ButtonsArea.setPreferredSize(new Dimension(300,300));
JButton French = new JButton("French");
French.setPreferredSize(new Dimension(200, 150));
French.setFont(Font1);
French.addActionListener(new ChangeListener());
JButton German = new JButton("German");
German.setPreferredSize(new Dimension(200, 150));
German.setFont(Font1);
JButton Spanish = new JButton("Spanish");
Spanish.setPreferredSize(new Dimension(200, 150));
Spanish.setFont(Font1);
ButtonsArea.add(French, BorderLayout.EAST);
ButtonsArea.add(German, BorderLayout.CENTER);
ButtonsArea.add(Spanish, BorderLayout.WEST);
ButtonsArea.add(Output,BorderLayout.SOUTH);
//Tried many different things to get the buttons and textfields
//to have space between them but nothing seems to work.
//Header.setSize(100,100);
Header.setFont(Font1);
Header.setText("Welcome!");
Header.setEditable(false);
WorkSpace.setBackground(Color.LIGHT_GRAY);
class ChangeListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource()==French);
Output.setText("Bonjour!");
}}
Words.pack();
Words.setSize(new Dimension(1000, 600));
Words.setLocationRelativeTo(null);
WorkSpace.add(Header);
Words.add(WorkSpace, BorderLayout.NORTH);
Words.add(Center, BorderLayout.CENTER);
/*Words.add(Instructions, BorderLayout.CENTER);
Words.add(Input, BorderLayout.CENTER);*/
Words.add(ButtonsArea, BorderLayout.SOUTH);
//Words.add(Output, BorderLayout.SOUTH);
Words.setVisible(true);
}
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TranslatorFrame {
public static void main(String[] args) {
JFrame Words = new JFrame("Greetings Translator");
Words.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Did some research to find the line so the program
// would appear in the center of the screen
Font Font1 = new Font("SansSerif", Font.BOLD, 40);
JPanel WorkSpace = new JPanel();
JTextField Instructions = new JTextField("Enter \"Hello\" Here: ");
JTextField Input = new JTextField();
JPanel Center = new JPanel();
Center.setBackground(Color.lightGray);
Center.add(Instructions, BorderLayout.EAST);
Center.add(Input, BorderLayout.WEST);
final JTextField Output = new JTextField("");
Output.setFont(Font1);
Output.setPreferredSize(new Dimension(195, 100));
JTextField Header = new JTextField();
Header.setPreferredSize(new Dimension(195, 100));
Input.setPreferredSize(new Dimension(150, 50));
Input.setFont(Font1);
Instructions.setPreferredSize(new Dimension(375, 50));
Instructions.setBackground(Color.cyan);
// set the back ground color of my Instructions field so that it
// wouldn't
// look so gray and boring. There don't seem to be many preset colors to
// choose from.
Instructions.setFont(Font1);
Instructions.setEditable(false);
JPanel ButtonsArea = new JPanel();
ButtonsArea.setBackground(Color.lightGray);
ButtonsArea.setPreferredSize(new Dimension(300, 300));
final JButton French = new JButton("French");
French.setPreferredSize(new Dimension(200, 150));
French.setFont(Font1);
French.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource() == French)
;
Output.setText("Bonjour!");
}
});
JButton German = new JButton("German");
German.setPreferredSize(new Dimension(200, 150));
German.setFont(Font1);
JButton Spanish = new JButton("Spanish");
Spanish.setPreferredSize(new Dimension(200, 150));
Spanish.setFont(Font1);
ButtonsArea.add(French, BorderLayout.EAST);
ButtonsArea.add(German, BorderLayout.CENTER);
ButtonsArea.add(Spanish, BorderLayout.WEST);
ButtonsArea.add(Output, BorderLayout.SOUTH);
// Tried many different things to get the buttons and textfields
// to have space between them but nothing seems to work.
// Header.setSize(100,100);
Header.setFont(Font1);
Header.setText("Welcome!");
Header.setEditable(false);
WorkSpace.setBackground(Color.LIGHT_GRAY);
Words.pack();
Words.setSize(new Dimension(1000, 600));
Words.setLocationRelativeTo(null);
WorkSpace.add(Header);
Words.add(WorkSpace, BorderLayout.NORTH);
Words.add(Center, BorderLayout.CENTER);
/*
* Words.add(Instructions, BorderLayout.CENTER); Words.add(Input,
* BorderLayout.CENTER);
*/
Words.add(ButtonsArea, BorderLayout.SOUTH);
// Words.add(Output, BorderLayout.SOUTH);
Words.setVisible(true);
}
}

Why aren't the Jpanels working?

I am trying to write a program with JPanels and for the life of me, I can't seem to get the JPanels to go into the proper positions. I don't have a clue what I am doing wrong.
Here is some of the code I have so far:
package mainGUIWindowFrames;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class CustomerWindow extends JFrame
{
//Attribute
private JTextField textTF;
private JButton copyButton;
private JLabel copyLabel;
private Border panelEdge;
//Constructor
public CustomerWindow()
{
this.setBounds(100,100,800,600);
panelEdge = BorderFactory.createEtchedBorder();
JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
mainPanel.add(createCustomerPanel(), BorderLayout.NORTH);
mainPanel.add(createCustomerInfoPanel(), BorderLayout.EAST);
mainPanel.add(createSearchPanel(), BorderLayout.WEST);
}
//Operational Methods
public JPanel createCustomerPanel()
{
JPanel customerPanel = new JPanel();
JLabel customerL = new JLabel("Clients",SwingConstants.CENTER);
customerL.setForeground(Color.blue);
customerL.setFont(new Font("Copperplate Gothic Bold",Font.BOLD,48));
customerPanel.add(customerL);
customerPanel.setBorder(panelEdge);
return customerPanel;
}
public JPanel createCustomerInfoPanel()
{
JPanel infoPanel = new JPanel();
infoPanel.setBorder(panelEdge);
JLabel infoL = new JLabel("Clients",SwingConstants.CENTER);
infoL.setForeground(Color.blue);
infoL.setFont(new Font("Copperplate Gothic Bold",Font.BOLD,48));
infoPanel.add(infoL);
//add a text field
textTF = new JTextField(50);
infoPanel.add(textTF);
//add a button
copyButton = new JButton("Copy Text");
copyButton.addActionListener(new ButtonListener());
infoPanel.add(copyButton);
copyLabel = new JLabel("-----------------");
infoPanel.add(copyLabel);
return infoPanel;
}
public JPanel createSearchPanel()
{
JPanel lowerPanel = new JPanel();
JLabel label = new JLabel("Text Transferred from JList:");
//the spot where the data shows up
lowerPanel.add(label);
return lowerPanel;
}
The only Panel that shows up is the CreateCustomerPanel(). I have no idea what I need to do to get the other two panels to work.
If you could help me out that would be great!!
well I eventually wound up solving it by creating another panel and moving the panels I had out of the main constructor.
public CustomerWindow() {
panelEdge = BorderFactory.createEtchedBorder();
}
public JPanel createNorthPanel()
{
JPanel customerPanel = new JPanel();
JLabel customerL = new JLabel("Clients",SwingConstants.CENTER);
customerL.setForeground(Color.blue);
customerL.setFont(new Font("Copperplate Gothic Bold",Font.BOLD,48));
customerPanel.add(customerL);
customerPanel.setBorder(panelEdge);
return customerPanel;
}
//Operational Methods
public JPanel createCustomerPanel()
{
JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
mainPanel.add(createNorthPanel(), BorderLayout.NORTH);
mainPanel.add(createCustomerInfoPanel(), BorderLayout.EAST);
mainPanel.add(createSearchPanel(), BorderLayout.WEST);
return mainPanel;
}
public JPanel createCustomerInfoPanel()
{
JPanel infoPanel = new JPanel();
Box vBox = Box.createVerticalBox();
infoPanel.setBorder(panelEdge);
JLabel infoL = new JLabel("Clients",SwingConstants.CENTER);
infoL.setForeground(Color.blue);
infoL.setFont(new Font("Copperplate Gothic Bold",Font.BOLD,48));
infoPanel.add(infoL);
//add a text field
clientId = new JTextField(10);
vBox.add(clientId);
vBox.add(Box.createVerticalStrut(25));
fName = new JTextField(10);
vBox.add(fName);
vBox.add(Box.createVerticalStrut(25));
lName = new JTextField(10);
vBox.add(lName);
vBox.add(Box.createVerticalStrut(25));
address = new JTextField(10);
vBox.add(address);
vBox.add(Box.createVerticalStrut(25));
postalCode = new JTextField(10);
vBox.add(postalCode);
vBox.add(Box.createVerticalStrut(25));
number = new JTextField(10);
vBox.add(number);
vBox.add(Box.createVerticalStrut(25));
type = new JTextField(10);
vBox.add(type);
infoPanel.add(vBox);
return infoPanel;
Ive still got a lot of work to do but thanks to all those who helped me out!!
Based on your example, nothing should show up, as you've not added mainPanel to anything.
Once I did that, I was able to get
to show up...
Modified code example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
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.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
public class CustomerWindow extends JFrame {
//Attribute
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) {
}
CustomerWindow frame = new CustomerWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private JTextField textTF;
private JButton copyButton;
private JLabel copyLabel;
private Border panelEdge;
//Constructor
public CustomerWindow() {
this.setBounds(100, 100, 800, 600);
panelEdge = BorderFactory.createEtchedBorder();
JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
mainPanel.add(createCustomerPanel(), BorderLayout.NORTH);
mainPanel.add(createCustomerInfoPanel(), BorderLayout.EAST);
mainPanel.add(createSearchPanel(), BorderLayout.WEST);
add(mainPanel);
}
//Operational Methods
public JPanel createCustomerPanel() {
JPanel customerPanel = new JPanel();
JLabel customerL = new JLabel("Clients", SwingConstants.CENTER);
customerL.setForeground(Color.blue);
customerL.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 48));
customerPanel.add(customerL);
customerPanel.setBorder(panelEdge);
return customerPanel;
}
public JPanel createCustomerInfoPanel() {
JPanel infoPanel = new JPanel();
infoPanel.setBorder(panelEdge);
JLabel infoL = new JLabel("Clients", SwingConstants.CENTER);
infoL.setForeground(Color.blue);
infoL.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 48));
infoPanel.add(infoL);
//add a text field
textTF = new JTextField(50);
infoPanel.add(textTF);
//add a button
copyButton = new JButton("Copy Text");
// copyButton.addActionListener(new ButtonListener());
infoPanel.add(copyButton);
copyLabel = new JLabel("-----------------");
infoPanel.add(copyLabel);
return infoPanel;
}
public JPanel createSearchPanel() {
JPanel lowerPanel = new JPanel();
JLabel label = new JLabel("Text Transferred from JList:");
//the spot where the data shows up
lowerPanel.add(label);
return lowerPanel;
}
}
You didn't add the mainpanel in the constructor.
add(mainPanel);

getting JLabel to refresh after button clicked

I'm making a flash card application, and I'm trying to get it to where is has a JLabel at the top that says what the active set of flash cards is. The way I have it set up though, is that when the user clicks the "Add Set" button, it creates a button at the bottom with no real label to be called on.
So I was using ActionListener to try and get the label of the button itself, but the JLabel just shows the title of the Add Set button and doesn't change whenever a different button is clicked.
Heres my code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
public class GraphicsUI extends JPanel {
private DeckList setsList;
CardActions action = new CardActions();
JButton addSetButton, addCardButton;
private JLabel label;
private JPanel actives, optionsPanel,cardPanel, flashCardsPanel, bottomPanel;
private String name;
public GraphicsUI(){
this.setPreferredSize(new Dimension(1000,825));
this.setBackground(Color.LIGHT_GRAY);
actives = new JPanel();
actives.setPreferredSize(new Dimension(1000, 50));
actives.setBackground(Color.blue);
this.add(actives);
label = new JLabel();
actives.add(label);
optionsPanel = new JPanel();
optionsPanel.setPreferredSize(new Dimension(200, 350));
optionsPanel.setBackground(Color.cyan);
this.add(optionsPanel);
cardPanel = new JPanel();
cardPanel.setPreferredSize(new Dimension(580, 350));
cardPanel.setBackground(Color.green);
this.add(cardPanel);
flashCardsPanel = new JPanel();
flashCardsPanel.setPreferredSize(new Dimension(200, 350));
flashCardsPanel.setBackground(Color.white);
this.add(flashCardsPanel);
bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout());
bottomPanel.setPreferredSize(new Dimension(1000, 400));
bottomPanel.setBackground(Color.black);
this.add(bottomPanel);
this.addSetButton = new JButton("Add Set");
addSetButton.setPreferredSize(new Dimension(150, 30));
optionsPanel.add(addSetButton, BorderLayout.WEST);
addSetButton.addActionListener(new ButtonListener());
}
public class ButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
label.setText("Active set: " + e.getActionCommand());
if(e.getSource() ==addSetButton){
action.setCommand(CardActions.Command.ADDSET);
action.setList(getSetInfo());
}
}
}
private CardList getSetInfo(){
CardList cl = new CardList();
String setName = JOptionPane.showInputDialog("Enter the name of your set.");
if(setName.isEmpty()){
JOptionPane.showMessageDialog(this, "Cannot have an empty set.");
}
else{
cl.setSetName(setName);
ImageIcon img = new ImageIcon("setIcon.png");
JButton newset = new JButton(setName);
newset.setIcon(img);
newset.setBackground(Color.white);
bottomPanel.add(newset);
bottomPanel.revalidate();
}
return cl;
}
}
i think you forgot to add an ActionListener to your newSet Button, below you'll find a working example. I commented the two lines with the icon, so uncomment and try it.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
*
* #author ottp
* #version 1.0
*/
public class CardPanel extends JPanel {
final private JLabel label;
private JButton addSetButton;
private JPanel actives, optionsPanel,cardPanel, flashCardsPanel, bottomPanel;
public CardPanel() {
actives = new JPanel();
actives.setPreferredSize(new Dimension(1000, 50));
actives.setBackground(Color.BLUE);
this.add(actives);
label = new JLabel();
actives.add(label);
optionsPanel = new JPanel();
optionsPanel.setPreferredSize(new Dimension(200, 350));
optionsPanel.setBackground(Color.cyan);
this.add(optionsPanel);
cardPanel = new JPanel();
cardPanel.setPreferredSize(new Dimension(580, 350));
cardPanel.setBackground(Color.green);
this.add(cardPanel);
flashCardsPanel = new JPanel();
flashCardsPanel.setPreferredSize(new Dimension(200, 350));
flashCardsPanel.setBackground(Color.white);
this.add(flashCardsPanel);
bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout());
bottomPanel.setPreferredSize(new Dimension(1000, 400));
bottomPanel.setBackground(Color.black);
this.add(bottomPanel);
this.addSetButton = new JButton("Add Set");
addSetButton.setPreferredSize(new Dimension(150, 30));
optionsPanel.add(addSetButton, BorderLayout.WEST);
addSetButton.addActionListener(new ButtonListener());
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
label.setForeground(Color.WHITE);
label.setText("Active set: " + e.getActionCommand());
if(e.getSource().equals(addSetButton)) {
getSetInfo();
}
}
}
private void getSetInfo() {
String newSetName =
JOptionPane.showInputDialog(cardPanel, "Enter the name of your set", JOptionPane.INFORMATION_MESSAGE);
JButton newSet = new JButton(newSetName);
newSet.setBackground(Color.WHITE);
newSet.addActionListener(new ButtonListener());
bottomPanel.add(newSet);
bottomPanel.revalidate();
}
}
Greets
Patrick

Categories