Related
I've just begun coding in Java and was wondering how to achieve this. What I want is for the user to be able to input text into a text box, select the font, color and size which will then display in a label at the bottom when the Ok button is clicked. Any help would be appreciated. Thanks.
package textchanger;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class textchanger implements ActionListener {
String[] fontStrings = {"Arial", "Arial Black", "Helvetica", "Impact", "Times New Roman"};
String[] sizeStrings = {"10", "12", "14", "16", "18"};
String[] colorStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};
String[] bgStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};
JPanel panel;
JLabel labelText, labelFont, labelSize, labelColor, labelBG, labelOutput;
JTextField textField;
JComboBox comboFont, comboSize, comboColor, comboBG;
JButton btnOk, btnCancel;
public JPanel contentPane() { //Creates the GUI
panel = new JPanel();
panel.setLayout(new GridLayout(8, 8, 10, 10));
labelText = new JLabel("Enter Text:");
textField = new JTextField(10);
labelFont = new JLabel("Select font type:");
comboFont = new JComboBox(fontStrings);
comboFont.setSelectedIndex(0);
comboFont.addActionListener(this);
labelSize = new JLabel("Select font size:");
comboSize = new JComboBox(sizeStrings);
comboSize.setSelectedIndex(0);
comboSize.addActionListener(this);
labelColor = new JLabel("Select font color:");
comboColor = new JComboBox(colorStrings);
comboColor.setSelectedIndex(0);
comboColor.addActionListener(this);
labelBG = new JLabel("Select a background color:");
comboBG = new JComboBox(bgStrings);
comboBG.setSelectedIndex(0);
comboBG.addActionListener(this);
btnOk = new JButton("Ok");
btnCancel = new JButton("Cancel");
labelOutput = new JLabel("");
panel.add(labelText);
panel.add(textField);
panel.add(labelFont);
panel.add(comboFont);
panel.add(labelSize);
panel.add(comboSize);
panel.add(labelColor);
panel.add(comboColor);
panel.add(labelBG);
panel.add(comboBG);
panel.add(btnOk);
panel.add(btnCancel);
panel.add(labelOutput);
return panel;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Fonts, Colors and Sizes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 350);
textchanger txtObj = new textchanger();
frame.setContentPane(txtObj.contentPane());
frame.setVisible(true);
}
}
For clarity and other reasons, I'd avoid making the class implements ActionListener. Just add an anonymous ActionListener to each JComboBox. Something like this
JComboBox comboFont;
JLabel label = new JLabel("label");
String fontString = "ariel";
int fontWeight = Font.PLAIN;
int fontSize = 16;
Font font = new Font(fontString, fontWeight, fontSize);
Color textColor = Color.BLACK
public JPanel contentPane() {
comboFont = new JComboBox(fontStrings);
comboFont.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
fontString = (String)comboFont.getSelectedItem();
font = new Font(fontString, fontWeight, fontSize);
label.setFont(font);
}
});
}
What this will do is dynamically change the font when a new font is selected from the combobox. You should have global values for Font, fontSize and fontWeight so that each different combobox can make use of them and change the font accordingly in the actionPerformed
Also, take a look at this answer from AndrewThompson, showing the actual rendered font style in the JComboBox, with all the fonts obtained from the system fonts. Here's a glimpse. Don't forget to up-vote the answer in the link!
Give this a try. I revamped your code
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class textchanger {
//String[] fontStrings = {"Arial", "Arial Black", "Helvetica", "Impact", "Times New Roman"};
Integer[] fontSizes = {10, 12, 14, 16, 18, 20, 22, 24};
String[] colorStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};
String[] bgStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};
String[] fontStyle = {"BOLD", "Italic", "Plain"};
JPanel panel;
JLabel labelText, labelFont, labelSize, labelColor, labelBG, labelOutput;
JTextField textField;
JComboBox comboFont, comboSize, comboColor, comboBG;
JButton btnOk, btnCancel;
String fontString;
int fontWeight = Font.PLAIN;
int fontSize;
Font font = new Font(fontString, Font.PLAIN, fontSize);
Color textColor;
Color bgColor;
static String text = "Text";
static JLabel textLabel = new JLabel(text);
JPanel textLabelPanel = new JPanel(new GridBagLayout());
public JPanel contentPane() { //Creates the GUI
panel = new JPanel();
panel.setLayout(new GridLayout(7, 8, 10, 10));
textLabelPanel.setPreferredSize(new Dimension(500, 50));
labelText = new JLabel("Enter Text:");
textField = new JTextField(10);
textField.setText(text);
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
String newText = textField.getText();
textLabel.setText(newText);
}
#Override
public void removeUpdate(DocumentEvent e) {
String newText = textField.getText();
textLabel.setText(newText);
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
labelFont = new JLabel("Select font type:");
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();
comboFont = new JComboBox(fonts);
fontString = (String) comboFont.getItemAt(0);
comboFont.setSelectedIndex(0);
comboFont.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fontString = (String) comboFont.getSelectedItem();
font = new Font(fontString, fontWeight, fontSize);
textLabel.setFont(font);
}
});
labelSize = new JLabel("Select font size:");
comboSize = new JComboBox(fontSizes);
comboSize.setSelectedIndex(0);
fontSize = (Integer) comboSize.getItemAt(0);
comboSize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fontSize = (Integer) comboSize.getSelectedItem();
font = new Font(fontString, fontWeight, fontSize);
textLabel.setFont(font);
}
});
labelColor = new JLabel("Select font color:");
comboColor = new JComboBox(colorStrings);
comboColor.setSelectedIndex(0);
textColor = Color.RED;
textLabel.setForeground(textColor);
comboColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String colorString = (String) comboColor.getSelectedItem();
switch (colorString) {
case "Red":
textColor = Color.RED;
break;
case "Blue":
textColor = Color.BLUE;
break;
case "Green":
textColor = Color.GREEN;
break;
case "Yellow":
textColor = Color.YELLOW;
break;
case "Orange":
textColor = Color.ORANGE;
break;
default:
textColor = Color.RED;
}
textLabel.setForeground(textColor);
}
});
labelBG = new JLabel("Select a background color:");
comboBG = new JComboBox(bgStrings);
comboBG.setSelectedIndex(1);
bgColor = Color.BLUE;
textLabelPanel.setBackground(bgColor);
comboBG.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String bgColorString = (String) comboBG.getSelectedItem();
switch (bgColorString) {
case "Red":
bgColor = Color.RED;
break;
case "Blue":
bgColor = Color.BLUE;
break;
case "Green":
bgColor = Color.GREEN;
break;
case "Yellow":
bgColor = Color.YELLOW;
break;
case "Orange":
bgColor = Color.ORANGE;
break;
default:
bgColor = Color.RED;
}
textLabelPanel.setBackground(bgColor);
}
});
btnOk = new JButton("Ok");
btnCancel = new JButton("Cancel");
labelOutput = new JLabel("");
panel.add(labelText);
panel.add(textField);
panel.add(labelFont);
panel.add(comboFont);
panel.add(labelSize);
panel.add(comboSize);
panel.add(labelColor);
panel.add(comboColor);
panel.add(labelBG);
panel.add(comboBG);
panel.add(btnOk);
panel.add(btnCancel);
panel.add(labelOutput);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(panel);
textLabelPanel.add(textLabel);
mainPanel.add(textLabelPanel, BorderLayout.SOUTH);
return mainPanel;
}
class FontCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
Font font = new Font((String) value, Font.PLAIN, 20);
label.setFont(font);
return label;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Fonts, Colors and Sizes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 350);
textchanger txtObj = new textchanger();
frame.setContentPane(txtObj.contentPane());
frame.setVisible(true);
}
});
}
}
I created an Address Book GUI, I just don't understand How to make the save and delete buttons to work, so when the user fills the text fields they can click save and it saves to the JList I have created and then they can also delete from it. How Do I Do this?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AddressBook {
private JLabel lblFirstname,lblSurname, lblMiddlename, lblPhone,
lblEmail,lblAddressOne, lblAddressTwo, lblCity, lblPostCode, picture;
private JTextField txtFirstName, txtSurname, txtAddressOne, txtPhone,
txtMiddlename, txtAddressTwo, txtEmail, txtCity, txtPostCode;
private JButton btSave, btExit, btDelete;
private JList contacts;
private JPanel panel;
public static void main(String[] args) {
new AddressBook();
}
public AddressBook(){
JFrame frame = new JFrame("My Address Book");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.cyan);
lblFirstname = new JLabel("First name");
lblFirstname.setBounds(135, 50, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblFirstname.setFont(styleOne);
panel.add(lblFirstname);
txtFirstName = new JTextField();
txtFirstName.setBounds(210, 50, 150, 20);
panel.add(txtFirstName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(385,50,150,20);
Font styleTwo = new Font ("Arial",Font.BOLD,13);
lblSurname.setFont(styleTwo);
panel.add(lblSurname);
txtSurname = new JTextField();
txtSurname.setBounds(450,50,150,20);
panel.add(txtSurname);
lblMiddlename = new JLabel ("Middle Name");
lblMiddlename.setBounds(620,50,150,20);
Font styleThree = new Font ("Arial", Font.BOLD,13);
lblMiddlename.setFont(styleThree);
panel.add(lblMiddlename);
txtMiddlename = new JTextField();
txtMiddlename.setBounds(710,50,150,20);
panel.add(txtMiddlename);
lblPhone = new JLabel("Phone");
lblPhone.setBounds(160,100,100,20);
Font styleFour = new Font ("Arial", Font.BOLD,13);
lblPhone.setFont(styleFour);
panel.add(lblPhone);
txtPhone = new JTextField();
txtPhone.setBounds(210,100,150,20);
panel.add(txtPhone);
lblEmail = new JLabel("Email");
lblEmail.setBounds(410,100,100,20);
Font styleFive = new Font ("Arial", Font.BOLD,13);
lblEmail.setFont(styleFive);
panel.add(lblEmail);
txtEmail = new JTextField();
txtEmail.setBounds(450,100,150,20);
panel.add(txtEmail);
lblAddressOne = new JLabel("Address 1");
lblAddressOne.setBounds(145,150,100,20);
Font styleSix = new Font ("Arial", Font.BOLD,13);
lblAddressOne.setFont(styleSix);
panel.add(lblAddressOne);
txtAddressOne = new JTextField();
txtAddressOne.setBounds(210,150,150,20);
panel.add(txtAddressOne);
lblAddressTwo = new JLabel("Address 2");
lblAddressTwo.setBounds(145,200,100,20);
Font styleSeven = new Font ("Arial", Font.BOLD,13);
lblAddressTwo.setFont(styleSeven);
panel.add(lblAddressTwo);
txtAddressTwo = new JTextField();
txtAddressTwo.setBounds(210,200,150,20);
panel.add(txtAddressTwo);
lblCity = new JLabel("City");
lblCity.setBounds(180,250,100,20);
Font styleEight = new Font ("Arial", Font.BOLD,13);
lblCity.setFont(styleEight);
panel.add(lblCity);
txtCity = new JTextField();
txtCity.setBounds(210,250,150,20);
panel.add(txtCity);
lblPostCode = new JLabel("Post Code");
lblPostCode.setBounds(380,250,100,20);
Font styleNine = new Font ("Arial", Font.BOLD,13);
lblPostCode.setFont(styleNine);
panel.add(lblPostCode);
txtPostCode = new JTextField();
txtPostCode.setBounds(450,250,150,20);
panel.add(txtPostCode);
//image
ImageIcon image = new ImageIcon("C:\\Users\\Hassan\\Desktop\\icon.png");
picture = new JLabel(image);
picture.setBounds(600,90, 330, 270);
panel.add(picture);
//buttons
btSave = new JButton ("Save");
btSave.setBounds(380,325,100,20);
panel.add(btSave);
btDelete = new JButton ("Delete");
btDelete.setBounds(260,325,100,20);
panel.add(btDelete);
btExit = new JButton ("Exit");
btExit.setBounds(500,325,100,20);
panel.add(btExit);
btExit.addActionListener(new Action());
//list
contacts=new JList();
contacts.setBounds(0,10,125,350);
panel.add(contacts);
frame.add(panel);
frame.setVisible(true);
}
//button actions
static class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame option = new JFrame();
int n = JOptionPane.showConfirmDialog(option,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
Buttons need Event Handlers to work. You have not added any Event Handlers to the Save and Delete buttons. You need to call the addActionListener on those buttons too.
I recommend anonymous inner classes:
mybutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do whatever should happen when the button is clicked...
}
});
You need to addActionListener to the buttons btSave and btDelete.
You could create a anonymous class like this and perform your work there.
btSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
btDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
Edit:
I have an example to which you can refer to and accordingly make changes by understanding it. I got it from a professor at our institute.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TooltipTextOfList{
private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}
public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction extends MouseAdapter implements ActionListener{
public void actionPerformed(ActionEvent ae){
String data = txtItem.getText();
if (data.equals(""))
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box.");
else{
model.addElement(data);
JOptionPane.showMessageDialog(null,"Item added successfully.");
txtItem.setText("");
}
}
}
}
In this program, i have to create a GUI that saves objects of Contacts onto an array which then is turned into an array to be passed into the constructor of the default table model.
I know i'm doing an extra step here.
The back up button actually saves whatever is in the Vector of contacts onto a binary file.
The load button will load whatever file name you put in the username back into the vector.
The view all contacts should display everything that is in the vector(well technically the contactListArray).
I'm having this problem where i can't get the JTable on the view card to update. If I load the contacts, and then click load contacts it shows, so i know the data is being written into the .dat file correctly. The problem seems to be that once i click on the view button the JTable is creating and won't change, even though i have it set to change in the method.
The problem, i think, is down at the where is says if(source == viewBut)
that entire block i think may be the problem.
Thank you for your help in advance, i really appreciate it.
/*
* Lab number: Final Project
* Robert Lopez
* Section number: 4
*/
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.event.*;
import javax.swing.table.TableModel;
class Contact implements Serializable{ String firstName, lastName, eAddress, address, phoneNum; }
public class finalLab implements ActionListener{
static CardLayout layout;
static private JFrame frame = new JFrame("Address Book");
static private JButton[] topMenuButton = new JButton[5];
static private Vector<Contact> contactList = new Vector<Contact>();
static private int contactSize = 0;
static private String[] columnNames = {"First Name", "Last Name","E-Mail Address", "Address", "Phone Number"};
static private String[][] contactListArray;
//START--------------------------Menu Card----------------------------------------------
static JPanel menuCard = new JPanel(new BorderLayout());
static JPanel menuTop = new JPanel( new GridLayout(2,1) );
static private JLabel firstLabel = new JLabel("Use The Buttons Below To Manage Contacts");
static JPanel menuMid = new JPanel(new FlowLayout());
static private JLabel userName = new JLabel("User Name:");
static private JTextField userNameField = new JTextField("", 15);
static private JLabel numContacts = new JLabel("Number of Contacts:");
static private JTextField numContactsField= new JTextField("", 15);
static private JPanel menuLower = new JPanel(new GridLayout(2,8));
static private JButton loadBut = new JButton("Load Contacts");
static private JButton addBut = new JButton("Add New Contacts");
static private JButton searchBut = new JButton("Search Contacts");
static private JButton sortBut = new JButton("Sort Contacts");
static private JButton deleteBut = new JButton("Delete Contacts");
static private JButton viewBut = new JButton("View All Contacts");
static private JButton backupBut = new JButton("Backup Contacts");
static private JButton blankBut = new JButton("");
//END---------------------------------Menu Card------------------------------------
//START---------------------------------View Card------------------------------------
//View Panel
static private JPanel viewCard = new JPanel(new BorderLayout());
static private JPanel viewCardLower = new JPanel();
static private JLabel viewLabel = new JLabel("Contact List");
static private JTable viewContacts;
static private JPanel viewCardMid = new JPanel(new BorderLayout());
static private JTableHeader header;
static private JScrollPane scrollPane = new JScrollPane();
//END---------------------------------View Card------------------------------------
//START-----------------------------------Delete Card------------------------------------
//Delete Panel
static private JPanel deleteCard = new JPanel(new GridLayout (3,1));
static private JPanel deleteMid = new JPanel();
static private JPanel deleteLower = new JPanel();
static private JLabel deleteLabel = new JLabel("Delete Contacts");
static private JLabel contactInfoLabel = new JLabel("Contact Phone #");
static private JTextField contactInfoField = new JTextField("", 15);
//END-----------------------------------Delete Card---------------------------------
//START-----------------------------------Add Contact-------------------------------
static private JPanel addCard = new JPanel(new GridLayout(6,2));
static private JLabel firstNameLabel = new JLabel("First Name");
static private JLabel lastNameLabel = new JLabel("Last Name");
static private JLabel eAddressLabel = new JLabel(" E-Mail Address");
static private JLabel addressLabel = new JLabel("Address");
static private JLabel phoneNumLabel = new JLabel("Phone No.");
static private JTextField firstNameField = new JTextField("", 10);
static private JTextField lastNameField = new JTextField("", 10);
static private JTextField eAddressField = new JTextField("", 10);
static private JTextField addressField = new JTextField("", 10);
static private JTextField phoneNumField = new JTextField("", 10);
static private JButton saveContactBut = new JButton("Save New Contact");
static private JPanel addLowerLeft = new JPanel();
static private JPanel addLowerRight = new JPanel();
//END------------------------------------Add Contact-----------------------------
//****************************** MAIN METHOD *******************************
static JPanel contentPane = (JPanel)frame.getContentPane();
static private JPanel mainPanel = new JPanel();
public static void main(String[] args){
ActionListener AL = new finalLab();
mainPanel.setLayout(layout = new CardLayout() );
contentPane.setLayout(new BorderLayout());
//Buttons, Labels
loadBut.addActionListener(AL);
for(int i = 0; i < 5; i++){
topMenuButton[i] = new JButton("Top Menu");
topMenuButton[i].addActionListener(AL);
}
backupBut.addActionListener(AL);
viewBut.addActionListener(AL);
addBut.addActionListener(AL);
deleteBut.addActionListener(AL);
saveContactBut.addActionListener(AL);
//-------------------------------------------------------
//Top Menu
firstLabel.setHorizontalAlignment(JTextField.CENTER);
firstLabel.setFont(new Font( "serif", Font.BOLD, 25 ));
menuTop.add(firstLabel);
numContactsField.setEditable(false);
numContactsField.setText("" + contactSize);
//Adding Middle Content
menuMid.add(userName);
menuMid.add(userNameField);
menuMid.add(numContacts);
menuMid.add(numContactsField);
//Adding Lower Content
menuLower.add(loadBut);
menuLower.add(addBut);
menuLower.add(searchBut);
menuLower.add(sortBut);
menuLower.add(deleteBut);
menuLower.add(viewBut);
menuLower.add(backupBut);
menuLower.add(blankBut);
menuCard.add(menuTop, BorderLayout.NORTH);
menuCard.add(menuMid, BorderLayout.CENTER);
menuCard.add(menuLower, BorderLayout.SOUTH);
//-------------------------------------------------------
//Delete Card
deleteLabel.setHorizontalAlignment(JTextField.CENTER);
deleteLabel.setFont(new Font( "serif", Font.BOLD, 25 ));
deleteCard.add(deleteLabel);
deleteMid.add(contactInfoLabel);
deleteMid.add(contactInfoField);
deleteCard.add(deleteMid);
deleteLower.add(topMenuButton[0]);
deleteCard.add(deleteLower);
//-------------------------------------------------------
//Add Card
firstNameLabel.setHorizontalAlignment(JTextField.RIGHT);
lastNameLabel.setHorizontalAlignment(JTextField.RIGHT);
eAddressLabel.setHorizontalAlignment(JTextField.RIGHT);
addressLabel.setHorizontalAlignment(JTextField.RIGHT);
phoneNumLabel.setHorizontalAlignment(JTextField.RIGHT);
addCard.add(firstNameLabel);
addCard.add(firstNameField);
addCard.add(lastNameLabel);
addCard.add(lastNameField);
addCard.add(eAddressLabel);
addCard.add(eAddressField);
addCard.add(addressLabel);
addCard.add(addressField);
addCard.add(phoneNumLabel);
addCard.add(phoneNumField);
addLowerLeft.add(saveContactBut);
addLowerRight.add(topMenuButton[1]);
addCard.add(addLowerLeft);
addCard.add(addLowerRight);
//----------------------------------------------------------
//View Card
viewLabel.setHorizontalAlignment(JTextField.CENTER);
viewLabel.setFont(new Font( "serif", Font.BOLD, 25 ));
viewCard.add(viewLabel, BorderLayout.NORTH);
viewCardLower.add(topMenuButton[2]);
viewCard.add(viewCardLower, BorderLayout.SOUTH);
//Adding to frame
mainPanel.add("Menu Card", menuCard);
mainPanel.add("Delete Card", deleteCard);
mainPanel.add("Add Card", addCard);
//mainPanel.add("View Card", viewCard);
contentPane.add(mainPanel);
layout.show(mainPanel, "Menu Card");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 275);
frame.setResizable(false);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e){
Object source =e.getSource();
if(source == loadBut){
try {
FileInputStream fis = new FileInputStream (userNameField.getText());
ObjectInputStream ois = new ObjectInputStream(fis);
contactList.clear();
contactSize = 0;
for(; true; contactSize++){
contactList.add( (Contact) ois.readObject() );
numContactsField.setText("" + (contactSize+1) );
}
} catch(EOFException e2){
} catch(Exception e2){
e2.printStackTrace();
}
}
if(source == addBut)
layout.show(mainPanel, "Add Card");
if(source == viewBut){
contactListArray = new String[contactSize][5];
for(int i = 0; i < contactSize; i++){
contactListArray[i][0] = contactList.get(i).firstName;
contactListArray[i][1] = contactList.get(i).lastName;
contactListArray[i][2] = contactList.get(i).eAddress;
contactListArray[i][3] = contactList.get(i).address;
contactListArray[i][4] = contactList.get(i).phoneNum;
}
DefaultTableModel model = new DefaultTableModel(contactListArray,columnNames);
viewContacts = new JTable(model);
header = viewContacts.getTableHeader();
viewContacts.setFillsViewportHeight(true);
viewContacts.revalidate();
viewCardMid.add(header, BorderLayout.NORTH);
viewCardMid.add(viewContacts, BorderLayout.CENTER);
viewCard.add(viewCardMid, BorderLayout.CENTER);
mainPanel.add("View Card", viewCard);
layout.show(mainPanel, "View Card");
}
if(source == deleteBut)
layout.show(mainPanel, "Delete Card");
if(source == saveContactBut){
contactList.add(new Contact());
contactList.get(contactSize).firstName = firstNameField.getText();
contactList.get(contactSize).lastName = lastNameField.getText();
contactList.get(contactSize).eAddress = eAddressField.getText();
contactList.get(contactSize).address = addressField.getText();
contactList.get(contactSize).phoneNum = phoneNumField.getText();
contactSize++;
firstNameField.setText("");
lastNameField.setText("");
eAddressField.setText("");
addressField.setText("");
phoneNumField.setText("");
}
if(source == backupBut){
try{
FileOutputStream fos = new FileOutputStream (userNameField.getText(), false);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(int i = 0; i < contactSize; i++)
oos.writeObject(contactList.get(i));
oos.close();
}
catch (IOException e2){
System.out.println("IO Exception " + e2);
}
}
for(int i = 0; i < 5; i++)
if(source == topMenuButton[i]){
layout.show(mainPanel, "Menu Card");
numContactsField.setText("" + contactSize);
}
}
}
The problem revolves around you lack of understanding in how tables and the CardLayout works..
// This is good...
DefaultTableModel model = new DefaultTableModel(contactListArray, columnNames);
// This is bad...
viewContacts = new JTable(model);
// This is bad...and raises some eyebrows
header = viewContacts.getTableHeader();
// This okay, but doesn't belong here, and is pointless given the following code...
viewContacts.setFillsViewportHeight(true);
// Pointless, you've not added the component to anything yet..
viewContacts.revalidate();
// ?? What ??
viewCardMid.add(header, BorderLayout.NORTH);
// Not good. The table should be added to a JScrollPane first and the scroll
// pane added to the card
viewCardMid.add(viewContacts, BorderLayout.CENTER);
// Okay, but wrong place...
viewCard.add(viewCardMid, BorderLayout.CENTER);
// Here is your main problem. The card layout only allows one component to exist
// for a given name. If you try and add another card, it is discarded and the first
// component with that name remains
mainPanel.add("View Card", viewCard);
// Not bad...
layout.show(mainPanel, "View Card");
Instead of creating the table view when the view button is pressed, you should initalise and the view when you first create the UI and replace/update the table model when you click the view button...
In your constructor you should add...
viewContacts = new JTable(); // Don't need the model at this stage
viewContacts.setFillsViewportHeight(true);
viewCardMid.add(new JScrollPane(viewContacts), BorderLayout.CENTER);
mainPanel.add("View Card", viewCard);
And in your view button action code...
DefaultTableModel model = new DefaultTableModel(contactListArray, columnNames);
viewContacts.setModel(model);
mainPanel.add("View Card", viewCard);
Also, as has begin pointed about, you should not be using static class fields, it's not required in your case and will cause you issues as the complexity of your program grows.
You should be using if-else statements in you action performed method, this will reduce the possibility of logic errors and help improve performance
You should also investigate moving the logic for each view into it's own class, so as to reduce the clutter in your main class
Take the time to read through Creating a GUI With JFC/Swing, in particular, I'd looking into How to use Tables and How to use CardLayout
You make your variables static. The memory for static variables is not allocated on the stack but in regular memory. I didnt look at your code in detail but i would try to remove all static variables in your class and try again from there.
I am trying to align several elements in a Java Applet, I am not able to do it. Please help me. Here is my code:
public class User extends JApplet implements ActionListener,ItemListener {
public int sentp,recievedp,corruptedp;
public String stetus;
public double energi,nodeid,en;
TextField name,time,initene,ampco,acttran;
Button rsbt,vlbt,insd ;
Choice ch,ch2;
public String patrn;
public void init() {
this.setSize(800,600);
Label namep= new Label("\n\nEnter the No. of Nodes: ", Label.CENTER);
name = new TextField(5);
Label timep = new Label("\n\nEnter time of Simulation: ",Label.CENTER);
time = new TextField(5);
Label initen = new Label("\n\nInitial Energy Of Each Sensor Node:");
initene = new TextField("10^-4 Joules");
initene.setEditable(false);
Label ampcon = new Label("\n\nAmplifier Constant:");
ampco = new TextField("10^-12 Joules");
ampco.setEditable(false);
Label acttrans = new Label("\n\nEnergy Required To Activate Transmitter/Reciever:");
acttran = new TextField("50 ^ -9 Joules");
acttran.setEditable(false);
Label chp = new Label("\n\nSelect Radio Model:",Label.CENTER);
rsbt = new Button("Run The Simulation");
ch= new Choice();
ch.add("");
ch.add("Gaussian RadioModel");
ch.add("Rayleigh RadioModel");
Label pat= new Label("\n\nDistribution Pattern");
ch2= new Choice();
ch2.add("");
ch2.add("Rectangular Pattern");
ch2.add("Linear Pattern");
ch2.add("Random Pattern");
vlbt=new Button("ViewLog");
insd=new Button("Details of node");
JPanel cp = new JPanel();
this.add(cp);
GridBagLayout gridb = new GridBagLayout();
Container cont = getContentPane();
cont.setLayout(gridb);
add(cp);
GroupLayout layout = new GroupLayout(cp);
cp.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(namep)
.addComponent(name)
.addComponent(rsbt))
.addGroup(layout.createSequentialGroup()
.addComponent(timep)
.addComponent(time)
.addComponent(vlbt))
.addGroup(layout.createSequentialGroup()
.addComponent(chp)
.addComponent(ch))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(pat)
.addComponent(ch2))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(initen)
.addComponent(initene))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(ampcon)
.addComponent(ampco))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(acttrans)
.addComponent(acttran))
);
rsbt.addActionListener(this);
vlbt.addActionListener(this);
insd.addActionListener(this);
ch.addItemListener(this);
ch2.addItemListener(this);
}
Try this, is this good for you :
import java.awt.*;
import javax.swing.*;
public class AppletLayout extends JApplet
{
private JTextField noNodeField;
private JTextField timeSimField;
private JTextField iniEngField;
private JTextField ampConsField;
private JTextField engReqField;
private JComboBox selModeCombo;
private JComboBox distPattCombo;
private JButton runSimButton;
private JButton logButton;
private JButton detailNodeButton;
private String[] selectionModelString = {"", "Gaussian RadioModel"
, "Rayleigh RadioModel"};
private String[] distPatternString = {"", "Rectangular Pattern"
, "Linear Pattern"
, "Random Pattern"};
public void init()
{
try
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndDisplayGUI();
}
});
}
catch(Exception e)
{
System.err.println("Unable to Create and Display GUI : " + e.getMessage());
e.printStackTrace();
}
}
private void createAndDisplayGUI()
{
JLabel noNodeLabel = new JLabel("Enter the No. of Nodes :", JLabel.LEFT);
noNodeField = new JTextField(5);
JLabel timeSimLabel = new JLabel("Enter time of Simulation :", JLabel.LEFT);
timeSimField = new JTextField(5);
JLabel iniEngLabel = new JLabel("Initial Energy Of Each Sensor Node :", JLabel.LEFT);
iniEngField = new JTextField("10^-4 Joules");
JLabel ampConsLabel = new JLabel("Amplifier Constant :", JLabel.LEFT);
ampConsField = new JTextField("10^-12 Joules");
JLabel engReqLabel = new JLabel("Energy Required To Activate Transmitter/Reciever :", JLabel.LEFT);
engReqField = new JTextField("50 ^ -9 Joules");
JLabel selModeLabel = new JLabel("Select Radio Model :", JLabel.LEFT);
selModeCombo = new JComboBox(selectionModelString);
JLabel distPattLabel = new JLabel("Distribution Pattern :", JLabel.LEFT);
distPattCombo = new JComboBox(selectionModelString);
runSimButton = new JButton("Run Simulation");
logButton = new JButton("View Log");
detailNodeButton = new JButton("Details of Node");
JComponent contentPane = (JComponent) getContentPane();
JPanel topPanel = new JPanel();
topPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
topPanel.setLayout(new GridLayout(0, 2));
topPanel.add(noNodeLabel);
topPanel.add(noNodeField);
topPanel.add(timeSimLabel);
topPanel.add(timeSimField);
topPanel.add(iniEngLabel);
topPanel.add(iniEngField);
topPanel.add(ampConsLabel);
topPanel.add(ampConsField);
topPanel.add(engReqLabel);
topPanel.add(engReqField);
topPanel.add(selModeLabel);
topPanel.add(selModeCombo);
topPanel.add(distPattLabel);
topPanel.add(distPattCombo);
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
//buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.setLayout(new GridLayout(0, 1, 5, 5));
buttonPanel.add(runSimButton);
buttonPanel.add(logButton);
buttonPanel.add(detailNodeButton);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout(5, 5));
mainPanel.add(topPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.LINE_END);
contentPane.add(mainPanel, BorderLayout.PAGE_START);
setSize(1000, 600);
}
}
Here is the output :
Your current code looks pretty much like you are using some sort of GUI builder tool to generate the final layout.
For maximum control, build the component and add them to the panel. If you are looking to use GridBagLayout as shown in your code then follow the sequence construct as shown below
JPanel p1 = new JPanel(new GridBagLayout());
GridBagConstraints cs = new GridBagConstraints();
cs.fill = GridBagConstraints.HORIZONTAL;
lblUsername = new JLabel("Name: ");
cs.gridx = 0;
cs.gridy = 0;
cs.gridwidth = 1;
p1.add(lblUsername, cs);
txtUsername = new JTextField("", 20);
cs.gridx = 1;
cs.gridy = 0;
cs.gridwidth = 2;
p1.add(txtUsername, cs);
...
add(cp);
Or alternatively use BorderLayout or FlowLayout to hold the components on your panel:
JPanel p1 = new JPanel(new BorderLayout());
p1.add(lblUsername, BorderLaout.EAST);
...
When you say this
JPanel cp = new JPanel();
it means you're going to get a FlowLayout automatically. You probably want a different one.
Edit: OK, I can see where you're giving cp a GroupLayout, but I don't see where you pack() the window that cp is in or call setVisible().
Edit: But that doesn't matter for an applet.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I keep getting a NullPointerException each time I try to run the code using another class.
Can some please read through it somehow without running it? Because you would have to need the pictures. I just need to know if I did anything wrong, which I probably did since it is giving me this exception.
I really need help I don't know what to do, I've tried many things.
Stacktrace
java.lang.NullPointerException
at BurgerMakerPanel$TopBreadListener.updateLabel(BurgerMakerPanel.java:174)
at BurgerMakerPanel.<init>(BurgerMakerPanel.java:40)
at BurgerMaker.main(BurgerMaker.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
BurgerMaker.java
import javax.swing.JFrame;
public class BurgerMaker {
public static void main(String[] args) {
JFrame frame = new JFrame ("Burger Maker");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new BurgerMakerPanel());
frame.pack();
frame.setVisible(true);
}
}
BurgerMakerPanel.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BurgerMakerPanel extends JPanel{
private final int WIDTH = 600, HEIGHT = 1200;
private JLabel inputLabel, inputLabel2, inputLabel3, inputLabel4, inputLabel5, inputLabel6, inputLabel7, titleLabel, titleLabel2, topBreadPicture, bottomBreadPicture,
pattyPicture, cheesePicture, veggiePicture, saucePicture;
private JComboBox breadList, breadList2, pattyList, vegetableList, sauceList, cheeseList;
private JPanel primary, picturePanel, test, test2, test3, test4, titlePanel, spacePanel, topBreadPanel, bottomBreadPanel, pattyPanel, veggiePanel, saucePanel, cheesePanel;
private JButton push;
public BurgerMakerPanel() {
String[] breadStrings = {"White Bread Top", "Rye Bread Top", "Hamburger Bread Top", "Wheat Bread Top"};
String[] pattyStrings = {"Beef", "Chicken", "Pork"};
String[] veggieStrings = {"Lettuce", "Tomato", "Pickle", "Onion"};
String[] bread2Strings = {"White Bread Bottom", "Rye Bread Bottom", "Hamburger Bread Bottom", "Wheat Bread Bottom"};
String[] cheeseStrings = {"American", "Swiss Cheese", "Cheddar Cheese", "Pepper Jack Cheese"};
String[] sauceStrings = {"Mayonnaise", "Mustard", "Ketchup", "BBQ"};
push = new JButton("Create my Sandwich/Burger!");
TopBreadListener tbl = new TopBreadListener();
BottomBreadListener bbl = new BottomBreadListener();
PattyListener pl = new PattyListener();
CheeseListener cl = new CheeseListener();
SauceListener sl = new SauceListener();
VeggieListener vl = new VeggieListener();
JLabel separatorLabel = new JLabel(" ________________________________________________________________ " );
separatorLabel.setFont(new Font("Courier New", Font.BOLD, 14));
JLabel separatorLabel2 = new JLabel(" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " );
separatorLabel2.setFont(new Font("Courier New", Font.BOLD, 14));
inputLabel = new JLabel("Select your type of bottom bread:", SwingConstants.CENTER);
inputLabel.setFont(new Font("Verdana", Font.PLAIN, 14));
breadList = new JComboBox(breadStrings);
breadList.setSelectedIndex(3);
breadList.addActionListener(new TopBreadListener());
tbl.updateLabel(breadStrings[breadList.getSelectedIndex()]);
inputLabel2 = new JLabel("Select your type of patty:", SwingConstants.CENTER);
inputLabel2.setFont(new Font("Verdana", Font.PLAIN, 14));
pattyList = new JComboBox(pattyStrings);
pattyList.setSelectedIndex(2);
pattyList.addActionListener(new PattyListener());
pl.updateLabel(pattyStrings[pattyList.getSelectedIndex()]);
inputLabel3 = new JLabel("Select your type of sauce:", SwingConstants.CENTER);
inputLabel3.setFont(new Font("Verdana", Font.PLAIN, 14));
sauceList = new JComboBox(sauceStrings);
sauceList.setSelectedIndex(3);
sauceList.addActionListener(new SauceListener());
sl.updateLabel(sauceStrings[sauceList.getSelectedIndex()]);
inputLabel4 = new JLabel("Select your type of cheese:", SwingConstants.CENTER);
inputLabel4.setFont(new Font("Verdana", Font.PLAIN, 14));
cheeseList = new JComboBox(cheeseStrings);
cheeseList.setSelectedIndex(3);
cheeseList.addActionListener(new CheeseListener());
cl.updateLabel(cheeseStrings[cheeseList.getSelectedIndex()]);
inputLabel5 = new JLabel("Select your type of vegetable:", SwingConstants.CENTER);
inputLabel5.setFont(new Font("Verdana", Font.PLAIN, 14));
vegetableList = new JComboBox(veggieStrings);
vegetableList.setSelectedIndex(3);
vegetableList.addActionListener(new VeggieListener());
vl.updateLabel(veggieStrings[vegetableList.getSelectedIndex()]);
inputLabel6 = new JLabel("Select your type of top bread:", SwingConstants.CENTER);
inputLabel6.setFont(new Font("Verdana", Font.PLAIN, 14));
breadList2 = new JComboBox(bread2Strings);
breadList2.setSelectedIndex(4);
breadList2.addActionListener(new BottomBreadListener());
bbl.updateLabel(bread2Strings[breadList2.getSelectedIndex()]);
inputLabel7 = new JLabel("Press this only when you are done making your sandwich/burger!", SwingConstants.CENTER);
inputLabel7.setFont(new Font("Verdana", Font.BOLD, 14));
titleLabel = new JLabel("This is a program that will help you make your own sandwich or burger!", SwingConstants.CENTER);
titleLabel2 = new JLabel("Follow all directions and have fun! Thank you!", SwingConstants.CENTER);
titleLabel.setFont(new Font("Verdana", Font.BOLD, 15));
titleLabel2.setFont(new Font("Verdana", Font.BOLD, 15));
primary = new JPanel();
// Set up first subpanel
picturePanel = new JPanel();
spacePanel = new JPanel();
titlePanel = new JPanel();
topBreadPanel = new JPanel();
saucePanel = new JPanel();
pattyPanel = new JPanel();
cheesePanel = new JPanel();
veggiePanel = new JPanel();
bottomBreadPanel = new JPanel();
topBreadPanel.setPreferredSize(new Dimension(600, 70));
saucePanel.setPreferredSize(new Dimension(600, 7));
pattyPanel.setPreferredSize(new Dimension(600, 127));
cheesePanel.setPreferredSize(new Dimension(600, 9));
veggiePanel.setPreferredSize(new Dimension(600, 58));
bottomBreadPanel.setPreferredSize(new Dimension(600, 70));
test = new JPanel();
test2 = new JPanel();
test3 = new JPanel();
test4 = new JPanel();
titlePanel.setPreferredSize(new Dimension(600, 60));
spacePanel.setPreferredSize(new Dimension(600, 5));
test.setPreferredSize(new Dimension(500, 80));
test2.setPreferredSize(new Dimension(450, 80));
test3.setPreferredSize(new Dimension(450, 80));
test4.setPreferredSize(new Dimension(600, 60));
picturePanel.setPreferredSize(new Dimension(600, 600));
JLabel label1 = new JLabel ("Here is your finished product!");
picturePanel.add(label1);
picturePanel.add(topBreadPanel);
picturePanel.add(saucePanel);
picturePanel.add(pattyPanel);
picturePanel.add(cheesePanel);
picturePanel.add(veggiePanel);
picturePanel.add(bottomBreadPanel);
titlePanel.add(titleLabel);
titlePanel.add(titleLabel2);
test.add(inputLabel);
test.add(breadList);
test.add(inputLabel6);
test.add(breadList2);
test2.add(inputLabel2);
test2.add(pattyList);
test2.add(inputLabel4);
test2.add(cheeseList);
test3.add(inputLabel5);
test3.add(vegetableList);
test3.add(inputLabel3);
test3.add(sauceList);
test4.add(inputLabel7);
test4.add(push);
primary.add(spacePanel);
primary.add(titlePanel);
primary.add(separatorLabel2);
primary.add(test);
primary.add(test2);
primary.add(test3);
primary.add(test4);
primary.add(separatorLabel);
primary.add(spacePanel);
primary.add(picturePanel);
primary.setPreferredSize(new Dimension(WIDTH, HEIGHT));
}
public JPanel getPanel(){
return primary;
}
private class TopBreadListener implements ActionListener{
public void actionPerformed(ActionEvent e){
JComboBox ceb1 = (JComboBox)e.getSource();
String ingredientName1 = (String)ceb1.getSelectedItem();
updateLabel(ingredientName1);
}
public void updateLabel(String name) {
ImageIcon icon1 = new ImageIcon(name + ".png");
topBreadPicture.setIcon(icon1);
}
}
private class BottomBreadListener implements ActionListener{
public void actionPerformed(ActionEvent e){
JComboBox ceb2 = (JComboBox)e.getSource();
String ingredientName2 = (String)ceb2.getSelectedItem();
updateLabel(ingredientName2);
}
public void updateLabel(String name) {
ImageIcon icon2 = new ImageIcon(name + ".png");
bottomBreadPicture.setIcon(icon2);
}
}
private class PattyListener implements ActionListener{
public void actionPerformed(ActionEvent e){
JComboBox ceb3 = (JComboBox)e.getSource();
String ingredientName3 = (String)ceb3.getSelectedItem();
updateLabel(ingredientName3);
}
public void updateLabel(String name) {
ImageIcon icon3 = new ImageIcon(name + ".png");
pattyPicture.setIcon(icon3);
}
}
private class CheeseListener implements ActionListener{
public void actionPerformed(ActionEvent e){
JComboBox ceb4 = (JComboBox)e.getSource();
String ingredientName4 = (String)ceb4.getSelectedItem();
updateLabel(ingredientName4);
}
public void updateLabel(String name) {
ImageIcon icon4 = new ImageIcon(name + ".png");
cheesePicture.setIcon(icon4);
}
}
private class VeggieListener implements ActionListener{
public void actionPerformed(ActionEvent e){
JComboBox ceb5 = (JComboBox)e.getSource();
String ingredientName5 = (String)ceb5.getSelectedItem();
updateLabel(ingredientName5);
}
public void updateLabel(String name) {
ImageIcon icon5 = new ImageIcon(name + ".png");
veggiePicture.setIcon(icon5);
}
}
private class SauceListener implements ActionListener{
public void actionPerformed(ActionEvent e){
JComboBox ceb6 = (JComboBox)e.getSource();
String ingredientName6 = (String)ceb6.getSelectedItem();
updateLabel(ingredientName6);
}
public void updateLabel(String name) {
ImageIcon icon6 = new ImageIcon(name + ".png");
saucePicture.setIcon(icon6);
}
}
}
topBreadPicture is null and is not initialized.
topBreadPicture.setIcon(icon1);
The labels such as veggiePicture etc. are declared but never instantiated.
As to the images, it would be better to declare them as class attributes and load them at the same time that the labels are (being created &) added. Further on image loading, use ImageIO.read(File/URL) instead of using an ImageIcon to load it. The former will throw an exception if the image is not found, while the latter (AFAIR) will simply return a null image.
JComboBox ceb1 = (JComboBox)e.getSource();
String ingredientName1 = (String)ceb1.getSelectedItem();
updateLabel(ingredientName1);
there is potential for ceb1 to be null before calling getSelectedItem()
ImageIcon icon5 = new ImageIcon(name + ".png");
veggiePicture.setIcon(icon5);
veggiePicture is never initializied.
tbl.updateLabel(breadStrings[breadList.getSelectedIndex()]);
breadList.getSelectedIndex() can be -1 if nothing is selected
so breadStrings[-1] would return null therefore trying to pass a null parameter
could be wrong though..
Its still always good practice to check what you're putting as an argument first before passing it in.