JFileChooser crashes - Java 7 - java

I'm trying to make my program load a txt file with JFileChooser, but it doesn't seem to work. When I press the JButton, the console gives me a lot of errors. Here's the entire code so far:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.JFileChooser;
public class Sudoku extends JFrame{
JPanel mainWindow = new JPanel();
JPanel buttonWindow = new JPanel();
JPanel sudokuArea = new JPanel();
JButton load = new JButton("Load");
JButton solve = new JButton("Solve");
JTextArea sudokuGrid = new JTextArea();
Field field = new Field();
public static void main(String[] args) {
new Sudoku();
}
public Sudoku(){
super("SudokuSolver");
setSize(200,300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(mainWindow);
mainWindow.setLayout(new BorderLayout());
mainWindow.add(buttonWindow, BorderLayout.SOUTH);
mainWindow.add(sudokuArea, BorderLayout.CENTER);
buttonWindow.add(load);
buttonWindow.add(solve);
sudokuArea.setLayout(new BorderLayout());
sudokuArea.add(sudokuGrid, BorderLayout.CENTER);
sudokuGrid.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
sudokuGrid.setEditable(false);
sudokuGrid.append(field.toString());
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loader();
}
public void loader(){
JFileChooser sumtin = new JFileChooser();
if(sumtin.showOpenDialog() == JFileChooser.APPROVE_OPTION)
{
File filer = sumtin.getSelectedFile();
field.fromFile(filer.getName());
sudokuGrid.setText(field.toString());
mainWindow.revalidate();
mainWindow.repaint();
}
}
} );
setVisible(true);
}
The field method is from another class called Field, but it's not really relevant (I think).
Here's what the console says:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Sudoku$1.loader(Sudoku.java:52)
at Sudoku$1.actionPerformed(Sudoku.java:45)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
ce)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I'm not really sure what to make of it, as I don't really know what it means. Any pointers?
EDIT: New errorcode after trying David Colers code:
Sudoku.java:49: error: method showOpenDialog in class JFileChooser cannot be app
lied to given types;
if(sumtin.showOpenDialog() == JFileChooser.APPRO
VE_OPTION)
^
required: Component
found: no arguments
reason: actual and formal argument lists differ in length
1 error

you are not handling the JFileChooser correctly for one thing.
EDIT: changed this keyword to null.
JFileChooser sumtin = new JFileChooser();
if(sumtin.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File filer = sumtin.getSelectedFile();
field.fromFile(filer.getName());
sudokuGrid.setText(field.toString());
mainWindow.revalidate();
mainWindow.repaint();
}

you missed a few steps:
first create a filechooser
JFileChooser fileChooser = new JFileChooser();
show it, and get the result
int result = fileChooser.showOpenDialog(this);
And if the user has opened a file, you can get it and do what you want
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
...
}

Related

How can I parse a value from a JTextField into an Integer and perform some math operations on it?

So, I've been trying to make a Celsius converter in Java using swing and got stuck on getting the input from the JTextField and parsing it into an Integer so i can perform an equation on it. If I leave it as a String I am unable to do any math operations.
I've added a private string called cValue in which I store the value of text field in, and then I have some code in the ActionListener that parses that string into an Integer.
When I run the program it opens up the window without any problems. I can type in anything in the text field, but as soon as I press the button the program exits out and I'm shown an error which I can't understand. If I move the code out of the action listener and run the program, it gives me an error.
Now, I'm pretty new to Java and am not that familiar with it yet. I wrote this using eclipse and made the UI with WindowBuilder. I've tried many things and nothing has worked so far. I appreciate any form of feedback I can get.
This is the code:
private String cValue;
private String result = "0";
private JPanel contentPane;
private JTextField celsiusField;
private JButton convertButton;
/**
* Create the frame.
*/
public CelsiusConverter() {
setDefaultCloseOperation(CelsiusConverter.EXIT_ON_CLOSE);
setBounds(100, 100, 194, 134);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblCelsius = new JLabel("Celsius");
lblCelsius.setBounds(10, 11, 61, 14);
contentPane.add(lblCelsius);
celsiusField = new JTextField();
celsiusField.setBounds(81, 8, 86, 20);
contentPane.add(celsiusField);
celsiusField.setColumns(10);
JLabel lblFahrenheit = new JLabel("Fahrenheit:");
lblFahrenheit.setBounds(10, 73, 70, 14);
contentPane.add(lblFahrenheit);
JLabel lblResult = new JLabel();
lblResult.setText(String.valueOf(result));
lblResult.setBounds(81, 73, 87, 14);
contentPane.add(lblResult);
cValue = celsiusField.getText();
convertButton = new JButton("Convert");
convertButton.setBounds(10, 39, 157, 23);
contentPane.add(convertButton);
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int parsed = Integer.parseInt(cValue);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CelsiusConverter frame = new CelsiusConverter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And this is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at learningWindowBuilder.CelsiusConverter$1.actionPerformed(CelsiusConverter.java:53)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
cValue = celsiusField.getText();
You can't invoke that statement yet because the GUI isn't even visible and the user hasn't had a chance to enter data into the text field.
You need to get the text from the text field in your ActionListener
String cValue = celsiusField.getText();
int parsed = Integer.parseInt(cValue);

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException and how to fix it? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I want to create an application which chooses the number to be guessed by selecting an integer at random in the range 1-1000.The application then displays the following in a label: I have a number between 1-1000.Can you guess my number?Please enter your first guess. As each guess is input,the background color should change to either red or blue.Red indicates that the user is getting "warmer" ,and blue,"colder".
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class GuessNumber extends JFrame{
private JLabel topLabel;
private JLabel colorLabel;
private JLabel correctLabel;
private JTextField numberText;
private JTextField inputText;
private JButton playBtn;
private int num;
GuessNumber(){
setSize(600,300);
setTitle("Guess the number");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
topLabel=new JLabel("I have a number between 1 and 1000.Can you guess my number?",JLabel.CENTER);
add("North",topLabel);
playBtn=new JButton("Play");
inputText=new JTextField();
inputText.setEditable(false);
correctLabel=new JLabel();
colorLabel=new JLabel();
//Read a random number when play button is clicked
playBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
Random r=new Random();
num=r.nextInt(1001);
numberText.setText(Integer.toString(num));
inputText.setEditable(true);
}
});
//Show whether your guess is close to the number or not
inputText.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
if(Integer.parseInt(inputText.getText())>num/2){
colorLabel.setText("Warmer");
colorLabel.setBackground(Color.red);
colorLabel.setOpaque(true);
}else{
colorLabel.setText("Colder");
colorLabel.setBackground(Color.blue);
colorLabel.setOpaque(true);
}
if(Integer.parseInt(inputText.getText())==num){
correctLabel.setText("Correct!");
correctLabel.setVisible(true);
inputText.setEditable(false);
}
}
});
JPanel centerPanel=new JPanel();
centerPanel.setLayout(new GridLayout(3,1));
centerPanel.add(inputText);
centerPanel.add(colorLabel);
centerPanel.add(correctLabel);
add(centerPanel);
add("South",playBtn);
setVisible(true);
}
}
class Example{
public static void main(String args[]){
new GuessNumber();
}
}
The program will compile but I get an exception in run time.I can't find the error in my program.How can I fix this?
Here is the error I get:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GuessNumber$1.actionPerformed(Example.java:34)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
ce)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionP
rivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionP
rivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionP
rivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
you forgot numberText = new JTextField();. You need to initialize a reference-variable before you can use it.

Simple Java Calculator Logic

I'm new to programming and I was making a calculator with only 1 textfield.
I need a method which can recognize which string characters from these (+ , - , * , /)
to send the result to a variable and when i click the = button it shows the result.
I have tried to write something like that (1+2) and save it to variable then then when I try to press = button to settext the variable it shows a privilage error.
Here is the code
JButton btnOne = new JButton("1");
btnOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sum+=1;
txtoprtn.setText(txtoprtn.getText()+"1");
JButton btnTwo = new JButton("2");
btnTwo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sum+=2;
txtoprtn.setText(txtoprtn.getText()+"2");
}
});
JButton btnAdd = new JButton("+");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtoprtn.setText(txtoprtn.getText()+"+");
}
});
JButton btnEqual = new JButton("=");
btnEqual.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
x = Integer.parseInt(txtoprtn.getText());
txtoprtn.setText(Integer.toString(x));
}
}
);
and this is the error
**Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "1+2"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.jadv.day01.tasks.AdvCalc$11.actionPerformed(AdvCalc.java:140)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)**
any suggestions????
First problem
When you try to just write a string statement of "1+2", what do you expect will happen? It can't simply just be evaluated like that. You would have to first use Integer.parseInt() to each of your # buttons after the number insertion is done(say, when you click the +/-///*, or =. That means the number is done and you'll get say
Integer.parseInt("123") instead of Integer.parseInt("1")+Integer.parseInt("2")+Integer.parseInt("3")
What you're trying to do is parsing a + in the middle of the parse. Keep the integer parse to the numbers and the operators stored somewhere else(explained in second problem)
Second problem
When you say "+", that doesn't parse into any operation. You would have to store the values into their individual variables and when clicked a + button, you would get a correct answer. If you want to do this without any external imports, then you would have to store the operations in a list and evaluate when = is clicked.
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
operations.add("+");//operations is a list
}
});
Solving both problems at once using an import
If you want to evaluate using a package, then use this:
ScriptEngine evaluationMachine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.eval(foo); //evaluates something like "2+1" into 3.
with the following imports:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
EDIT: By the way, though the second way is much faster, you should probably try and write it without external imports since you're new to programming. There will be inevitable situations where you're going to have to think about the problem.
The cause of the exception is that you are trying to parse a String like "1+2" to an Integer in the line:
x = Integer.parseInt(txtoprtn.getText());
You should store the numbers somewhere else, i.e. in an ArrayList.

NumberFormatException while using JFrame

The code is supposed to get an order and its price and save them in their respective ArrayLists.
public class SetMenu0{
private double price;
private int size;
private String output;
private String priceOutput;
String next;
JTextField orderIn;
JTextField priceIn;
private JFrame orderInput;
JPanel txtFldPanel;
JPanel btnPanel;
ArrayList orderList = new ArrayList<String>();
ArrayList priceList = new ArrayList<Double>();
public SetMenu0()
{
orderInput = new JFrame();
orderInput.setTitle("Input Order and Price");
orderInput.setSize(200,350);
orderInput.getContentPane();
orderInput.setLayout(new BorderLayout());
orderInput.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel txtFldPanel = new JPanel();
orderIn = new JTextField(10);
priceIn = new JTextField(5);
txtFldPanel.add(orderIn);
txtFldPanel.add(priceIn);
JPanel btnPanel = new JPanel();
JButton addBtn = new JButton("ADD");
btnPanel.add(addBtn);
addBtn.addActionListener(new ButtonListener());
addBtn.setActionCommand("add");
JButton fnshBtn = new JButton("FINISH");
btnPanel.add(fnshBtn);
addBtn.addActionListener(new ButtonListener());
fnshBtn.setActionCommand("fnsh");
size = orderList.size();
Container cont = orderInput.getContentPane();
cont.add(txtFldPanel,BorderLayout.NORTH);
cont.add(btnPanel,BorderLayout.SOUTH);
orderInput.pack();
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String actionEnter = e.getActionCommand();
if(actionEnter.equals("add"))
{
orderList.add(orderIn.getText());
priceList.add(Double.parseDouble(priceIn.getText()));
orderIn.setText("");
priceIn.setText("");
}
else if(actionEnter.equals("fnsh"))
{
orderInput.dispose();
}
}
}
public JFrame getFrame()
{
return orderInput;
}
public ArrayList getOrd()
{
return orderList;
}
public ArrayList getPri()
{
return priceList;
}
public int getSize()
{
return size;
}
}
When i press the ADD button it shows a NumberFormatException. Why is this? I could add the rest of the code from the main but why is it not saving in the ArrayList?
This is the error:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.howtodoinjava.demo.poi.SetMenu0$ButtonListener.actionPerformed(SetMenu0.java:84)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
It's probably due to this line:
priceList.add(Double.parseDouble(priceIn.getText()));
You want to make sure that priceIn text field contains a number before you try to parse the text.
You have to use (on button add click)
if(!(priceIn.isEmpty || orderIn.isEmpty)){
//Do your adding
}
This code checks if there is something in the JTextFiels

NullPointerException while opening new frame

today I'm having a bit of a slight, see, I'm trying to run my code and I'm getting a NullPointerException. The clues in the exception leads me to this function right here:
private void irGuiJuego(JFrame frame){
SwingConsole.run(new GUIJuego(), 800, 600, true);
frame.dispose();
}
Where SwingConsole would have this code:
package utiles;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SwingConsole {
public static void run(final JFrame frame, final int width, final int height, final boolean exitOnClose) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
if (exitOnClose)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
//frame.setResizable(false);
frame.setVisible(true);
}
});
}
public static void run(final JFrame frame, final int width, final int height, final boolean exitOnClose, final String title) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
if (exitOnClose)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(title);
frame.setSize(width, height);
frame.setVisible(true);
}
});
}
}
It is kind of odd, considering that I'm using the same method to open up another frame, in this function to be specific:
private void volverMenuInicio(JFrame frame){
SwingConsole.run(new MenuInicio(), 300, 150, true);
frame.dispose();
}
I'll leave you guys a pastebin of the GUIJuego Frame, since it's sort of excessive to post it here: http://pastebin.com/LSXbc7KE , have the pastebin of the other frame too, in case you need it: http://pastebin.com/hbdd7j84
Edit: Here's the stacktrace, sorry for the lack of it before!
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source) at
java.awt.Container.add(Unknown Source) at
gui.GUIJuego.(GUIJuego.java:113) at
gui.MenuNuevoJuego.irGuiJuego(MenuNuevoJuego.java:95) at
gui.MenuNuevoJuego.access$2(MenuNuevoJuego.java:94) at
gui.MenuNuevoJuego$2.actionPerformed(MenuNuevoJuego.java:74) at
javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at
javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at
javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at
javax.swing.DefaultButtonModel.setPressed(Unknown Source) at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown
Source) at java.awt.Component.processMouseEvent(Unknown Source) at
javax.swing.JComponent.processMouseEvent(Unknown Source) at
java.awt.Component.processEvent(Unknown Source) at
java.awt.Container.processEvent(Unknown Source) at
java.awt.Component.dispatchEventImpl(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at
java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at
java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at
java.awt.Container.dispatchEventImpl(Unknown Source) at
java.awt.Window.dispatchEventImpl(Unknown Source) at
java.awt.Component.dispatchEvent(Unknown Source) at
java.awt.EventQueue.dispatchEventImpl(Unknown Source) at
java.awt.EventQueue.access$200(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue$4.run(Unknown Source) at
java.awt.EventQueue$4.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at
java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.run(Unknown Source)
Thanks for reading, by the way!
The NPE is being thrown from line 113 in GUIJuego.java, as the stack trace indicates:
panelDatosCiudad.add(arcaLabel);
It's happening because arcaLabel, defined in line 35, is never set to a value, and so you're adding a null JLabel to the container.

Categories

Resources