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
Related
I'm basically building a simple GUI for a simple baking program.
The problem is that after creating a model for JTable, adding a row of data
model.addRow(new String[] {"data", "data","data", "data"});
does not work inside of an actionlistener:
public void actionPerformed(ActionEvent event) {
String buttonText = event.getActionCommand();
if (buttonText.equals("Create Savings Account")) {
createSavingsAccount();
public void createCreditAccount() {
logic.createCreditAccount(pNrField.getText());
model.addRow(new String[] {"data", "data","data", "data"});
}
If I try to create an account I get this message:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at svimag6.GUImain.createSavingsAccount(GUImain.java:145)
at svimag6.GUImain.actionPerformed(GUImain.java:124)
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)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at svimag6.GUImain.createSavingsAccount(GUImain.java:145)
at svimag6.GUImain.actionPerformed(GUImain.java:124)
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)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at svimag6.GUImain.createCreditAccount(GUImain.java:140)
at svimag6.GUImain.actionPerformed(GUImain.java:128)
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)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at svimag6.GUImain.createCreditAccount(GUImain.java:140)
at svimag6.GUImain.actionPerformed(GUImain.java:128)
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)
However, if I hardcode the adding of new rows into the table, (in the constructor) it works. But I can't add data dynamically.
Here's the code:
package gui;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.*;
import java.awt.*;
//YOU NEED TO ADD A FIELD in the GUI FOR NAME, LASTNAME AND PNR
public class GUImain extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private BankLogic logic;
private JList<Object> customerList;
private JTable accountTable;
private JTable transactionTable;
private JTextField nameField;
private JTextField lastnameField;
private JTextField pNrField;
private DefaultTableModel model;
private DefaultTableModel model1;
private JButton addButton = new JButton("Add Customer");
private JButton showButton = new JButton("Show");
private JButton clearButton = new JButton("Rensa");
private JButton createSavingsAccountButton = new JButton("Create Savings Account");
private JButton createCreditAccountButton = new JButton("Create Credit Account");
private JButton deleteAccountButton = new JButton("Delete Account");
private JButton withdrawButton = new JButton("Withdraw");
private JButton depositButton = new JButton("Deposit");
String[] accountColumns = { "ID", "Account Type", "Balance", "Interest" };
String[] transactionColumns = { "Date", "Time", "Amount", "Balance" };
String testdata[][] = { { "101", "Amit", "670000" }, { "102", "Jai", "780000" }, { "101", "Sachin", "700000" } };
public GUImain() {
initiateInstanceVariables();
buildFrame();
}
private void initiateInstanceVariables() {
logic = new BankLogic();
customerList = new JList<Object>();
accountTable = new JTable();
DefaultTableModel model = new DefaultTableModel(0, 0);
model.setColumnIdentifiers(accountColumns);
accountTable.setModel(model);
transactionTable = new JTable();
DefaultTableModel model1 = new DefaultTableModel(0, 0);
model1.setColumnIdentifiers(transactionColumns);
transactionTable.setModel(model1);
model.addRow(new String[] {"data", "data","data", "data"});
nameField = new JTextField();
lastnameField = new JTextField();
pNrField = new JTextField();
nameField.setBorder(BorderFactory.createTitledBorder("Name"));
lastnameField.setBorder(BorderFactory.createTitledBorder("Lastname"));
pNrField.setBorder(BorderFactory.createTitledBorder("pNr"));
}
private void buildFrame() {
setTitle("Bank");
setSize(300, 250);
setLayout(new GridLayout(1, 2));
JPanel bankpanel = new JPanel(new GridLayout(5, 1));
bankpanel.add(nameField);
bankpanel.add(lastnameField);
bankpanel.add(pNrField);
bankpanel.add(addButton);
bankpanel.add(showButton);
bankpanel.add(clearButton);
bankpanel.add(createSavingsAccountButton);
bankpanel.add(createCreditAccountButton);
createSavingsAccountButton.setVisible(false);
createCreditAccountButton.setVisible(false);
addButton.addActionListener(this);
showButton.addActionListener(this);
clearButton.addActionListener(this);
createSavingsAccountButton.addActionListener(this);
createCreditAccountButton.addActionListener(this);
deleteAccountButton.addActionListener(this);
// // ACCOUNT TABLE
accountTable.setCellSelectionEnabled(true);
ListSelectionModel select = accountTable.getSelectionModel();
select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// // ACCOUNT TABLE
add(bankpanel);
add(customerList);
add(new JScrollPane(accountTable), BorderLayout.CENTER);
add(new JScrollPane(transactionTable), BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
// UI LOGIC. This activated the functions below.
public void actionPerformed(ActionEvent event) {
String buttonText = event.getActionCommand();
if (buttonText.equals("Add Customer")) {
addCustomer();
showAccountButtons();
}
if (buttonText.equals("Show")) {
showSelected();
}
if (buttonText.equals("Clear")) {
clear();
}
if (buttonText.equals("Create Savings Account")) {
createSavingsAccount();
}
if (buttonText.equals("Create Credit Account")) {
createCreditAccount();
}
}
private void addCustomer() {
logic.createCustomer(nameField.getText(), lastnameField.getText(), pNrField.getText());
customerList.setListData(logic.getAllCustomers().toArray());
clear();
}
public void createCreditAccount() {
logic.createCreditAccount(pNrField.getText());
model.addRow(new String[] {"data", "data","data", "data"});
}
public void createSavingsAccount() {
logic.createSavingsAccount(pNrField.getText());
model.addRow(new String[] {"data", "data","data", "data"});
}
private void showSelected() {
int position = customerList.getSelectedIndex();
if (position > -1) {
nameField.setText(logic.getNameForPersonAt(position));
lastnameField.setText(logic.getLastNameForPersonAt(position));
pNrField.setText(logic.getpNrAt(position));
} else {
JOptionPane.showMessageDialog(null, "You need a person in the list!");
}
}
private void showAccountButtons() {
createSavingsAccountButton.setVisible(true);
createCreditAccountButton.setVisible(true);
}
private void clear() {
nameField.setText("");
lastnameField.setText("");
pNrField.setText("");
}
}
You have "shadowed variables".
You try to define instance variables but they are null:
private DefaultTableModel model;
private DefaultTableModel model1;
And then you create a local variable which is not null
DefaultTableModel model = new DefaultTableModel(0, 0);
...
DefaultTableModel model1 = new DefaultTableModel(0, 0);
The ActionListener can only access the instance variable but it is null so you get a NPE.
Get rid of the local variables:
model = new DefaultTableModel(0, 0);
...
model1 = new DefaultTableModel(0, 0);
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.
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();
...
}
I try to make Test code about JTable input and refresh.
Insert and delete is working well,
but if I delete or insert data after sort the table, it make's exception:
"AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException : 9>=0" ..
Here's my test code.
How do I fix it?
and.. any other advice?
public class Test extends JFrame{
private DefaultTableModel modelTest = new DefaultTableModel();
private JTable tableTest = new JTable(modelTest);
private JScrollPane paneTest = new JScrollPane(tableTest);
private JButton button1 = new JButton("pattern1");
private JButton button2 = new JButton("pattern2");
private JButton button3 = new JButton("delete");
private void compInit(){
paneTest.setBounds(0, 0,778, 300);
button1.setBounds(250, 320,80,20);
button2.setBounds(450,320,80,20);
button3.setBounds(300,400,80,20);
DefaultTableModel tmp = modelTest;
tmp.addColumn(" ");
tmp.addColumn("col1");
tmp.addColumn("col2");
tmp.addColumn("col3");
tmp.addColumn("col4");
tmp.addColumn("col5");
tmp.addColumn("col6");
tmp.addColumn("col7");
try {
tableTest.setDefaultRenderer(Class.forName("java.lang.String"), new DefaultTableCellRenderer());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
tableTest.setAutoCreateRowSorter(true);
tableTest.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tableTest.getColumnModel().getColumn(0).setPreferredWidth(20);
tableTest.getColumnModel().getColumn(1).setPreferredWidth(45);
tableTest.getColumnModel().getColumn(2).setPreferredWidth(110);
tableTest.getColumnModel().getColumn(3).setPreferredWidth(60);
tableTest.getColumnModel().getColumn(4).setPreferredWidth(100);
tableTest.getColumnModel().getColumn(5).setPreferredWidth(227);
tableTest.getColumnModel().getColumn(6).setPreferredWidth(100);
tableTest.getColumnModel().getColumn(7).setPreferredWidth(100);
tableTest.getTableHeader().setForeground(new Color(105,105,105));
this.add(button1);
this.add(button2);
this.add(button3);
this.add(paneTest);
}
private void pattern1(){
for(int i = 0;i<10;i++){
Vector rowData = new Vector<>();
rowData.add(false);
rowData.add(i+1);
rowData.add("a : " + i);
rowData.add("b : " + i);
rowData.add("c : " + i);
rowData.add("d : " + i);
rowData.add("e : " + i);
rowData.add("f : " + i);
modelTest.addRow(rowData);
}
}
private void pattern2(){
for(int i = 0;i<10;i++){
Vector rowData = new Vector<>();
rowData.add(false);
rowData.add(i+1);
rowData.add("z : " + i);
rowData.add("y : " + i);
rowData.add("x : " + i);
rowData.add("w : " + i);
rowData.add("v : " + i);
rowData.add("u : " + i);
modelTest.addRow(rowData);
}
}
private void delete(){
DefaultTableModel tmp = modelTest;
tmp.getDataVector().removeAllElements();
tableTest.repaint();
}
private void eventInit(){
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
pattern1();
}
});
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
pattern2();
}
});
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
delete();
}
});
}
public Test(){
this.setLayout(null);
this.compInit();
this.eventInit();
this.setSize(778, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] ar){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Test();
}
});
}
}
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 >= 1
at java.util.Vector.elementAt(Unknown Source)
at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
at javax.swing.table.TableRowSorter$TableRowSorterModelWrapper.getValueAt(Unknown Source)
at javax.swing.table.TableRowSorter$TableRowSorterModelWrapper.getStringValueAt(Unknown Source)
at javax.swing.DefaultRowSorter.compare(Unknown Source)
at javax.swing.DefaultRowSorter.access$100(Unknown Source)
at javax.swing.DefaultRowSorter$Row.compareTo(Unknown Source)
at javax.swing.DefaultRowSorter$Row.compareTo(Unknown Source)
at java.util.Arrays.binarySearch0(Unknown Source)
at java.util.Arrays.binarySearch(Unknown Source)
at javax.swing.DefaultRowSorter.insertInOrder(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted0(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted(Unknown Source)
at javax.swing.JTable.notifySorter(Unknown Source)
at javax.swing.JTable.sortedTableChanged(Unknown Source)
at javax.swing.JTable.tableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableRowsInserted(Unknown Source)
at javax.swing.table.DefaultTableModel.insertRow(Unknown Source)
at javax.swing.table.DefaultTableModel.addRow(Unknown Source)
at timer.Test.pattern1(Test.java:77)
at timer.Test.access$0(Test.java:66)
at timer.Test$1.actionPerformed(Test.java:106)
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)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.DefaultRowSorter.getViewToModelAsInts(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted0(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted(Unknown Source)
at javax.swing.JTable.notifySorter(Unknown Source)
at javax.swing.JTable.sortedTableChanged(Unknown Source)
at javax.swing.JTable.tableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableRowsInserted(Unknown Source)
at javax.swing.table.DefaultTableModel.insertRow(Unknown Source)
at javax.swing.table.DefaultTableModel.addRow(Unknown Source)
at timer.Test.pattern2(Test.java:92)
at timer.Test.access$1(Test.java:81)
at timer.Test$2.actionPerformed(Test.java:111)
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)
Whenever you change your model vector directly, make sure to notify the container about this. You fail to do that in the following method:
private void delete(){
DefaultTableModel tmp = modelTest;
tmp.getDataVector().removeAllElements();
tableTest.repaint();
}
After the removeAllElements() you should call tmp.fireTableDataChanged(). Something like:
private void delete(){
DefaultTableModel tmp = modelTest;
tmp.getDataVector().removeAllElements();
tmp.fireTableDataChanged();
tableTest.repaint();
}
Reason: Changes directly to the Model's underlying data vector are not automatically propagated to the View. You are changing a Vector this way, not a Model. Changes to the Model are propagated to the View. Your calls to Model.addRow() inform the View that a row was added. Your Vector.removeAllElements() call is not informed to the View so after that call View and Model are out of sync (that is, if they weren't both empty before). The call to Model.fireTableDataChanged informs the View that the whole table data in the Model has changed. After this call they are in sync again. When Model and View are out of sync, you can expect ArrayOutOfBoundException's to occur e.g. during sorting.
I also had this problem recently - a NullPointerException caused by DefaultRowSorter.getViewToModelAsInts.
The problem for me is that I was trying to directly update the GUI when an exception was thrown in SwingWorker's doInBackground() method. I found the exact solution to my particular problem here. Maybe that will help you or at least point you in the right direction as I wouldn't be surprised if your problem was because you are trying to manipulate the GUI from the wrong thread.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am having a hard time finding the source of the problem in my currency converter.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Adam_Markros_Valutaomvandlare extends JFrame implements ActionListener {
JPanel left, middle, right;
JFrame ram;
JButton buttonOK;
JTextField fieldfrom, fieldto, extrafield;
JLabel labelfrom, labelto, labeldollar, labeleuro, labelpund, labelkrona, extralabel, nothing;
JRadioButton buttonDollar, buttonEuro, buttonPund, buttonKrona;
JRadioButton buttonDollar2, buttonEuro2, buttonPund2, buttonKrona2;
ButtonGroup GroupFrom = new ButtonGroup();
ButtonGroup GroupTo = new ButtonGroup();
int currencyFrom;
int currencyTo;
int taljare = 0;
int USD = 6;
int Pund = 10;
int Euro = 9;
int other;
int namnare = 0;
public Adam_Markros_Valutaomvandlare(){
left = new JPanel();
middle = new JPanel();
right = new JPanel();
setSize(600,250);
setTitle("Adam Markros - Valutaomvandlare");
setLayout(new GridLayout(1,3));
left.setLayout(new GridLayout(6,1));
middle.setLayout(new GridLayout(6,1));
right.setLayout(new GridLayout(6,1));
this.add(left);
this.add(middle);
this.add(right);
buttonOK = new JButton("OK");
fieldfrom = new JTextField();
fieldto = new JTextField();
extrafield = new JTextField();
labelfrom = new JLabel("Från:");
labelto = new JLabel("Till:");
extralabel = new JLabel("Annan valuta:");
nothing = new JLabel("");
buttonDollar = new JRadioButton("USD");
buttonEuro = new JRadioButton("Euro");
buttonPund = new JRadioButton("Pund");
buttonKrona = new JRadioButton("SEK");
buttonDollar2 = new JRadioButton("USD");
buttonEuro2 = new JRadioButton("Euro");
buttonPund2 = new JRadioButton("Pund");
buttonKrona2 = new JRadioButton("SEK");
GroupFrom.add(buttonDollar);
GroupFrom.add(buttonEuro);
GroupFrom.add(buttonPund);
GroupFrom.add(buttonKrona);
GroupTo.add(buttonDollar2);
GroupTo.add(buttonEuro2);
GroupTo.add(buttonPund2);
GroupTo.add(buttonKrona2);
left.add(labelfrom);
left.add(buttonDollar);
left.add(buttonEuro);
left.add(buttonPund);
left.add(buttonKrona);
left.add(fieldfrom);
middle.add(extralabel);
middle.add(extrafield);
middle.add(buttonOK);
right.add(labelto);
right.add(buttonDollar2);
right.add(buttonEuro2);
right.add(buttonPund2);
right.add(buttonKrona2);
right.add(fieldto);
buttonOK.addActionListener(this);
fieldfrom.addActionListener(this);
fieldto.addActionListener(this);
extrafield.addActionListener(this);
buttonDollar.addActionListener(this);
buttonDollar2.addActionListener(this);
buttonEuro.addActionListener(this);
buttonEuro2.addActionListener(this);
buttonPund.addActionListener(this);
buttonPund2.addActionListener(this);
buttonKrona.addActionListener(this);
buttonKrona2.addActionListener(this);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main (String[] args){
new Adam_Markros_Valutaomvandlare();
}
public void actionPerformed(ActionEvent e) {
if((fieldfrom.getText().toString()) != ""){
currencyFrom = Integer.parseInt(fieldfrom.getText());
}
if((fieldto.getText().toString()) != ""){
currencyTo = Integer.parseInt(fieldto.getText());
}
if((extrafield.getText().toString()) != ""){
taljare = Integer.parseInt(extrafield.getText());
}
/*
if(e.getSource() == buttonDollar){
currencyFrom = USD;
}
if(e.getSource() == buttonDollar2){
currencyTo = USD;
}
if(e.getSource() == buttonPund){
currencyFrom = Pund;
}
if(e.getSource() == buttonPund2){
currencyTo = Pund;
}
if(e.getSource() == buttonEuro){
currencyFrom = Euro;
}
if(e.getSource() == buttonEuro2){
currencyTo = Euro;
}
if(e.getSource() == buttonKrona){
currencyFrom = 1;
}
if(e.getSource() == buttonKrona2){
currencyTo = 1;
}
else{
taljare = other;
}
*/
if(e.getSource() == buttonOK){
if(buttonPund.isSelected()){
taljare = 10;
}
if(buttonDollar.isSelected()){
taljare = 6;
}
if(buttonEuro.isSelected()){
taljare = 9;
}
if(buttonKrona.isSelected()){
taljare = 1;
}
if(buttonPund2.isSelected()){
namnare = 10;
}
if(buttonDollar2.isSelected()){
namnare = 6;
}
if(buttonEuro2.isSelected()){
namnare = 9;
}
if(buttonKrona2.isSelected()){
namnare = 1;
}
currencyTo = (currencyFrom * (taljare / namnare));
fieldto.setText(Integer.toString(currencyTo));
}
}
}
Here are the errors:
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 Adam_Markros_Valutaomvandlare.actionPerformed(Adam_Markros_Valutaomvandlare.java:116)
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.JToggleButton$ToggleButtonModel.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$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$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)
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 Adam_Markros_Valutaomvandlare.actionPerformed(Adam_Markros_Valutaomvandlare.java:119)
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.JToggleButton$ToggleButtonModel.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$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$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)
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 Adam_Markros_Valutaomvandlare.actionPerformed(Adam_Markros_Valutaomvandlare.java:119)
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$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$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)
Don't use == or != for comparing Strings since these check if one object reference is the same as another, something you're not interested in.
Use equals(...) Or in your case isEmpty() since these check to see if a String's contents are the same as another or if a String is empty.
if (!myTextField.getText().isEmpty()) {
}