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
Related
When i run this program sometimes shows me all buttons, but sometimes only 2 or 3 or 4 or 5 or even just 1.. why is that??
I really do not get it. There should always be 6 buttons, but it doesnt show them. Is there any logical reason?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class testnet
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Knjigarna");
frame.setVisible(true);
frame.setSize(800,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1 = new JButton("Prikazi vse");
panel.add(button1);
button1.addActionListener (new Action1());
JButton button2 = new JButton("Prikazi knjigo");
panel.add(button2);
button2.addActionListener (new Action2());
JButton button3 = new JButton("Dodaj knjigo");
panel.add(button3);
button3.addActionListener (new Action3());
JButton button4 = new JButton("Brisi knjigo");
panel.add(button4);
button4.addActionListener (new Action4());
JButton button5 = new JButton("Uredi knjigo");
panel.add(button5);
button5.addActionListener (new Action5());
JButton button6 = new JButton("Izhod");
panel.add(button6);
button6.addActionListener (new Action6());
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame2 = new JFrame("Pikaz vseh knjig");
frame2.setVisible(true);
frame2.setSize(500,800);
JLabel label = new JLabel("Seznam vseh knjig:");
JPanel panel = new JPanel();
JTextField text1=new JTextField("Naslov: ");
JTextField text2=new JTextField("Avtor: ");
frame2.add(panel);
panel.add(label);
panel.add(text1);
panel.add(text2);
}
}
static class Action2 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame3 = new JFrame("Prikaz knjige");
frame3.setVisible(true);
frame3.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige:");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
static class Action3 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame4 = new JFrame("Dodajanje knjige");
frame4.setVisible(true);
frame4.setSize(600,300);
JLabel label = new JLabel("Vpisi podtke o knjigi");
JPanel panel = new JPanel();
frame4.add(panel);
panel.add(label);
}
}
static class Action4 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame5 = new JFrame("Brisanje knjige");
frame5.setVisible(true);
frame5.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige, ki jo zelis brisati");
JPanel panel = new JPanel();
frame5.add(panel);
panel.add(label);
}
}
static class Action5 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame6 = new JFrame("Urejanje knjige");
frame6.setVisible(true);
frame6.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige, ki jo zelis urejati");
JPanel panel = new JPanel();
frame6.add(panel);
panel.add(label);
}
}
static class Action6 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
}
try something with layout. JFrame and or remove managed by inside with a content pane. content pane default layout is BorderLayout. so you need to try border layout stuff.
or you can try this code in you main method
frame.setLayout(new FlowLayout());
this will add component by one by one.
for more about layout you can get in here
This is just a fix and not really an explanation of why the problem is occurring.
Call frame.revalidate() after adding all the buttons.
From the Java Docs,
public Component add(Component comp)
This method
changes layout-related information, and therefore, invalidates the
component hierarchy. If the container has already been displayed, the
hierarchy must be validated thereafter in order to display the added
component.
I'm trying to make a sort of simple soccer simulator. This is the code I created after watching tutorials and i know its pretty bad. All i want to do is add a value to the team, like 1 for the best team and 10 for the worst, and when i click simulate a pop up would show up telling me which team would win given the teams value. But i cant figure out how to do it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class sim extends JPanel {
public sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon(getClass().getResource("a.PNG"));
Icon c = new ImageIcon(getClass().getResource("c.JPG"));
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
HandlerClass handler = new HandlerClass();
chelsea.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//JOptionPane.showMessageDialog(null, String.format("%s", e.getActionCommand()));
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new sim());
frame.setVisible(true);
}
}
Firstly capitalize the name of your class always in Java, then check this code :
public class Sim extends JPanel {
public Sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon("/home/mehdi/Pictures/ICONS/Test/1.png");
Icon c = new ImageIcon("/home/mehdi/Pictures/ICONS/Test/2.png");
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
final JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
button.addActionListener(new HandlerClass(label));
}
private class HandlerClass implements ActionListener{
final JLabel label;
public HandlerClass(JLabel label){
this.label = label;
}
public void actionPerformed(ActionEvent e)
{
label.setText("SSSSSSSSSSSSSsssss");
JOptionPane.showMessageDialog(null, "Something");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new Sim());
frame.setVisible(true);
}
}
I am having a problem implementing the last part of this program, which is to make it where pressing the Enter key moves the active field from one text field to the next one in order (1,2,3,4).
This needs to be done without removing the focus cycling that is used by the tab key.
I have no idea how to even begin doing that, the only thing I've found in the API is replacing the traversal policy with your own, but I don't want to replace it I want to create a new one that runs in parallel with the default one.
public class unit27 {
JButton button1 = new JButton("add to next cup");
JButton button2 = new JButton("add to next cup");
JButton button3 = new JButton("add to next cup");
JButton button4 = new JButton("add to next cup");
JTextField text1 = new JTextField("4");
JTextField text2 = new JTextField("4");
JTextField text3 = new JTextField("4");
JTextField text4 = new JTextField("4");
JLabel label1 = new JLabel("Cup 1");
JLabel label2 = new JLabel("Cup 2");
JLabel label3 = new JLabel("Cup 3");
JLabel label4 = new JLabel("Cup 4");
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
public unit27() {
mainPanel.setLayout(new GridLayout(2, 4));
panel1.setLayout(new GridLayout(1, 3));
panel2.setLayout(new GridLayout(1, 3));
panel3.setLayout(new GridLayout(1, 3));
panel4.setLayout(new GridLayout(1, 3));
frame.add(mainPanel);
frame.setSize(800, 800);
frame.setVisible(true);
mainPanel.add(panel1);
mainPanel.add(panel2);
mainPanel.add(panel3);
mainPanel.add(panel4);
panel1.add(label1);
panel1.add(button1);
panel1.add(text1);
panel2.add(label2);
panel2.add(button2);
panel2.add(text2);
panel3.add(label3);
panel3.add(button3);
panel3.add(text3);
panel4.add(label4);
panel4.add(button4);
panel4.add(text4);
button1.add(text1);
button1.addActionListener(new MyListener1());
button2.addActionListener(new MyListener2());
button3.addActionListener(new MyListener3());
button4.addActionListener(new MyListener4());
// end class
}
class MyListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text1.getText());
int b = Integer.parseInt(text2.getText());
int c = a + b;
text2.setText(Integer.toString(c));
}
}
class MyListener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text2.getText());
int b = Integer.parseInt(text3.getText());
int c = a + b;
text3.setText(Integer.toString(c));
}
}
class MyListener3 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text3.getText());
int b = Integer.parseInt(text4.getText());
int c = a + b;
text4.setText(Integer.toString(c));
}
}
class MyListener4 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text4.getText());
int b = Integer.parseInt(text1.getText());
int c = a + b;
text1.setText(Integer.toString(c));
}
}
public static void main(String[] args) {
new unit27();
}
}
Swing does not allow 2 focus cycles to be run at the same time. If you really need to have a second focus cycle (and not just add enter to the focus traversal keys), then what you could do is:
Create a Map which determines your cycle.
On each component with the extra cycle add a key binding for Enter that gets the next visible field in your cycle and calls requestFocus on it.
You would have to maintain the map and create custom checks to see if the next component is visible or should be skipped.
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");
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().