How to get an Image when JComboBox is selected? - java

I want to display an Image, when a JComboxBox is selected.
When I select "Tesla Model S" from the combo box I want to display an Image above the combo.
Adding the Price into the JTextField works fine. I'm writing a Program where I can select a Car and accessories.
After I had selected the two Items, the price will show up in both text fields and I can add them.
Unfortunately I can't post any picture to show you my example.
I'm sorry if there is a lot of mess in my code. I tried different things but none of them worked
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Auto extends JFrame implements ActionListener, ItemListener {
JTextField AutoFeld;
JTextField AussFeld;
JTextField GesamtFeld;
JButton ResButton;
JButton ClearButton;
JCheckBox displayButton;
ImageIcon image1;
ImageIcon image2;
ImageIcon image3;
JLabel label1;
JLabel label2;
JLabel label3;
JLabel Ergebnis;
JLabel GesamtLabel;
JPanel panel0;
StringBuffer choices;
public Auto() {
this.setTitle("Auto");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
this.setLayout(new GridLayout(0, 10));
/*image1 = new ImageIcon(getClass().getResource("AMGgt.jpg"));
image2 = new ImageIcon(getClass().getResource("AudiA7.jpg"));
image3 = new ImageIcon(getClass().getResource("TeslaS.jpg"));
*/
GesamtLabel = new JLabel("Gesamt");
image1 = new ImageIcon(getClass().getResource("AMGgt.jpg"));
label1 = new JLabel(image1);
image2 = new ImageIcon(getClass().getResource("AudiA7.jpg"));
label2 = new JLabel(image2);
image3 = new ImageIcon(getClass().getResource("TeslaS.jpg"));
label3 = new JLabel(image3);
AutoFeld = new JTextField("0", 10);
AutoFeld.setEditable(true);
AussFeld = new JTextField("0", 10);
AussFeld.setEditable(true);
GesamtFeld = new JTextField("0", 15);
GesamtFeld.setEditable(false);
ResButton = new JButton("Ergebnis");
//ResButton.addActionListener(this);
ResButton.addActionListener(e -> {
Object source = e.getSource();
String s1 = AutoFeld.getText();
String s2 = AussFeld.getText();
int o1 = Integer.parseInt(s1);
int o2 = Integer.parseInt(s2);
if (source == ResButton) {
GesamtFeld.setText("" + (o1 + o2));
}
});
ClearButton = new JButton("Clear");
//ClearButton.addActionListener(this);
ClearButton.addActionListener(e -> {
Object source = e.getSource();
if (source == ClearButton) {
AutoFeld.setText("0");
AussFeld.setText("0");
GesamtFeld.setText("0");
}
});
displayButton = new JCheckBox("Helles Display");
displayButton.setSelected(true);
JPanel panel0 = new JPanel();
panel0.add(label1);
panel0.add(label2);
panel0.add(label3);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(3, 2));
String[] Autos = {"---Bitte Model auswählen---", "Tesla Model S", "Mercedes-AMG GT", "Audi A7"};
JComboBox AutoList = new JComboBox(Autos);
AutoList.addActionListener(e -> {
Object source = e.getSource();
JComboBox selectedChoice = (JComboBox) e.getSource();
if ("Tesla Model S".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("108420");
label1.getIcon();
} else if ("Mercedes-AMG GT".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("134351");
label2.getIcon();
} else if ("Audi A7".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("58350");
//label3.getIcon();
}
});
panel1.add(AutoList);
AutoList.setSelectedIndex(0);
//AutoList.addActionListener(this);
panel1.add(AutoFeld);
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(3, 2));
String[] Ausstattung = {"---Bitte Ausstattung auswählen---", "Sportsitze", "Navigationsgerät", "Kaffeehalter"};
JComboBox AussList = new JComboBox(Ausstattung);
panel2.add(AussList);
AussList.setSelectedIndex(0);
AussList.addActionListener(e -> {
JComboBox selectedChoice = (JComboBox) e.getSource();
if ("Sportsitze".equals(selectedChoice.getSelectedItem())) {
AussFeld.setText("1679");
} else if ("Navigationsgerät".equals(selectedChoice.getSelectedItem())) {
AussFeld.setText("90");
} else if ("Kaffeehalter".equals(selectedChoice.getSelectedItem())) {
AussFeld.setText("20");
}
});
panel2.add(AussFeld);
JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayout(3, 2));
panel3.add(GesamtLabel);
panel3.add(GesamtFeld);
JPanel panel4 = new JPanel();
panel4.add(ResButton);
panel4.add(ClearButton);
JPanel panel5 = new JPanel();
panel5.add(displayButton);
displayButton.setSelected(true);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(panel0);
panel.add(panel1);
panel.add(panel2);
panel.add(panel3);
panel.add(panel4);
panel.add(panel5);
panel.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
setContentPane(panel);
pack();
setResizable(true);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
//JComboBox selectedChoice = (JComboBox) e.getSource();
Object source = e.getSource();
JComboBox selectedChoice = (JComboBox) e.getSource();
String s1 = AutoFeld.getText();
String s2 = AussFeld.getText();
double o1 = Double.valueOf(s1);
double o2 = Double.valueOf(s2);
/*if(source == ClearButton) {
AutoFeld.setText("0");
AussFeld.setText("0");
GesamtFeld.setText("0");
} */
}
public static void main(String[] args) {
JFrame myApplication = new Auto();
myApplication.setVisible(true);
}
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
}
}

If you want to display one image, you only need one JLabel, so remove label2 and label3.
Initialize label1 with out any icon : label1 = new JLabel();
and have the action listener set the icon:
AutoList.addActionListener(e -> {
Object source = e.getSource();
JComboBox selectedChoice = (JComboBox) e.getSource();
if ("Tesla Model S".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("108420");
label1.setIcon(image1);
} else if ("Mercedes-AMG GT".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("134351");
label1.setIcon(image2);
} else if ("Audi A7".equals(selectedChoice.getSelectedItem())) {
AutoFeld.setText("58350");
label1.setIcon(image3);
}
});
You will also need to change the code of the clear button.

Related

Trying to add a JComboBox dropdown into a JTextField area

I have spent many hours digging around the web and cannot seem to find a straightforward answer or method to add a dropdown selection into my main panel that houses the various text fields, in this case, I am trying to add a paint color selection to the panel so that color can then be used as a variable in determining cost.
The closest I have come so far is having a combo box popup in a new window but then was unable to retrieve the selection.
package paintestimator;
import java.lang.String;
import java.awt.Button;
import java.awt.Choice;
import java.awt.Component;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.PopupMenu;
import javax.swing.JComboBox;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class PaintEstimator extends JFrame
{
private JTextField wallHeight = new JTextField(3);
private JTextField wallWidth = new JTextField(3);
private JTextField wallArea = new JTextField(3);
private JTextField gallonsNeeded = new JTextField(3);
private JTextField cansNeeded = new JTextField(3);
private JTextField paintTime = new JTextField(3);
private JTextField sColor = new JTextField(3);
private JTextField matCost = new JTextField(3);
private JTextField laborCost = new JTextField(3);
//Josh
public PaintEstimator()
{
JButton CalcChangeBTN = new JButton("Calculate");
JButton ClearBTN = new JButton("Clear");
JButton ChoiceA = new JButton("Paint Color");
//JComboBox vendorBTN = (new JComboBox());
ChoiceA.addActionListener(new ChoiceAListener());
CalcChangeBTN.addActionListener(new CalcChangeBTNListener());
ClearBTN.addActionListener(new ClearBTNListener());
wallHeight.setEditable(true);
wallWidth.setEditable(true);
wallArea.setEditable(false);
gallonsNeeded.setEditable(false);
paintTime.setEditable(false);
cansNeeded.setEditable(false);
sColor.setEditable(true);
matCost.setEditable(false);
laborCost.setEditable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(16, 3, 0, 0));
// need cost of paint array to set equations for material cost
// need combobox arrays for both color and cost
// vendor selection combo box sets array field for cost/color
mainPanel.add(new JLabel("Please enter wall height in feet"));
mainPanel.add(wallHeight);
mainPanel.add(new JLabel("please enter wall width in feet"));
mainPanel.add(wallWidth);
//box to show chosen color
//mainPanel.add(new JLabel("Color Chosen"));
// mainPanel.add(sColor);
mainPanel.add(new JLabel("wall area"));
mainPanel.add(wallArea);
mainPanel.add(new JLabel("Gallons Needed"));
mainPanel.add(gallonsNeeded);
mainPanel.add(new JLabel("Number of cans Needed"));
mainPanel.add(cansNeeded);
mainPanel.add(new JLabel("Time to paint in Hours"));
mainPanel.add(paintTime);
mainPanel.add(new JLabel("Cost of Labor"));
mainPanel.add(laborCost);
mainPanel.add(new JLabel("Total Cost of Material"));
mainPanel.add(matCost);
mainPanel.add( new JLabel("Select a Color"));
mainPanel.add (ChoiceA);
// mainPanel.add(sColor);
// Select<String> select = new Select<>();
//select.setLabel("Sort by");
//select.setItems("Most recent first", "Rating: high to low",
// "Rating: low to high", "Price: high to low", "Price: low to high");
//select.setValue("Most recent first");
// mainPanel.add(select);
mainPanel.add(CalcChangeBTN);
mainPanel.add(ClearBTN);
// mainPanel.add(ChoiceA);
setContentPane(mainPanel);
pack();
setTitle("Paint Estimator Tool");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
//Josh
class CalcChangeBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try
{
final double paintCvrGal = 320.0;
final double gallonsPerCan = 1.0;
double h = Integer.parseInt(wallHeight.getText());
double w = Integer.parseInt(wallWidth.getText());
double a = h * w;
double c = ((a / paintCvrGal) * gallonsPerCan);
double n = (c / gallonsPerCan);
double p = (int) ((a * 0.76) / 60);
double l = Integer.parseInt(laborCost.getText());
double labCost = l * p;
// double mc = c * CostofPaint
wallArea.setText(String.valueOf(a));
String wallArea = String.valueOf(a);
gallonsNeeded.setText(String.valueOf(c));
String gallonsNeeded = Double.toString(c);
cansNeeded.setText(String.valueOf(n));
String cansNeeded = Double.toString(n); // still need refine decimal point to #.0
(one decimal place)
paintTime.setText(String.valueOf(p));
String paintTime = String.valueOf(p);
laborCost.setText(String.valueOf(labCost));
String laborCost = Double.toString(labCost);
} catch (NumberFormatException f)
{
wallHeight.requestFocus();
wallHeight.selectAll();
}
}
}
class ClearBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// clear text fields and set focus
cansNeeded.setText("");
gallonsNeeded.setText("");
wallArea.setText("");
wallHeight.setText("");
wallWidth.setText("");
paintTime.setText("");
sColor.setText("");
laborCost.setText("");
//set focus
wallHeight.requestFocus();
}
}
class ChoiceAListener implements ActionListener
{
public void actionPreformed (ActionEvent e)
{
}
public static void main(String[] args)
{
PaintEstimator window = new PaintEstimator();
window.setVisible(true);
}
}
Below is the combo box I was able to create:
public static void main(String[] args)
{
String[] optionsToChoose =
{
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
JFrame jFrame = new JFrame();
JComboBox<String> jComboBox = new JComboBox<>(optionsToChoose);
jComboBox.setBounds(80, 50, 140, 20);
JButton jButton = new JButton("Done");
jButton.setBounds(100, 100, 90, 20);
JLabel jLabel = new JLabel();
jLabel.setBounds(90, 100, 400, 100);
jFrame.add(jButton);
jFrame.add(jComboBox);
jFrame.add(jLabel);
jFrame.setLayout(null);
jFrame.setSize(350, 250);
jFrame.setVisible(true);
jButton.addActionListener((ActionEvent e) ->
{
String selectedColor = "You selected " +
jComboBox.getItemAt(jComboBox.getSelectedIndex());
jLabel.setText(selectedColor);
});
}
Start by reading through How to Use Combo Boxes (and it wouldn't hurt to look over some the examples)
Start by creating an instance field for the combobox...
public class PaintEstimator extends JFrame {
//...
private JComboBox<String> colorChoice = new JComboBox<>();
//...
Next, create a ComboBoxModel to hold the values you want to present and replace the ChoiceA button with the combobox...
mainPanel.add(new JLabel("Select a Color"));
//mainPanel.add(ChoiceA);
// mainPanel.add(sColor);
String[] optionsToChoose = {
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(optionsToChoose);
colorChoice.setModel(model);
mainPanel.add(colorChoice);
And then in your ActionListener, get the selected value...
public void actionPerformed(ActionEvent e) {
try {
String choosenColor = (String) colorChoice.getSelectedItem();
System.out.println("choosenColor = " + choosenColor);
Runnable example...
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new PaintEstimator();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintEstimator extends JFrame {
private JTextField wallHeight = new JTextField(3);
private JTextField wallWidth = new JTextField(3);
private JTextField wallArea = new JTextField(3);
private JTextField gallonsNeeded = new JTextField(3);
private JTextField cansNeeded = new JTextField(3);
private JTextField paintTime = new JTextField(3);
private JTextField sColor = new JTextField(3);
private JTextField matCost = new JTextField(3);
private JTextField laborCost = new JTextField(3);
private JComboBox<String> colorChoice = new JComboBox<>();
public PaintEstimator() {
JButton CalcChangeBTN = new JButton("Calculate");
JButton ClearBTN = new JButton("Clear");
//ChoiceA.addActionListener(new ChoiceAListener());
CalcChangeBTN.addActionListener(new CalcChangeBTNListener());
ClearBTN.addActionListener(new ClearBTNListener());
wallHeight.setEditable(true);
wallWidth.setEditable(true);
wallArea.setEditable(false);
gallonsNeeded.setEditable(false);
paintTime.setEditable(false);
cansNeeded.setEditable(false);
sColor.setEditable(true);
matCost.setEditable(false);
laborCost.setEditable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(16, 3, 0, 0));
// need cost of paint array to set equations for material cost
// need combobox arrays for both color and cost
// vendor selection combo box sets array field for cost/color
mainPanel.add(new JLabel("Please enter wall height in feet"));
mainPanel.add(wallHeight);
mainPanel.add(new JLabel("please enter wall width in feet"));
mainPanel.add(wallWidth);
mainPanel.add(new JLabel("wall area"));
mainPanel.add(wallArea);
mainPanel.add(new JLabel("Gallons Needed"));
mainPanel.add(gallonsNeeded);
mainPanel.add(new JLabel("Number of cans Needed"));
mainPanel.add(cansNeeded);
mainPanel.add(new JLabel("Time to paint in Hours"));
mainPanel.add(paintTime);
mainPanel.add(new JLabel("Cost of Labor"));
mainPanel.add(laborCost);
mainPanel.add(new JLabel("Total Cost of Material"));
mainPanel.add(matCost);
mainPanel.add(new JLabel("Select a Color"));
String[] optionsToChoose = {
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(optionsToChoose);
colorChoice.setModel(model);
mainPanel.add(colorChoice);
mainPanel.add(CalcChangeBTN);
mainPanel.add(ClearBTN);
setContentPane(mainPanel);
pack();
setTitle("Paint Estimator Tool");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
class CalcChangeBTNListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String choosenColor = (String) colorChoice.getSelectedItem();
System.out.println("choosenColor = " + choosenColor);
final double paintCvrGal = 320.0;
final double gallonsPerCan = 1.0;
double h = Integer.parseInt(wallHeight.getText());
double w = Integer.parseInt(wallWidth.getText());
double a = h * w;
double c = ((a / paintCvrGal) * gallonsPerCan);
double n = (c / gallonsPerCan);
double p = (int) ((a * 0.76) / 60);
double l = Integer.parseInt(laborCost.getText());
double labCost = l * p;
// double mc = c * CostofPaint
wallArea.setText(String.valueOf(a));
String wallArea = String.valueOf(a);
gallonsNeeded.setText(String.valueOf(c));
String gallonsNeeded = Double.toString(c);
cansNeeded.setText(String.valueOf(n));
String cansNeeded = Double.toString(n);
paintTime.setText(String.valueOf(p));
String paintTime = String.valueOf(p);
laborCost.setText(String.valueOf(labCost));
String laborCost = Double.toString(labCost);
} catch (NumberFormatException f) {
wallHeight.requestFocus();
wallHeight.selectAll();
}
}
}
class ClearBTNListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
cansNeeded.setText("");
gallonsNeeded.setText("");
wallArea.setText("");
wallHeight.setText("");
wallWidth.setText("");
paintTime.setText("");
sColor.setText("");
laborCost.setText("");
//set focus
wallHeight.requestFocus();
}
}
}
}

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

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

Can't re-add the same panel

This is driving me insane. I'm trying to change the panels when you click on 3 different buttons and it works, but for one panel - only once.
If you click addPerson - the Person panel shows,
If you then click addCD - the CD panel shows; (same for view store)
If you then click on addPerson - it doesn't work. It throws a nullpointer exception.
Even if you click on addCD/viewstore and THEN add Person it shows but it just won't show a second time.
In a test file, I created a GUI with an add and remove: if I clicked add it threw the null pointer exception but if I just added it already and compiled, it was fine...
/* PERSON PANEL */
public JPanel create_PersonPnl()
{
personPnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
personPnl.setBackground(Color.WHITE);
personPnl.setPreferredSize(minPnl);
/* VERTICAL BOX for Person boxes */
Box personBox = Box.createVerticalBox();
personBox.setBorder(new TitledBorder(new LineBorder(Color.DARK_GRAY), "Person"));
/* Horizontal Box for Name Lbl & TF */
Box nameBox = Box.createHorizontalBox();
nameBox.add(Box.createHorizontalStrut(10));
nameLbl = new JLabel("Name: ");
nameBox.add(nameLbl);
nameBox.add(Box.createHorizontalStrut(5));
nameTF = new JTextField();
nameBox.add(nameTF);
nameBox.add(Box.createHorizontalStrut(10));
personBox.add(nameBox);
personBox.add(Box.createVerticalStrut(10));
Box limitBox = Box.createHorizontalBox();
limitBox.add(Box.createHorizontalStrut(10));
limitLbl = new JLabel("CD Limit: ");
limitBox.add(limitLbl);
limitTF = new JFormattedTextField();
limitBox.add(limitTF);
limitBox.add(Box.createHorizontalStrut(10));
personBox.add(limitBox);
personBox.add(Box.createVerticalStrut(10));
personBox.add(addPersonBtn = new JButton("Add Person"));
personBox.add(Box.createVerticalStrut(10));
personList = new JList(temp);
personList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollp = new JScrollPane(personList);
scrollp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollp.setSize(100, 45);
personBox.add(scrollp);
personBox.add(Box.createVerticalStrut(10));
Box optionsBox = Box.createHorizontalBox();
editPrsnBtn = new JButton("Edit");
editPrsnBtn.addActionListener(this);
optionsBox.add(editPrsnBtn);
removePrsnBtn = new JButton("Remove");
removePrsnBtn.addActionListener(this);
optionsBox.add(removePrsnBtn);
personBox.add(optionsBox);
personPnl.add(personBox);
return personPnl;
}
This is what is in my ActionPerformed method.
if(e.getSource() == addPersonBtn)
{
changePnl.removeAll();
changePnl.add(create_PersonPnl());
changePnl.revalidate();
System.out.println("PersonPnl added");
}
if(e.getSource() == addCDBtn)
{
changePnl.removeAll();
changePnl.add(create_CDPnl());
changePnl.revalidate();
}
if(e.getSource() == viewStoreBtn)
{
changePnl.removeAll();
changePnl.add(create_StorePnl());
changePnl.revalidate();
}
Only code for ChangePnl.
changePnl = new JPanel();
changePnl.setBackground(Color.WHITE);
defaultPnl = new JPanel();
defaultPnl.setBackground(Color.WHITE);
defaultPnl.add(new JLabel("Welcome to the CD Store"));
defaultPnl.add(new JLabel("Click an option from the left"));
changePnl.add(defaultPnl);
The S.O.P was to debug to see what was being run.. and that only prints once and that's it unless I take out .add(create_PersonPnl()); so I've narrowed it but I don't have a clue since it works the first time.
Thank in advance!
Separate test file to prove it's create_PersonPnl()
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class Test implements ActionListener
{
JButton add, remove;
JButton addPersonBtn, editPrsnBtn, removePrsnBtn;
JFrame frame;
JFormattedTextField limitTF;
JLabel nameLbl, limitLbl;
JList personList;
JPanel TotalGUI, welcomePnl, mainPnl, imagePnl, changePnl, defaultPnl, cdPnl, storePnl;
JPanel personPnl;
JScrollPane scrollp;
JTextField nameTF;
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
Dimension minPnl = new Dimension(300, 400);
/* Test for JList */
String[] temp = {"1", "2", "3", "4", "1", "2", "3", "4","1", "2", "3", "4","1", "2", "3", "4" };
public Test()
{
frame = new JFrame("CD Store");
frame.setExtendedState(JFrame.NORMAL);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.pack(); //sets size based on components size in TotalGUI
//frame.setJMenuBar(create_MenuBar());
//frame.setMinimumSize(minDim);
frame.setSize(725, 550);
//set frame location (central to screen)
int fw = frame.getSize().width;
int fh = frame.getSize().height;
int fx = (dim.width-fw)/2;
int fy = (dim.height-fh)/2;
frame.getContentPane().add(create_Content_Pane());
frame.setVisible(true);
//moves the frame to the centre
frame.setLocation(fx, fy);
}
public JPanel create_Content_Pane()
{
JPanel TotalGUI = new JPanel();
TotalGUI.add(remove = new JButton("Remove"));
remove.addActionListener(this);
TotalGUI.add(add = new JButton("Add")); <- this crashes when selected
add.addActionListener(this);
//TotalGUI.add(create_PersonPnl()); <- works just fine
return TotalGUI;
}
public JPanel create_PersonPnl()
{
personPnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
personPnl.setBackground(Color.WHITE);
personPnl.setPreferredSize(minPnl);
/* VERTICAL BOX for Person boxes */
Box personBox = Box.createVerticalBox();
personBox.setBorder(new TitledBorder(new LineBorder(Color.DARK_GRAY), "Person"));
/* Horizontal Box for Name Lbl & TF */
Box nameBox = Box.createHorizontalBox();
nameBox.add(Box.createHorizontalStrut(10));
nameLbl = new JLabel("Name: ");
nameBox.add(nameLbl);
nameBox.add(Box.createHorizontalStrut(5));
nameTF = new JTextField();
nameBox.add(nameTF);
nameBox.add(Box.createHorizontalStrut(10));
personBox.add(nameBox);
personBox.add(Box.createVerticalStrut(10));
Box limitBox = Box.createHorizontalBox();
limitBox.add(Box.createHorizontalStrut(10));
limitLbl = new JLabel("CD Limit: ");
limitBox.add(limitLbl);
limitTF = new JFormattedTextField();
limitBox.add(limitTF);
limitBox.add(Box.createHorizontalStrut(10));
personBox.add(limitBox);
personBox.add(Box.createVerticalStrut(10));
personBox.add(addPersonBtn = new JButton("Add Person"));
personBox.add(Box.createVerticalStrut(10));
personList = new JList(temp);
personList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollp = new JScrollPane(personList);
scrollp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollp.setSize(100, 45);
personBox.add(scrollp);
personBox.add(Box.createVerticalStrut(10));
Box optionsBox = Box.createHorizontalBox();
editPrsnBtn = new JButton("Edit");
editPrsnBtn.addActionListener(this);
optionsBox.add(editPrsnBtn);
removePrsnBtn = new JButton("Remove");
removePrsnBtn.addActionListener(this);
optionsBox.add(removePrsnBtn);
personBox.add(optionsBox);
personPnl.add(personBox);
return personPnl;
}
public static void main(String[] args)
{
new Test();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == remove)
{
TotalGUI.removeAll();
TotalGUI.revalidate();
}
if(e.getSource() == add)
{
TotalGUI.add(create_PersonPnl());
TotalGUI.revalidate();
}
}
}
In your method
public JPanel create_Content_Pane()
{
JPanel TotalGUI = new JPanel();
TotalGUI.add(remove = new JButton("Remove"));
remove.addActionListener(this);
TotalGUI.add(add = new JButton("Add")); <- this crashes when selected
add.addActionListener(this);
//TotalGUI.add(create_PersonPnl()); <- works just fine
return TotalGUI;
}
The NullPointerException occurs because your private field TotalGUI is null... Remove the JPanel declaration in front of TotalGUI = new JPanel(); That will solve the null pointer problem. This probably solves only your problem in the test scenario... To solve the problem in your original scenario it would be nice to have the complete source code of the class..

Categories