program not exiting upon GUI creation - java

For testing purposes I have created a GUI in my ClientGUI class. The program never seems to exit and hangs.I call my create function in main to see how the gui looks and after this the program should terminate but instead it hangs.Please explain to me why this is happening.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class ClientGUI extends JFrame{
// creates username textfield
private JLabel username = new JLabel("Username ");
private JTextField textUsername = new JTextField(10);
//creates password textfield
private JLabel password = new JLabel("Password ");
private JPasswordField passText = new JPasswordField(10);
// adding two buttons
private JButton Login = new JButton("Login");
private JButton Create = new JButton("Create");
private JPanel error;
private JFrame my_error;
private JLabel errormsg = new JLabel("Error Try Again");
private JButton cancel_me = new JButton("OK");
private String option;
private String usr_name;
private char [] ident;
private String pass;
private String passme;
public volatile boolean []go = new boolean[1];
// constructor
ClientGUI(){
super("GossApp"); //title of jframe
}
public void CreatGui(){
JPanel myPanel = new JPanel(new GridBagLayout()); // creates a panel of type gridbaglayout
GridBagConstraints GridC = new GridBagConstraints();// constraints for layout
GridC.insets = new Insets(0,10,0,10); // spacing
// position 0,0 is corner
GridC.gridx = 0;
GridC.gridy = 0;
myPanel.add(username, GridC); // adding to panel
// position 0,1 adding user text field below username
GridC.gridy = 1;
myPanel.add(textUsername, GridC);
// position 0, 2 adding password name below user
GridC.gridx = 0;
GridC.gridy = 2;
myPanel.add(password, GridC);
//position 0,3 adding password text field below password
GridC.gridy = 3;
myPanel.add(passText, GridC);
// adding login button to panel next to password text
GridC.gridx = 1;
GridC.gridy = 3;
myPanel.add(Login, GridC);
Login.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*
String my_name = textUsername.getText();
char [] my_password = passText.getPassword();
String my_stringword = new String(my_password);
*/
option ="log";
whileLog(option);
}
});
// adding create button gui next to user text field
GridC.gridx = 1;
GridC.gridy = 1;
myPanel.add(Create,GridC);
Create.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
option= "create";
whileLog(option);
}
});
add(myPanel); //adds gui to jframe
setSize(270,170); // creates dimensions of frame
setLocationRelativeTo(null); // center gui
setVisible(true); // I can see!
my_error = new JFrame("Error");
error = new JPanel(new GridBagLayout());
GridC.gridx= 1;
GridC.gridy = 1;
error.add(cancel_me,GridC);
cancel_me.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
my_error.setVisible(false);
}
});
GridC.gridy = 2;
error.add(errormsg,GridC);
my_error.add(error);
my_error.pack();
my_error.setLocationRelativeTo(null);
my_error.setVisible(false);
}
public class clientserver{
public static void main(String[]args) {
ClientGUI my_gui = new ClientGUI();
my_gui.CreatGui();
}
}

you need to set
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
For your ClientGui, otherwise the default kicks in, which makes it not really close. The default keeps the JVM running as the JFrame hasnĀ“t been destroyed properly.
an additional small paragraph from the methods documentation, which shows what the default is.
[...]
HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects.
[...]
EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.
[...]
The value is set to HIDE_ON_CLOSE by default. Changes to the value of this property cause the firing of a property change event, with property name "defaultCloseOperation".
[...]

Related

Accessing Java Swing Components Through Another Class? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to access java swing components from a different class. For example, I need to change the text on a button once a specific operation has been completed. I am trying to use "getters" and "setters" to do the operation(at the bottom of the section of code.) Right now I only want to "set" the text.
I have another class that calls the "set" method and tries to set the text of the chosen button. This is the main class. The line of code that is "gui.setProcessItemBtn().setText("Some Text");" Throws:
Exception in thread "main" java.lang.NullPointerException
I believe this means that there isnt anything to set the text to. Am i missing something to link my setter methods to the actual gui components?
Main class
package book;
import book.UserInterface;
/**
*
* #author KJ4CC
*/
public class Book {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
UserInterface gui = new UserInterface();
gui.startUI();
gui.setProcessItemBtn().setText("Some Text");
}
}
User Interface class
public class UserInterface extends JFrame {
private JButton processItem;
private JButton confirmItem;
private JButton viewOrder;
private JButton finishOrder;
private JButton newOrder;
private JButton exit;
public void startUI(){
UserInterface gui = new UserInterface();
gui.bookingUI();
}
public static void bookingUI(){
//sets windows, and pane in the UI
JFrame frame = new JFrame("Ye old Book stoppe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel toppane = new JPanel(new GridBagLayout());
JPanel bottomPane = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
frame.setSize(800, 300);
frame.setVisible(true);
//adds labels to the window
//----------------------------------------------------------BUTTOM PANE-------------------------
//setting up buttons to be placed onto the bottompanel
JButton processItem = new JButton("Process Item");
JButton confirmItem = new JButton("Confirm Item");
JButton viewOrder = new JButton("View Order");
JButton finishOrder = new JButton("Finish Order ");
JButton newOrder = new JButton("New Order");
JButton exit = new JButton("Exit");
//adding the buttons to the pane.---------------------------------------------------------------
GridBagConstraints b = new GridBagConstraints();
b.insets = new Insets(5,5,5,5);
b.ipadx = 10;
b.ipady = 10;
b.gridx = 1;
b.gridy = 0;
bottomPane.add(processItem, b);
b.gridx = 2;
b.gridy = 0;
bottomPane.add(confirmItem,b);
confirmItem.setEnabled(false);
b.gridx = 3;
b.gridy = 0;
bottomPane.add(viewOrder, b);
viewOrder.setEnabled(false);
b.gridx = 4;
b.gridy = 0;
bottomPane.add(finishOrder,b);
finishOrder.setEnabled(false);
b.gridx = 5;
b.gridy = 0;
bottomPane.add(newOrder,b);
b.gridx = 6;
b.gridy = 0;
bottomPane.add(exit, b);
bottomPane.setBackground(Color.BLUE);
frame.add(bottomPane,BorderLayout.SOUTH);
frame.setSize(810, 310);
}
//Creating getters and setters to change the text for the buttons and labels.
public JButton setProcessItemBtn(){
return processItem;
}
public JButton setConfirmItemBtn(){
return confirmItem;
}
public JButton setViewOrderbtn(){
return viewOrder;
}
public JButton setFinishOrderBtn(){
return finishOrder;
}
public JButton setNewOrderBtn(){
return newOrder;
}
public JButton setsetExitBtn(){
return exit;
}
Firstly, this is actually a getter, since it return's a value.
public JButton setProcessItemBtn(){
return processItem;
}
This would be a setter
public void setProcessItemBtn(JButton btn){
processItem = btn;
}
But, you don't seem to have one of those.
If you did have that method, then you could do something like this
public static void main(String[] args) {
UserInterface gui = new UserInterface();
gui.setProcessItemBtn(new JButton("Some Text"));
gui.startUI();
}
Now, that isn't perfect, nor is it guaranteed to show a button at all, but the idea of "setting" a value is what is important.
Alternatively, you may want to not use a static method or making a new JFrame when you class already extends one... Try something like this
public class UserInterface extends JFrame {
// Button variables
public UserInterface(){
bookingUI();
}
public void bookingUI(){
//sets windows, and pane in the UI
setTitle("Ye old Book stoppe");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel toppane = new JPanel(new GridBagLayout());
JPanel bottomPane = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
setSize(800, 300);
setVisible(true);
//setting up buttons to be placed onto the bottompanel
processItem = new JButton("Process Item");
confirmItem = new JButton("Confirm Item");
viewOrder = new JButton("View Order");
finishOrder = new JButton("Finish Order ");
newOrder = new JButton("New Order");
exit = new JButton("Exit");
// etc...
}
Then you can try UserInterface gui = new UserInterface(); and get the buttons, and set the text on them
There are multiple errors in your code:
The NPE occurs due to this:
You have 2 variables called processItem, one global variable:
private JButton processItem;
and one local variable:
JButton processItem = new JButton("Process Item");
the second processItem variable only exists within the bookingUI() method and the one you're returning on your getter is the global one, which is not initialized!
If you want to initialize the global variable processItem remove this word JButton from here:
JButton processItem = new JButton("Process Item");
That's why you're returning a not initialized variable
You're creating a JFrame object and extending JFrame for no reason, remove the extends JFrame part on your class.
Why are your setter methods returning a value? As a convention they should be void (and set a value) and the getters should be the ones returning something.
You're not indenting your code correctly
You're making your JFrame visible before you have painted everything in it, it will cause you troubles later
You're not placing your program inside the EDT

Tried to add data to the JTable Dynamically using DefaultTableModel but it is not working

I tried to add data to the JTable Dynamically using DefaultTableModel, but it isn't working.
I had created two classes: One class (Input.java) represents a popup which allows you to write the data (name, option and constraint) and save it. Another class represents a popup which includes a table (InputMain.java). InputMain will then transform those info (if received) to a row with in the table that list out those all the information in three columns. In Input, I created an instance of InputMain, and set the model of the table to a new DefaultTableModel() (if I don't do this, it will throw an error) (a table is already created in InputMain, so that if I create an instance of InputMain, I am probably calling the table within InputMain). Then, according to actionPerformed(ActionEvent e), after the 'enter' button is clicked within the JPanel, it will create a new array of data with nameText, optionText and constraintText. And finally, the data will be added to the model.
I don't know why I can't add all those data into the table, except that method above sounds logical to me.
Here's the InputMain.java class:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by paull on 14/5/2016.
*/
public class InputMain {
JButton add;
JButton change;
JButton delete;
JTable table;
String[] columns;
String[][] data;
JButton create;
JPanel labelPanel;
JPanel bigPanel;
JPanel centerPanel;
public InputMain() {
int fontSize = 50;
add = new JButton("add");
change = new JButton("change");
delete = new JButton("delete");
create = new JButton("create");
columns = new String[]{"name","option","constraint"};
data = new String[][]{{"","",""}};
table = new JTable(data,columns) {
#Override
public boolean isCellEditable(int row, int column) {
return false; //to avoid it from being changable by double clicking any data
}
};
table.setPreferredScrollableViewportSize(new Dimension(450,63));
table.setFillsViewportHeight(true);
JScrollPane jsp = new JScrollPane(table); // not always can the table be fully shown --> add a scrollbar
add.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
change.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
delete.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
create.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
table.setFont(new Font(table.getName(),Font.PLAIN,fontSize));
//table.getEditorComponent().setFont(new Font(add.getName(),Font.PLAIN,fontSize));
table.getTableHeader().setFont(new Font(table.getName(),Font.PLAIN,fontSize));
labelPanel = new JPanel();
labelPanel.add(add);
labelPanel.add(change);
labelPanel.add(delete);
labelPanel.setLayout(new FlowLayout(10,30,10));
centerPanel = new JPanel();
centerPanel.add(labelPanel);
centerPanel.setLayout(new GridBagLayout());
bigPanel = new JPanel();
bigPanel.setLayout(new GridLayout(3,0));
bigPanel.add(centerPanel);
bigPanel.add(jsp);
bigPanel.add(create);
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
Input i = new Input();
s.add(i.labelPanel);
s.setVisible(true);
}
}); // pressing add button pops up the Input Frame
}
}
And here's the Input.java class:
package com.company;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by paull on 14/5/2016.
*/
public class Input extends JPanel{
JLabel nameLabel;
JLabel optionLabel;
JLabel constraintLabel;
JButton enter;
JPanel labelPanel;
JPanel jp2;
JPanel jp3;
JPanel jp4;
JTextField nameText;
String[] optionStrings;
JComboBox<String> optionText;
JCheckBox wk1;
JCheckBox wk2;
JCheckBox wk3;
JCheckBox wk4;
JCheckBox wk5;
public Input() {
nameLabel = new JLabel("name: ");
optionLabel = new JLabel("option: ");
constraintLabel = new JLabel("constraint:");
enter = new JButton("add");
nameText = new JTextField(10);
Options c = new Options();
optionStrings = new String[]{c.satNight,c.sunEight,c.sunNineThirty,c.sunEleven,c.sunNight};
optionText = new JComboBox<String>(optionStrings);
wk1 = new JCheckBox("1");
wk2 = new JCheckBox("2");
wk3 = new JCheckBox("3");
wk4 = new JCheckBox("4");
wk5 = new JCheckBox("5");
int fontSize = 50;
nameLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
optionLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
constraintLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
enter.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
nameText.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
optionText.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk1.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk2.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk3.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk4.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk5.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
labelPanel = new JPanel();
labelPanel.add(nameLabel);
labelPanel.add(nameText);
labelPanel.add(optionLabel);
labelPanel.add(optionText);
labelPanel.add(constraintLabel);
labelPanel.add(wk1);
labelPanel.add(wk2);
labelPanel.add(wk3);
labelPanel.add(wk4);
labelPanel.add(wk5);
labelPanel.add(enter);
labelPanel.setLayout(new FlowLayout(10,30,10));
InputMain i = new InputMain();
i.table.setModel(new DefaultTableModel());
DefaultTableModel model = (DefaultTableModel) i.table.getModel();
enter.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String constraintText = "";
String[] data = new String[]{nameText.getText(),optionText.getSelectedItem().toString(),constraintText};
model.addRow(data);
nameText.setText("");
}
});
}
}
Thanks in advance.
I think the problem lies in the actionPerformed of InputMain.
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
Input i = new Input();
s.add(i.labelPanel);
s.setVisible(true);
}
});
You construct a new instance of Input. That means that you create a new empty DefaultTableModel and attach it to your table each time you click on the add button. Try move the construction of the Input outside of your actionPerformed like this:
Input i = new Input();
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
s.add(i.labelPanel);
s.setVisible(true);
}
UPDATE
Of course the instantiation of InputMain inside of Input should be removed, too. Instead have a member of Type InputMain in Input:
private InputMain inputMain;
and change the constructor of Input to set the value:
public Input (InputMain inputMain) {
this.inputMain = inputMain;
...
And change the instantiation of Input in InputMain to
Input i = new Input(this);

Create Text in JText Field that user can not edit in java

I am creating a game similar to the star wars game sabacc. I am trying to create a Jtextfield that has three card suites already on the screen. The user will press a button and depending on the button they press the card suit will change to a different suit. If they get three of the same suites they win. I am having trouble getting text onto the screen though. As of right now I keep getting an error saying non static method can not be referenced by a static content.
Here is my code for the main application :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CardApp extends JFrame implements ActionListener {
private JButton oneButton,
twoButton,
threeButton;
private int width = 25;
private int height = 15;
public CardApp() {
//JPanel boardPanel = new JPanel(new GridLayout(height,width));
JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
JTextField TextField = new JTextField(30);
Hand settingTheText = new Hand();
TextField.setText(settingTheText.ListOfCards());
oneButton = new JButton("1");
twoButton = new JButton("2");
threeButton = new JButton("3");
// Listen for events on each button
oneButton.addActionListener(this);
twoButton.addActionListener(this);
threeButton.addActionListener(this);
// Add each to the panel of buttons
buttonPanel.add(oneButton);
buttonPanel.add(twoButton);
buttonPanel.add(threeButton);
// Add everything to a main panel attached to the content pane
JPanel mainPanel = new JPanel(new BorderLayout());
getContentPane().add(mainPanel);
mainPanel.add(TextField, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setTitle("Sabacc Example by Angela Rucci");
setSize(375, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
int pressed = 0;
if (e.getSource() == oneButton){
pressed = 1;}
if (e.getSource() == twoButton){
pressed = 2;}
if (e.getSource() == threeButton){
pressed = 3;}
Hand handObject = new Hand();
///This IS WHERE IM GETTING MY ERROR!//
String screenText = handObject.ListOfCards();
TextField.setText(screenText);
}
public static void main(String[] args) {
CardApp c = new CardApp();
}
}
This is the other file where i am getting my list of suits
package cardapp;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Hand {
String [] Suits = {"C", "H", "S", "D"};
String [] probability = {"C","H","R","D"};
Random randomInt = new Random ();
String RandomSuit;
String RandomShuffle;
String ThreeSuits;
String LeftSuit;
String MiddleSuit;
String RightSuit;
int pressed = 0;
public int Discards(int pressedNumber){
return pressed;
}
public void Randomizer (){
int RandomSuitNumber = randomInt.nextInt(4);//this is generator a random number
//------------------Decide what hand to randomize --------------------------//
if (pressed==1){
LeftSuit= Suits[RandomSuitNumber];
}
if (pressed==2){
MiddleSuit=Suits[RandomSuitNumber];
}
if (pressed==3){
RightSuit=Suits[RandomSuitNumber];
}
//----------------20% chance of new random set------------------------------------//
int ProabilityRandomNum = randomInt.nextInt(5);//this will create a random number for probability array
RandomShuffle= probability[ProabilityRandomNum];//this will pick a random letter in proability array
//------------If proability array equals R then change all of the suits----------//
if (RandomShuffle.equals("R")){
JOptionPane.showMessageDialog(null, "Randomized Hand!");
int leftNumber = randomInt.nextInt(4);
int middleNumber = randomInt.nextInt(4);
int rightNumber = randomInt.nextInt(4);
LeftSuit= Suits[leftNumber];
MiddleSuit= Suits[middleNumber];
RightSuit= Suits[rightNumber];}
ThreeSuits = (LeftSuit + MiddleSuit + RightSuit);
}
public String ListOfCards (){
return ThreeSuits;
}
public void GameOver(){
if (LeftSuit == MiddleSuit && MiddleSuit == RightSuit &&
RightSuit== LeftSuit){
JOptionPane.showMessageDialog(null, "WINNER!!");
}
}
}
The variables are local to the method. the JTextField TextField is visible to the CardApp() only. if you want it to be available to the whole class, put it as a private class member :
public class CardApp extends JFrame implements ActionListener {
private JButton oneButton,
twoButton,
threeButton;
private int width = 25;
private private int height = 15;
// available to all methods
// better naming convention was JTextfield tf = new JTextField(30);
// even stackoverflow thinks its a class name :)
// see the color highlighting
private JTextField TextField = new JTextField(30);
public CardApp() {
//JPanel boardPanel = new JPanel(new GridLayout(height,width));
JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
//JTextField TextField = new JTextField(30);
Hand settingTheText = new Hand();
TextField.setText(settingTheText.ListOfCards());
}
//
// code continues here ...
//
}

Graphical User Interface Binary to Decimal Converter

I've tried to finish my program and all it does is it keeps on opening up a new JFrame. What have I done wrong?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class BinaryConverter {
public static void main(String[] args) {
new BinaryConverter();
}
private JFrame frame;
private JButton button;
private JTextField text;
private JTextField text2;
private String decimalnumber = null;
// Constructor - builds and displays the window.
public BinaryConverter() {
frame = new JFrame("Let's Convert!");
// Create JLabel object for "Binary:" and add it to frame.
JLabel label = new JLabel("Binary:");
frame.setLayout(new FlowLayout());
frame.add(label);
// Create JTextField object and add it to frame
text = new JTextField(15);
frame.add(text);
// Create JLabel object for "Decimal:" and add it to frame.
JLabel label2 = new JLabel("Decimal:");
frame.add(label2);
// Create JTextField object and add it to frame
text2 = new JTextField(15);
frame.add(text2);
// Create JButton object and add it to frame.
button = new JButton("Convert");
button.addActionListener(new ButtonListener());
frame.add(button);
// Set frame attributes and make frame visible
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void Convert() {
String binary = text.getText(); // inserted binary number
int i;
for (i = 0; i < binary.length(); i++) { // The exponent
char select = binary.charAt(binary.length() - i);
char number = (char) (select * Math.pow(2, i));
decimalnumber += number;
}
}
public class ButtonListener implements ActionListener {
// This method is called automatically when button is clicked.
// Every Listener must have this method.
public void actionPerformed(ActionEvent e) {
BinaryConverter c = new BinaryConverter();
c.Convert();
if (button.getText().equals("Convert")) {
text2.setText(decimalnumber);
text.getText();
text2.getText();
} else {
}
}
}
}
This creates (and shows) a new instance of BinaryConverter!
// This method is called automatically when button is clicked.
// Every Listener must have this method.
public void actionPerformed(ActionEvent e) {
BinaryConverter c = new BinaryConverter(); //create/show a NEW instance!
c.Convert();
if (button.getText().equals("Convert")) {
text2.setText(decimalnumber);
text.getText();
text2.getText();
} else {
}
}
That is why it is showing new instances of the GUI.
So replace:
BinaryConverter c = new BinaryConverter();
c.Convert();
With simply:
Convert();

Trouble with integer validation and showing users have entered invalid data

This is for a Java program I'm working on as part of a homework assignment. I don't want the work done for me, but I'm stuck. I'm fairly new to Java, and using NetBeans IDE 7.0.1.
I'm having difficulty with some exception handling when trying to validate user input. This program will log charitable donations from user input. However, I've not been successful in validating the donation amount text field input. If a user inputs text instead of numbers, I would like them to be notified that their input was invalid, and I'd like the exception handling to handle the error and carry on after the user fixes their entry. Any help is greatly appreciated.
Here is my code:
package donorgui;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.awt.*;
public class DonorGUI extends JFrame
{
// Components
private JPanel panel;
private JTextArea results;
private JButton entryButton;
private JButton exitButton;
private JButton clearButton;
private JTextField donorField;
private JTextField charityField;
private JTextField pledgeField;
//create variables
String[] donorName = new String[20];
String[] charityName = new String[20];
double[] donationAmt = new double[20];
int i = 0;
// Constants for the window size
private final int WINDOW_WIDTH = 750;
private final int WINDOW_HEIGHT = 510;
//Constructor
public DonorGUI(){
// Set the title.
setTitle("Donor");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel that contains the other components.
buildPanel();
// Add the panel to the content pane.
add(panel);
// Size and display the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
}
//The buildPanel method creates a panel containing other components.
private void buildPanel(){
// Create labels to display instructions.
JLabel message1 = new JLabel("Name of the Donor:");
JLabel message2 = new JLabel("Name of the Charity:");
JLabel message3 = new JLabel("Amount of the Pledge:");
//instantiate the results area
results = new JTextArea(25,60);
// Create text fields to receive user input
donorField = new JTextField(10);
charityField = new JTextField(10);
pledgeField = new JTextField(10);
//create the user buttons to cause action
entryButton = new JButton("Enter Donation.");
entryButton.addActionListener(new EntryButtonListener());
exitButton = new JButton("EXIT");
exitButton.addActionListener(new ExitButtonListener());
clearButton = new JButton ("Clear Fields");
clearButton.addActionListener(new ClearButtonListener());
// Create a panel.
panel = new JPanel();
//set the LayoutManager
panel.setLayout(new FlowLayout());
// Add the labels, text fields, and button to the panel.
panel.add(message1);
panel.add(donorField);
panel.add(message2);
panel.add(charityField);
panel.add(message3);
panel.add(pledgeField);
panel.add(results);
panel.add(entryButton);
panel.add(exitButton);
panel.add(clearButton);
}
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
donationAmt[i] = Double.parseDouble(pledgeField.getText());
results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
i++;
}
}
public boolean donationAmt(String amount) {
int i = 0;
try {
i = Integer.parseInt (amount);
return true;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid Input. Please enter a dollar amount");
return false;
}
}
private class ClearButtonListener implements ActionListener {
#Override
public void actionPerformed (ActionEvent e) {
donorField.setText("");
charityField.setText("");
pledgeField.setText("");
}
}
private class ExitButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
/* Application method */
public static void main(String[] args){
DonorGUI rpc = new DonorGUI();
}
}
Here is my revised code. After some user input testing, I'm getting an exception when I use 100.00, 40.00, etc... instead of whole dollar amounts, such as 100, 40, etc.
Any thoughts?
package donorgui;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.awt.*;
public class DonorGUI extends JFrame
{
// Components
private JPanel panel;
private JTextArea results;
private JButton entryButton;
private JButton exitButton;
private JButton clearButton;
private JTextField donorField;
private JTextField charityField;
private JTextField pledgeField;
//create variables
String[] donorName = new String[20];
String[] charityName = new String[20];
double[] donationAmt = new double[20];
int i = 0;
// Constants for the window size
private final int WINDOW_WIDTH = 750;
private final int WINDOW_HEIGHT = 550;
//Constructor
public DonorGUI(){
// Set the title.
setTitle("Donor");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel that contains the other components.
buildPanel();
// Add the panel to the content pane.
add(panel);
// Size and display the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
}
//The buildPanel method creates a panel containing other components.
private void buildPanel(){
// Create labels to display instructions.
JLabel message1 = new JLabel("Name of the Donor:");
JLabel message2 = new JLabel("Name of the Charity:");
JLabel message3 = new JLabel("Amount of the Pledge:");
//instantiate the results area
results = new JTextArea(25,60);
// Create text fields to receive user input
donorField = new JTextField(10);
charityField = new JTextField(10);
pledgeField = new JTextField(10);
//create the user buttons to cause action
entryButton = new JButton("Enter Donation.");
entryButton.addActionListener(new EntryButtonListener());
exitButton = new JButton("EXIT");
exitButton.addActionListener(new ExitButtonListener());
clearButton = new JButton ("Clear Fields");
clearButton.addActionListener(new ClearButtonListener());
// Create a panel.
panel = new JPanel();
//set the LayoutManager
panel.setLayout(new FlowLayout());
// Add the labels, text fields, and button to the panel.
panel.add(message1);
panel.add(donorField);
panel.add(message2);
panel.add(charityField);
panel.add(message3);
panel.add(pledgeField);
panel.add(results);
panel.add(entryButton);
panel.add(exitButton);
panel.add(clearButton);
}
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
if (donationAmt(pledgeField.getText())) {
donationAmt[i] = Double.parseDouble(pledgeField.getText());
}
results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
i++;
}
}
public boolean donationAmt(String amount) {
if(amount==null || amount=="" || amount.length()<1){ //checking for empty field
JOptionPane.showMessageDialog(null, "Please enter a dollar amount");
return false;
}
for(int i = 0; i < amount.length(); i++){ //verifying dollar amount entered as number
if (!Character.isDigit(amount.charAt(i))){
JOptionPane.showMessageDialog(null, "Invalid input. Please enter a dollar amount");
return false;
}
}
return true;
}
private class ClearButtonListener implements ActionListener {
#Override
public void actionPerformed (ActionEvent e) {
donorField.setText("");
charityField.setText("");
pledgeField.setText("");
}
}
private class ExitButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
/* Application method */
public static void main(String[] args){
DonorGUI rpc = new DonorGUI();
}
}
You can use InputVerifier, discussed here.
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
if(donationAmt(pledgeField.getText())){
donationAmt[i] = Double.parseDouble(pledgeField.getText());
results.append(donorName[i] + " " + charityName[i] + " " + donationAmt[i] + "\n ");
i++;
}
}
}
Something like this would work. This checks so that the amount is not empty and contains only digits based on your exisiting method.
public boolean donationAmt(String amount) {
if(amount==null || amount=="" || amount.length()<1){ //check so that the amount field is not empty, pherhaps you can add a check so the amound is not 0 :)
JOptionPane.showMessageDialog(null, "Invalid Input. The amount cannot be empty");
return false;
}
for(int i = 0; i < amount.length(); i++){ //loop thru the string and check so that each char is a digit
if (!Character.isDigit(amount.charAt(i))){
JOptionPane.showMessageDialog(null, "The amount can contain only numbers");
return false;
}
return true;
If you want to make sure that the amount is not 0, one approach would be to parse amount to int, and check so that parsedAmount<0. This should be done after it's verified that the amount is not empty and is only digits (e.i last:) ) to avoid NPE's and numberformatexception

Categories