Trying to find error in Java Swing program - java

So this is my program... It's a way to enter and list marathon runners. Now I'm getting an error when using the "Ny" button (http://gyazo.com/e29517af6befd6242d86e6fe1dc5aae1). Here's the error code: http://gyazo.com/9f80885d41db38cfa5502fe911f6a893.
I think the problems is between the "Form" panel and the listener. There may be unreachable code somewhere? I had this working the other day but I lost the code. Now it doesn't work.
The idea is that the "ny" button shows the user a panel "Form", but instead I get the rror.
I'm a huge noob, so I expect it's some obvious syntax error I just can't seem to spot.
Any feedback is appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Maraton extends JFrame{
JTextArea display;
JButton visa;
ArrayList <Tävlande> list = new ArrayList <Tävlande>();
Maraton(){
super("Kista Maraton");
display = new JTextArea();
display.setEditable(false);
add(display, BorderLayout.CENTER);
add(new JScrollPane(display),BorderLayout.CENTER);
setLocationRelativeTo(null);
setSize(300, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel nedre = new JPanel ();
JPanel höger = new JPanel();
add(nedre, BorderLayout.SOUTH);
add(höger, BorderLayout.EAST);
höger.setLayout(new BoxLayout(höger, BoxLayout.Y_AXIS));
nedre.setBackground( new Color(246,246,246) );
nedre.setBorder(BorderFactory.createLineBorder(new Color(200,200,200)));
JButton ny = new JButton("Ny");
ny.addActionListener(new NyLis());
JButton visa = new JButton("Visa");
visa.addActionListener(new VisaLis());
visa.setEnabled(false);
JButton nyTid = new JButton("Ny Tid");
nedre.add(ny);
nedre.add(visa);
nedre.add(nyTid);
JRadioButton StartNrRb = new JRadioButton("Startnr");
JRadioButton NamnRb = new JRadioButton("Namn");
JRadioButton ÅlderRb = new JRadioButton("Ålder");
JRadioButton TidRb = new JRadioButton("Tid");
höger.add(StartNrRb);
höger.add(NamnRb);
höger.add(ÅlderRb);
höger.add(TidRb);
ButtonGroup bg1 = new ButtonGroup();
bg1.add(NamnRb);
bg1.add(StartNrRb);
bg1.add(ÅlderRb);
bg1.add(TidRb);
}
class Form2 extends JPanel{
JTextField startNrFält;
JTextField tidFält;
Form2(){
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
JPanel rad0 = new JPanel();
rad0.add(new JLabel("Start Nummer: "));
rad0.add(new JLabel("Tid: "));
rad0.setLayout(new BoxLayout(rad0, BoxLayout.Y_AXIS));
rad0.add(startNrFält);
rad0.add(tidFält);
add(rad0);
}
}
class Form extends JPanel{
JTextField namnFält;
JTextField landFält;
JTextField ålderFält;
Form(){
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel rad1 = new JPanel();
rad1.add(new JLabel("Namn: "));
namnFält = new JTextField(15);
rad1.add(namnFält);
add(rad1);
JPanel rad2 = new JPanel();
rad2.add(new JLabel("Land: "));
landFält = new JTextField(15);
rad2.add(landFält);
add(rad2);
JPanel rad3 = new JPanel();
rad3.add(ålderFält);
rad3.add(new JLabel("Ålder: "));
ålderFält = new JTextField(5);
rad3.add(ålderFält);
add(rad3);
}
}
class NyLis implements ActionListener{
public void actionPerformed(ActionEvent ave){
Form f = new Form();
int svar = JOptionPane.showConfirmDialog(null, f);
String namn = f.namnFält.getText();
String land = f.landFält.getText();
int ålder = Integer.parseInt(f.ålderFält.getText());
Tävlande tv = new Tävlande (namn,land,ålder);
list.add(tv);
visa.setEnabled(true);
}
}
class VisaLis implements ActionListener{
public void actionPerformed(ActionEvent ave) {
display.setText("");
for (Tävlande t : list){
display.append(t.toString()+"\n");
}
}
}
class NyTidLis implements ActionListener{
public void actionPerformed(ActionEvent ave) {
Form f2 = new Form();
JOptionPane.showMessageDialog(null, f2);
}
}
public static void main (String []args){
new Maraton();
}
}

The problem is you're trying to add a null object to your JPanel when you click the ny button. The offending code is found in the constructor for your Form object:
rad3.add(ålderFält);
ålderFält = new JTextField(5); //NO! Create the JTextFieldObject first
rad3.add(ålderFält);
Alter the code to the following:
ålderFält = new JTextField(5);
rad3.add(ålderFält);
rad3.add(ålderFält);
And you should have no problems (or at least the code runs for me).
You also have a problem with your visa button. You're declaring an entirely new JButton in your constructor, which will lead to more NullPointerExceptions when you try to enable it.
In the future, read your stack trace a little more closely. Sometimes you have to dig through a few lines of it to find out where, exactly, in your code you're going wrong. This is especially true when you're doing graphical stuff.

You are redefining the JButton visa in the constructor of your class on this line:
JButton visa = new JButton("Visa");
This is distinct from the visa variable defined class level (here this.visa, and visa represent two seperate JButtons), which you attempt to access (uninitialized) in your NyLis actionListener.
Change the aforementioned line to:
visa = new JButton("Visa");

Related

Place label for text box above the box and not to the side

As stated in the title i need to move the label for the text box to be above the box and not to the side. attached i have a picutres of what i mean. what i have vs what i want i have tried searching for it but i cannot seem to find the answer im looking for/not exactly sure what to look up. I have tried using JFrame but it made a separate window unless i need to make the entire GUI a JFrame for me to get the result i want?
Also the actionPerformed method has things but it is irrelevant to the question but displays correctly still.
import java.awt.event.\*;
import javax.swing.\*;
import java.text.DecimalFormat;
public class Project4 extends JFrame implements ActionListener {
private JTextArea taArea = new JTextArea("", 30, 20);
ButtonGroup group = new ButtonGroup();
JTextField name = new JTextField(20);
boolean ch = false;
boolean pep = false;
boolean sup = false;
boolean veg = false;
DecimalFormat df = new DecimalFormat("##.00");
double cost = 0.0;
public Project4() {
initUI();
}
public final void initUI() {
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
getContentPane().add(panel1, "North");
getContentPane().add(panel2, "West");
getContentPane().add(panel3, "Center");
getContentPane().add(panel4, "East");
panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
getContentPane().add(panel5, "South");
JButton button = new JButton("Place Order");
button.addActionListener(this);
panel5.add(button);
JButton button2 = new JButton("Clear");
button2.addActionListener(this);
panel5.add(button2);
panel3.add(taArea);
JCheckBox checkBox1 = new JCheckBox("Cheese Pizza") ;
checkBox1.addActionListener(this);
panel4.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Pepperoni Pizza");
checkBox2.addActionListener(this);
panel4.add(checkBox2);
JCheckBox checkBox3 = new JCheckBox("Supreme Pizza");
checkBox3.addActionListener(this);
panel4.add(checkBox3);
JCheckBox checkBox4 = new JCheckBox("Vegetarian Pizza");
checkBox4.addActionListener(this);
panel4.add(checkBox4);
JRadioButton radioButton1 = new JRadioButton("Pick Up");
group.add(radioButton1);
radioButton1.addActionListener(this);
panel1.add(radioButton1);
JRadioButton radioButton2 = new JRadioButton("Delivery");
group.add(radioButton2);
radioButton2.addActionListener(this);
panel1.add(radioButton2);
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
panel5.add(name_label);
panel5.add(name);
setSize(600, 300);
setTitle("Pizza to Order");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent action) {
}
public static void main(String[] args) {
Project4 ex = new Project4();
ex.setVisible(true);
}
}
You can use a nested JPanel with another layout in order to achieve that. I would go with BorderLayout here. You can also other layouts that allow vertical orientation. Visiting the visual guide to Layout Managers will help you spot them.
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
JPanel verticalNestedPanel = new JPanel(new BorderLayout());
verticalNestedPanel.add(name_label, BorderLayout.PAGE_START);
verticalNestedPanel.add(name, BorderLayout.PAGE_END);
panel5.add(verticalNestedPanel);

Java Button Placement using BorderLayout

This code displays nothing, I have exhausted many avenues but it does not display anything on the GUI (I have a main class that calls this as well already). Please help. I am trying to put the two JButtons horizontally at the bottom of the page and the JTextField and JLabel at the center of the screen.
package test;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("");
textfield = new JTextField("enter text here");
JPanel bottom = new JPanel(new BorderLayout());
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel (new BorderLayout());
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom, BorderLayout.PAGE_END);
centre.add(subCentre, BorderLayout.CENTER);
}
}
Your code is a bit over-complicated. You only need two panels, centre, and buttons. There are two reasons your UI is not showing up:
You never added the panels to the frame
You never set visible to true(Achieve this by using setVisible(true)), unless you did this in the class you ran it in.
One simple way to achieve your desired UI is like so(I added a main method to show the window):
import javax.swing.*;
import java.awt.*;
public class test extends JFrame {
public Test() {
super("test");
JPanel buttons = new JPanel();
JPanel centre = new JPanel();
add(buttons, BorderLayout.SOUTH); //these lines add the
add(centre, BorderLayout.CENTER); //panels to the frame
JButton clear = new JButton("Clear"); // No need
JButton copy = new JButton("Copy"); // to declare
JLabel label = new JLabel("Label"); // these
JTextField textfield = new JTextField("enter text here"); // privately
buttons.add(copy);
buttons.add(clear);
centre.add(label);
centre.add(textfield);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
} //end constructor
//added main method to run the UI
public static void main(String[] args) {
new Experiments();
} //end main
} //end class
And it shows the window:
I got closer but its not pretty code, the JFrame is 500x500 so this works based on that... any better suggestions than what I have?
package lab6;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("label");
textfield = new JTextField("enter text here");
JPanel masterPanel = new JPanel(new BorderLayout());
JPanel top = new JPanel();
top.setPreferredSize(new Dimension(100, 200));
JPanel bottom = new JPanel();
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel ();
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom);
centre.add(subCentre);
masterPanel.add(bottom, BorderLayout.PAGE_END);
masterPanel.add(top, BorderLayout.PAGE_START);
masterPanel.add(centre, BorderLayout.CENTER);
add(masterPanel);
}
}

Swing Number Format Exception

For some reason the AddListener class below doesn't work, and I keep getting a number format exception. Could anyone please tell me the reason for this. It seems to me as if it should work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BabyCalculator extends JFrame {
JFrame theFrame = this;
JTextField addField; // Declaring this here so that you can access the variable from other places. MAKE SURE TO NOT DECLARE THIS AGAIN IN THE CONSTRUCTOR
JTextField totalField;
public BabyCalculator() {
//You set this up so that you can refer to the frame using the inner class below.
setDefaultCloseOperation(EXIT_ON_CLOSE);
setName("Baby Calculator");
setLayout(new GridLayout(3, 0));
//add
JLabel addLabel = new JLabel("Amount to add:");
addField = new JTextField(10);
JButton addButton = new JButton("add");
addButton.addActionListener(new AddListener());
//multiply
JLabel multiplyLabel = new JLabel("Amount to multiply:");
JTextField multiplyField = new JTextField(10);
JButton multiplyButton = new JButton("multiply");
//total
JLabel totalLabel = new JLabel("Total");
totalField = new JTextField(10);
totalField.setEditable(false);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new StopListener());
//Create Panels
JPanel topRow = new JPanel(new BorderLayout());
JPanel middleRow = new JPanel(new BorderLayout());
JPanel bottomRow = new JPanel(new FlowLayout());
//Add the top Row
topRow.add(addLabel, BorderLayout.WEST);
topRow.add(addField, BorderLayout.CENTER);
topRow.add(addButton, BorderLayout.EAST);
add(topRow);
middleRow.add(multiplyLabel, BorderLayout.WEST);
middleRow.add(multiplyField, BorderLayout.CENTER);
middleRow.add(multiplyButton, BorderLayout.EAST);
add(middleRow);
bottomRow.add(totalLabel);
bottomRow.add(totalField);
bottomRow.add(stopButton);
add(bottomRow);
pack();
setVisible(true);
}
public class AddListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String addFieldText = addField.getText();
String totalFieldText = totalField.getText();
double addAmount = Double.parseDouble(addFieldText);
double total = Double.parseDouble(totalFieldText);
total += addAmount;
totalField.setText(total + "");
}
}
//end class AddListener
public class StopListener implements ActionListener {//this is an inner class
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(theFrame, "You Clicked the stop button");
}//end class StopListener
}
public static void main(String[] args) {
JFrame newFrame = new BabyCalculator();
}
}
Note: The problem in the code is definitely related to the AddListener. Whenever I click the add button in the GUI I get an exception.
The problem is with the totalFieldText, it's default value is blank, meaning that when you try and convert to a double value, it causes a NumberFormatException
Try giving it a default value of 0, for example
totalField = new JTextField("0", 10);
You might also like to take a look at How to Use Spinners and How to Use Formatted Text Fields which will make your life easier

My GUI window doesn't show anything

I'm trying to use a grid layout to make a GUI window. I add all my components and it compiles but when it runs it doesn't show anything. I'm trying to make a simple layout grouped and stacked like this.
{introduction message}
{time label
time input text}
{gravity label
gravity input text}
{answer label
answer text box}
{calculate button clear button}
Here is my code
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
setTitle("Falling Distance Calculator");
setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 5));
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setVisible(true);
}
public static void main(String[] args)
{
new TurnerRandyFallingGUI();
}
}
You've added nothing to the JFrame that your class above extends. You need to add your components to containers whose hierarchy eventually leads to the top level window, to the this if you will. In other words, you have no add(someComponent) or the functionally similar this.add(someComponent)method call in your code above.
Consider adding all of your JPanels to a single JPanel
Consider adding that JPanel to the JFrame instance that is your class by calling add(thatJPanel).
Even better would be to not extend JFrame and just to create one when needed, but that will likely be the subject of another discussion at another time.
Before setVisible (true) statement add following statements:
add (introP);
add (timeP);
add (gravityP);
add (answerP);
add (buttonsP);
There is nothing in your JFrame. That is the reason
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setLayout(new GridLayout(5, 1));
this.add(introP);
this.add(timeP);
this.add(gravityP);
this.add(answerP);
this.add(buttonsP);
setTitle("Falling Distance Calculator");
this.pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.validate();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TurnerRandyFallingGUI();
}
});
}
}
Consider the following
In GridLayout, the first parameter is Rows, Second is columns
Never set the size of JFrame manually. Use pack() method to decide
the size
Use SwingUtilities.InvokeLater() to run the GUI in another thread.

how can I make this class an applet

I have the following class which is a simple gui, and I would like to make it an applet so it can be displayed in the browser. I know how to embed the code into an html page(got that done)... but how can make my class an applet? Also, I assuming I don't need a web server just to display the applet in my browser...
package tester1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PanelTest implements ActionListener {
JFrame frame;
JLabel inputLabel;
JLabel outputLabel;
JLabel outputHidden;
JTextField inputText;
JButton button;
JButton clear;
JButton about;
public PanelTest() {
frame = new JFrame("User Name");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 2, 10, 10));
//creating first row
JPanel row1 = new JPanel();
inputLabel = new JLabel("Your Name");
inputText = new JTextField(15);
// FlowLayout flow1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
// row1.setLayout(flow1);
row1.add(inputLabel);
row1.add(inputText);
frame.add(row1);
//creating second row
JPanel row2 = new JPanel();
button = new JButton("Display");
clear = new JButton("Clear");
about = new JButton("About");
button.addActionListener(this);
clear.addActionListener(this);
about.addActionListener(new displayAbout());
row2.add(button);
row2.add(clear);
row2.add(about);
frame.add(row2);
//creating third row
JPanel row3 = new JPanel();
outputLabel = new JLabel("Output:", JLabel.LEFT);
outputHidden = new JLabel("", JLabel.RIGHT);
// FlowLayout flow2 = new FlowLayout(FlowLayout.CENTER, 10, 10);
// row3.setLayout(flow2);
row3.add(outputLabel);
row3.add(outputHidden);
frame.add(row3);
frame.pack();
frame.setVisible(true);
}
//same method listen for two different events
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Display")) {
outputHidden.setText(inputText.getText());
}
if(command.equals("Clear")) {
outputHidden.setText("");
inputText.setText("");
}
}
//another way to listen for events
class displayAbout implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Username 1.1 \n by Jorge L. Vazquez");
}
}
public static void main(String[] args) {
PanelTest frameTest = new PanelTest();
}
}
Use a JApplet rather than a JFrame. Make sure you read the relevant Java Tutorial, which covers the applet lifecycle methods like init, start, stop, and destroy.
As a side note, you should not be building your UI outside of the event dispatch thread.
Use a JApplet instead of a JFrame like veer said, but you must also remove frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, frame.pack();, and frame.setVisible(true);
Also, replace main(String[] args) with init().

Categories