Why am I getting a NullPointerException in my code? [closed] - java

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.

Related

Setting the font of a JTextArea

I want to create a Text Editor in Java. Here is what I've written so far:
package com.thundercrust.applications;
import java.awt.BorderLayout;
public class TextEditor implements ActionListener{
private static String[] fontOptions = {"Serif", "Agency FB", "Arial", "Calibri", "Cambrian", "Century Gothic", "Comic Sans MS", "Courier New", "Forte", "Garamond", "Monospaced", "Segoe UI", "Times New Roman", "Trebuchet MS", "Serif"};
private static String[] sizeOptions = {"8", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28"};
ImageIcon newIcon = new ImageIcon("res/NewIcon.png");
ImageIcon saveIcon = new ImageIcon("res/SaveIcon.png");
ImageIcon openIcon = new ImageIcon("res/OpenIcon.png");
ImageIcon fontIcon = new ImageIcon("res/FontIcon.png");
ImageIcon changeFontIcon = new ImageIcon("res/ChangeFontIcon.png");
JButton New = new JButton(newIcon);
JButton Save = new JButton(saveIcon);
JButton Open = new JButton(openIcon);
JButton changeFont = new JButton(changeFontIcon);
JLabel fontLabel = new JLabel(fontIcon);
JLabel fontLabelText = new JLabel("Font: ");
JLabel fontSizeLabel = new JLabel("Size: ");
JComboBox <String> fontName = new JComboBox<>(fontOptions);
JComboBox <String> fontSize = new JComboBox<>(sizeOptions);
JToolBar tool = new JToolBar();
JTextArea texty = new JTextArea();
JScrollPane scroll = new JScrollPane(texty);
private static final int WIDTH = 1366;
private static final int HEIGHT = WIDTH / 16 * 9;
private static String name = "Text Editor";
private static JFrame frame = new JFrame();
public void Display() {
frame.setTitle(name);
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
New.addActionListener(this);
New.setToolTipText("Creates a new File");
Save.addActionListener(this);
Save.setToolTipText("Saves the current File");
Open.addActionListener(this);
Open.setToolTipText("Opens a file");
changeFont.addActionListener(this);
changeFont.setToolTipText("Change the Font");
fontLabel.setToolTipText("Font");
fontLabelText.setToolTipText("Set the kind of Font");
fontSizeLabel.setToolTipText("Set the size of the Font");
tool.add(New);
tool.addSeparator();
tool.add(Save);
tool.addSeparator();
tool.add(Open);
tool.addSeparator();
tool.addSeparator();
tool.addSeparator();
tool.add(fontLabel);
tool.addSeparator();
tool.add(fontLabelText);
tool.add(fontName);
tool.addSeparator();
tool.add(fontSizeLabel);
tool.add(fontSize);
tool.addSeparator();
tool.add(changeFont);
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
pane.add(tool, "North");
pane.add(scroll, "Center");
frame.setContentPane(pane);
}
public static void main(String args[]) {
TextEditor editor = new TextEditor();
editor.Display();
}
public void actionPerformed(ActionEvent evt) {
String fontNameSet;
String fontSizeSetTemp;
int fontSizeSet;
Object source = evt.getSource();
if(source == New) {
texty.setText("");
}
else if(source == changeFont) {
fontNameSet = (String) fontName.getSelectedItem();
fontSizeSetTemp = (String) fontSize.getSelectedItem();
fontSizeSet = Integer.parseInt(fontSizeSetTemp);
System.out.println(fontNameSet + fontSizeSet);
scroll.setFont(new Font(fontNameSet, fontSizeSet, Font.PLAIN));
}
}
}
My problem is with setting fonts for the JTextArea. When I click the changeFont button on my actual program, nothing happens. What do I do?
new Font(fontNameSet, fontSizeSet, Font.PLAIN)
This has the arguments in the wrong order. It should be:
new Font(fontNameSet, Font.PLAIN, fontSizeSet)
Also, as mentioned in a comment:
scroll.setFont(new Font(fontNameSet, fontSizeSet, Font.PLAIN));
Should be:
texty.setFont(new Font(fontNameSet, Font.PLAIN, fontSizeSet));

Can't seem to get .remove to work

So for a class that I am currently taking I need to create an ATM System. So, I decided to have 2 panels. A main panel, where all of the processes take place, and an options panel, where the options are listed for the user. The problem, as mentioned above, is that I can't seem to get the main panel to be removed so I can actually replace it with the panel for, say the create account screen. In fact, all that happens is that the terminal window shows. Completely blank. As far as I have checked, the buttons event is firing and it even gets past the remove function.
In any event, I can't seem to figure out what the problem is, perhaps it is because the button being pressed is also being removed with the panel. Here's the related code.
public class AccountSystem extends JFrame implements ActionListener
{
public static Account currentuser = new Account(); //This is so that the methods know which account is currently logged in so they can perform operations on it.
public static int count=0;
public static Account acc[] = new Account[1000];
public static String parts[] = new String[3];
private JButton login, logout, createacc, deposit1, deposit2, withdraw1, withdraw2, transfer1, transfer2, nevermind;
private JPanel options, mainarea, titlecard;
private JTextField username, password, transfer, depositarea, withdrawarea, retypearea;
private JLabel userprompt, depositprompt, withdrawpromt, balancedisp, passwordprompt, mainmessage, title;
private String newuser, newpass, newpassconfirm;
BorderLayout borderlayout;
GridLayout gridlayout;
public AccountSystem()
{
borderlayout = new BorderLayout();
borderlayout.setHgap(5);
borderlayout.setVgap(5);
//Establishing our buttons here.
JButton login = new JButton("Login");
login.addActionListener(this);
JButton createacc = new JButton("New Account");
createacc.addActionListener(this);
//Establishing our panels here.
JPanel options = new JPanel();
JPanel mainarea = new JPanel();
JPanel titlecard = new JPanel();
//Establishing our JLabel here.
JLabel userprompt = new JLabel("Username: ");
JLabel passwordprompt = new JLabel("Password: ");
JLabel title = new JLabel(" LOGIN ");
//Establishing our textfields here.
JTextField username = new JTextField(20);
JTextField password = new JTextField(20);
JTextField transfer = new JTextField(20);
JTextField withdrawarea = new JTextField(20);
//Building the GUI here.
titlecard.setSize(500,50);
titlecard.setLocation (0,0);
mainarea.setSize(300,450);
mainarea.setLocation(0,50);
options.setSize(150,450);
options.setLocation(300,50);
titlecard.add(title);
mainarea.add(userprompt);
mainarea.add(username);
mainarea.add(passwordprompt);
mainarea.add(password);
mainarea.add(login);
mainarea.add(createacc);
getContentPane().setLayout(null);
getContentPane().add(titlecard);
getContentPane().add(mainarea);
getContentPane().add(options);
}
}
public void actionPerformed (ActionEvent e)
{
if ((e.getActionCommand()).equals("Login"))
{
login();
}
else if ((e.getActionCommand()).equals("New Account"))
{
accountmaker();
}
else if ((e.getActionCommand()).equals("Deposit Funds"))
{
deposit();
}
else if ((e.getActionCommand()).equals("Withdraw Funds"))
{
withdraw();
}
else if ((e.getActionCommand()).equals("Withdraw"))
{
withdrawprocedure();
}
else if ((e.getActionCommand()).equals("Create Account"))
{
accountprocedure();
}
}
public void accountmaker() //This is the screen where the user creates the account they want to. Of course, something needed to be done to differentiate this screen and the login screen.
{
currentuser = null; //This is so that the program doesn't get somehow confused when dealing with multiple uses of the program.
getContentPane().remove(mainarea);
title.setText("Create New Account");
mainarea = new JPanel();
JLabel userprompt = new JLabel ("Username: ");
JLabel passwordprompt = new JLabel("Password: ");
JLabel retype = new JLabel ("Retype: "); //This is what makes it different from the login screen
createacc = new JButton ("Create Account");
createacc.addActionListener(this);
JButton nevermind = new JButton("Cancel");
nevermind.addActionListener(this);
JTextField username = new JTextField(20);
JTextField password = new JTextField(20);
retypearea = new JTextField(20);
mainarea.setSize(300,500);
mainarea.setLocation(0,0);
mainarea.add(userprompt);
mainarea.add(username);
mainarea.add(passwordprompt);
mainarea.add(password);
mainarea.add(retype);
mainarea.add(retypearea);
getContentPane().add(mainarea);
getContentPane().invalidate();
getContentPane().validate();
getContentPane().repaint();
}
And this is the Account class that the program uses.
public class Account
{
private String username;
private String password;
private double balance=0;
public void deposit (double deposit)
{
balance += deposit;
}
public void withdraw (double withdraw)
{
balance -= withdraw;
}
public void setBalance (double newbalance)
{
balance = newbalance;
}
public void setUsername (String newusername)
{
username = newusername;
}
public void setPassword (String newpassword)
{
password = newpassword;
}
public String getUsername ()
{
return username;
}
public double getbalance ()
{
return balance;
}
public String getpassword()
{
return password;
}
}
If I understand correctly.. you basically need to replace the main panel with account panel on certain event!
I have written example code (please modify it according to your project)
In this code.. I have created 4 panels namely
Component Panel: To hold all components
Main Panel: contains the label with text "Main Panel" and its border is painted RED
Account Panel: contains the label with text "Account Panel" and its border is painted GREEN
Option Panel: empty panel with its border is painted BLUE
Two buttons:
Account Button: Which should replace Main Panel with Account Panel
Main Button: Which should replace Account Panel with Main Panel
Using GridBagLayout, all you need to do is to place Main Panel and Account Panel at the same location i.e. gridx = 0 and gridy = 0 for both. At first Main Panel shall be displayed. On event "Account Button" set Main Panel's visibility false and Account Panels' true. For event "Main Button" do the vica versa. GridBagLayout is fantastic dynamic layout which manages the empty spacing by itslef without any distortion.
public class SwingSolution extends JFrame implements ActionListener
{
private JPanel componentPanel = null;
private JPanel mainPanel = null;
private JLabel mainLabel = null;
private JPanel optionPanel = null;
private JPanel accountPanel = null;
private JLabel accountLabel = null;
private JButton replaceToAccountPanel = null;
private JButton replaceToMainPanel = null;
private final static String MAIN_TO_ACCOUNT = "MainToAccount";
private final static String ACCOUNT_TO_MAIN = "AccountToMain";
public JPanel getComponentPanel()
{
if(null == componentPanel)
{
componentPanel = new JPanel();
GridBagLayout gridBagLayout = new GridBagLayout();
componentPanel.setLayout(gridBagLayout);
GridBagConstraints constraint = new GridBagConstraints();
constraint.insets = new Insets(10, 10, 10, 10);
mainPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 0;
mainPanel.setMinimumSize(new Dimension(100, 50));
mainPanel.setPreferredSize(new Dimension(100, 50));
mainPanel.setMaximumSize(new Dimension(100, 50));
mainPanel.setBorder(
BorderFactory.createLineBorder(Color.RED));
mainLabel = new JLabel("Main Panel");
mainPanel.add(mainLabel);
componentPanel.add(mainPanel, constraint);
accountPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 0;
accountPanel.setMinimumSize(new Dimension(100, 50));
accountPanel.setPreferredSize(new Dimension(100, 50));
accountPanel.setMaximumSize(new Dimension(100, 50));
accountPanel.setBorder(
BorderFactory.createLineBorder(Color.GREEN));
accountLabel = new JLabel("Account Panel");
accountPanel.add(accountLabel);
componentPanel.add(accountPanel, constraint);
optionPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 1;
optionPanel.setMinimumSize(new Dimension(100, 50));
optionPanel.setPreferredSize(new Dimension(100, 50));
optionPanel.setMaximumSize(new Dimension(100, 50));
optionPanel.setBorder(
BorderFactory.createLineBorder(Color.BLUE));
componentPanel.add(optionPanel, constraint);
replaceToAccountPanel = new JButton("Account Button");
replaceToAccountPanel.setName(MAIN_TO_ACCOUNT);
constraint.gridx = 0;
constraint.gridy = 2;
replaceToAccountPanel.setSize(new Dimension(800, 30));
replaceToAccountPanel.addActionListener(this);
componentPanel.add(replaceToAccountPanel, constraint);
replaceToMainPanel = new JButton("Main Button");
replaceToMainPanel.setName(ACCOUNT_TO_MAIN);
constraint.gridx = 1;
constraint.gridy = 2;
replaceToMainPanel.setMinimumSize(new Dimension(800, 30));
replaceToMainPanel.addActionListener(this);
componentPanel.add(replaceToMainPanel, constraint);
}
return componentPanel;
}
public void actionPerformed (ActionEvent evt)
{
JButton buttonClicked = (JButton) evt.getSource();
if(buttonClicked != null)
{
if(buttonClicked.getName().equals(MAIN_TO_ACCOUNT))
{
mainPanel.setVisible(false);
accountPanel.setVisible(true);
}
else if(buttonClicked.getName().equals(ACCOUNT_TO_MAIN))
{
mainPanel.setVisible(true);
accountPanel.setVisible(false);
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
SwingSolution main = new SwingSolution();
frame.setTitle("Simple example");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setContentPane(main.getComponentPanel());
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

How Do I get the buttons to work? Java Programming

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

Elements Alignment in Java Applet

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.

JTextArea - How to set text at a specified offset?

I want to set some text at a specified offset in my JTextArea. Let's say I have already in my edit "aaa bbb" and I want to overwrite "bbb" with "house", how can I do that in Java?
You could use replaceRange()
public void replaceRange(String str,
int start,
int end)
Replaces text from the indicated start to end position with the new text specified. Does nothing if the model is null. Simply does a delete if the new string is null or empty.
This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.
You need to take a look at three methods setSelectionStart(...), setSelectionEnd(...) and replaceSelection(...).
Here is a small sample program to help your cause :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextAreaSelection
{
private JTextField replaceTextField;
private JTextField startIndexField;
private JTextField endIndexField;
private void createAndDisplayGUI()
{
final JFrame frame = new JFrame("JTextArea Selection");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setOpaque(true);
final JTextArea tarea = new JTextArea(10, 10);
tarea.setText("aaa bbb");
final JButton updateButton = new JButton("UPDATE TEXT");
updateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//tarea.setSelectionStart(4);
//tarea.setSelectionEnd(7);
//tarea.replaceSelection("house");
int selection = JOptionPane.showConfirmDialog(null, getPanel());
if (selection == JOptionPane.OK_OPTION)
{
if (replaceTextField.getDocument().getLength() > 0
&& startIndexField.getDocument().getLength() > 0
&& endIndexField.getDocument().getLength() > 0)
{
String text = replaceTextField.getText().trim();
int start = Integer.parseInt(startIndexField.getText().trim());
int end = Integer.parseInt(endIndexField.getText().trim());
tarea.replaceRange(text, start, end);
}
}
}
});
contentPane.add(tarea, BorderLayout.CENTER);
contentPane.add(updateButton, BorderLayout.PAGE_END);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
}
private JPanel getPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2, 2, 2));
JLabel replaceLabel = new JLabel("Enter new String : "
, JLabel.CENTER);
replaceTextField = new JTextField(10);
JLabel startIndexLabel = new JLabel("Enter Start Index : "
, JLabel.CENTER);
startIndexField = new JTextField(10);
JLabel endIndexLabel = new JLabel("Enter End Index : ");
endIndexField = new JTextField(10);
panel.add(replaceLabel);
panel.add(replaceTextField);
panel.add(startIndexLabel);
panel.add(startIndexField);
panel.add(endIndexLabel);
panel.add(endIndexField);
return panel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextAreaSelection().createAndDisplayGUI();
}
});
}
}

Categories

Resources