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
Related
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".
[...]
EDITED
I've probably just stared at the screen for WAYYY too long but I feel the need to submit this question prior to going to sleep incase my delirium remains true...
The problem I'm having is I'm trying to get an int/double from the JTextField textField and convert it to a(n) int/double to use later in a listener, after retrieving it from a listener... ListenForText implements KeyListener, specifically KeyTyped, to obtain, through toString(), and store it in a String txtFldAmnt. After which I will store the result of Integer.parseInt(txtFldAmnt) into fldAmnt (fldAmnt = Integer.pareseInt(txtFldAmnt)) LINE 99 if copied to an editor. Once it's converted into an int I want to be able to manipulate it and then use it again, at LINE 173, to display, in a new window, the fldAmnt. Honestly, I don't really care about whether it's an int or String displayed, but I know a String is required for JTextField. What magic am I missing? Answers are always welcome but I prefer a chance to learn. Also, as I'm fairly new to Java, off topic pointers, criticism, and better ways to implement this code is greatly welcomed :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame{
/**
* wtf is the serial version UID = 1L
*/
private static final long serialVersionUID = 1L;
private JButton wdBtn;
private JButton dpBtn;
private JButton xferBtn;
private JButton balBtn;
private JRadioButton chkRadio;
private JRadioButton savRadio;
private JTextField textField;
private static String txtFldAmnt;
private static int fldAmnt = 0;
private static Double chkBal = 0.00;
private static Double savBal = 0.00;
public static void main(String[] args){
new GUI();
}
public GUI() {
//default location and size
this.setSize(300,182);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("ATM Machine");
//add buttons
wdBtn = new JButton("Withdraw");
dpBtn = new JButton("Deposit");
xferBtn = new JButton("Transfer");
balBtn = new JButton("Show Balance");
chkRadio = new JRadioButton("Checking");
chkRadio.setSelected(false);
savRadio = new JRadioButton("Savings");
savRadio.setSelected(false);
textField = new JTextField("", 20);
final JLabel textLabel = new JLabel("Enter amount: ");
textField.setToolTipText("Enter amount");
//Listener class to pass button listeners
ListenForButton lForButton = new ListenForButton();
wdBtn.addActionListener(lForButton);
dpBtn.addActionListener(lForButton);
xferBtn.addActionListener(lForButton);
balBtn.addActionListener(lForButton);
chkRadio.addActionListener(lForButton);
savRadio.addActionListener(lForButton);
ListenForText textFieldListener = new ListenForText();
textField.addKeyListener(textFieldListener);
//Configure layouts
JPanel PANEL = new JPanel();
PANEL.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(2,2, 5, 10));
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(1,2,10,10));
panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayout(2,1));
//add buttons to their panels
panel1.add(wdBtn);
panel1.add(dpBtn);
panel1.add(xferBtn);
panel1.add(balBtn);
panel2.add(chkRadio);
panel2.add(savRadio);
panel3.add(textLabel);
panel3.add(textField);
PANEL.add(panel1);
PANEL.add(panel2);
PANEL.add(panel3);
this.add(PANEL);
//this.setAlwaysOnTop(true);
this.setVisible(true);
}
//implement listeners
private class ListenForText implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
txtFldAmnt = (e.toString());
fldAmnt = Integer.parseInt(txtFldAmnt);
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
private class ListenForButton implements ActionListener {
public void actionPerformed(ActionEvent e){
//maybe do case/switch statements
if (e.getSource() == wdBtn) {
JFrame newFrame = new JFrame("Withdraw Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Withdraw Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == dpBtn) {
JFrame newFrame = new JFrame("Deposit Title");
/*
* Set the newFrame.setSize(300,182); to this comment in the if statement to place
* the window directly over current window
*/
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Deposit Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == xferBtn) {
JFrame newFrame = new JFrame("Transfer Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Transfer Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == balBtn){
JFrame newFrame = new JFrame("Balance Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JTextField newLbl = new JTextField(Integer.toString(fldAmnt));
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
}
}
}
-cheers
EDITED BELOW
Thank for the answers, and I'm sorry for the horrible description... but I found a work around, thoguh I'm not sure if it's appropriate.
with the above example:
fldAmnt = Integer.pareseInt(txtFldAmnt)
i just added a .getText() //Though I rewrote the entire source code
fldAmnt = Integer.pareseInt(txtFldAmnt.getText())
it's worked for me for my entire program.
I wish I didn't have to post my entire code below but I haven't decided on a great place to store all of my code yet.
(SUGGESTIONS ARE WELCOME :D)
but here it is:
import javax.swing.;
import java.awt.GridLayout;
import java.awt.event.;
import javax.swing.border.*;
public class ATM extends JFrame{
//buttons needed
JButton wBtn;
JButton dBtn;
JButton xBtn;
JButton bBtn;
//radios needed
JRadioButton cRadio;
JRadioButton sRadio;
//Text field needed
JTextField txt;
JLabel txtLabel;
static int withdraw = 0;
Double amount = 0.00;
Double cBal = 100.00;
Double sBal = 100.00;
double number1, number2, totalCalc;
public static void main(String[] args){
new Lesson22();
}
public ATM(){
this.setSize(400, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("My Third Frame");
wBtn = new JButton("Withdraw");
dBtn = new JButton("Deposit");
xBtn = new JButton("Transfer");
bBtn = new JButton("Show Balance");
cRadio = new JRadioButton("Checking");
sRadio = new JRadioButton("Savings");
txtLabel = new JLabel("Amount: $");
txt = new JTextField("", 10);
JPanel thePanel = new JPanel();
// Create an instance of ListenForEvents to handle events
ListenForButton lForButton = new ListenForButton();
wBtn.addActionListener(lForButton);
dBtn.addActionListener(lForButton);
xBtn.addActionListener(lForButton);
bBtn.addActionListener(lForButton);
// How to add a label --------------------------
// Creates a group that will contain radio buttons
// You do this so that when 1 is selected the others
// are deselected
ButtonGroup operation = new ButtonGroup();
// Add radio buttons to the group
operation.add(cRadio);
operation.add(sRadio);
// Create a new panel to hold radio buttons
JPanel operPanel = new JPanel();
JPanel btnPanel1 = new JPanel();
JPanel btnPanel2 = new JPanel();
btnPanel1.setLayout(new GridLayout(1,2));
btnPanel2.setLayout(new GridLayout(1,2));
Border btnBorder = BorderFactory.createEmptyBorder();
btnPanel1.setBorder(btnBorder);
btnPanel1.add(wBtn);
btnPanel1.add(dBtn);
btnPanel2.setBorder(btnBorder);
btnPanel2.add(xBtn);
btnPanel2.add(bBtn);
Border operBorder = BorderFactory.createBevelBorder(1);
// Set the border for the panel
operPanel.setBorder(operBorder);
// Add the radio buttons to the panel
operPanel.add(cRadio);
operPanel.add(sRadio);
// Selects the add radio button by default
cRadio.setSelected(true);
JPanel txtPanel = new JPanel();
txtPanel.add(txtLabel);
txtPanel.add(txt);
thePanel.add(btnPanel1);
thePanel.add(btnPanel2);
thePanel.add(operPanel);
thePanel.add(txtPanel);
thePanel.setLayout(new GridLayout(4,2));
this.add(thePanel);
this.setVisible(true);
txt.requestFocus();
}
private class ListenForButton implements ActionListener{
// This method is called when an event occurs
public void actionPerformed(ActionEvent e){
/******************************************************
* THIS IS FOR CHECKING
*****************************************************/
// Check if the source of the event was the button
if(cRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
cBal -= amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel cLabel = new JLabel(Double.toString(cBal));
JLabel CLBL = new JLabel("Checking: ");
panel.add(CLBL);
panel.add(cLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
amount = Double.parseDouble(txt.getText());
cBal += amount;
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (sBal >= 0 && sBal >= amount){
cBal += amount;
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
/******************************************************
* THIS IS FOR SAVINGS
*****************************************************/
if(sRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
if(sBal >= 0 && sBal >= amount){
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel sLabel = new JLabel(Double.toString(sBal));
JLabel SLBL = new JLabel("Savings: ");
panel.add(SLBL);
panel.add(sLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
try{
amount = Double.parseDouble(txt.getText());
sBal += amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number!",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (cBal >= 0 && cBal >= amount){
sBal += amount;
cBal -= amount;
}
else if (cBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
}
...and by the way can anyone explain this warning message:
The serializable class ATM does not declare a static final serialVersionUID field of type long
If not simply don't bother. I'll keep researching into it when I have time.
This is still not complete, but thank you all for your help!
KeyListener on any JTextComponent is a bad idea.
To monitor changes to a text component, use a DocumentListener, to filter the content that a text component can handle, use a DocumentFilter. See Listening for Changes on a Document, Implementing a Document Filter and DocumentFilter Examples for more details.
In your case, it'd probably better to use a JSpinner or JFormattedTextField as they are designed to handle (amongst other things) numbers
See How to Use Spinners and How to Use Formatted Text Fields for more details
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 ...
//
}
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();
Very new to Java here. How do I use a JRadioButton to set two different text fields? The three buttons are:
1. 7 at 5.35%
2. 15 at 5.5%
3. 30 at 5.75%
Choice 1 sets field1 to 7 and field2 to 5.35
Choice 2 sets field1 to 15 and field2 to 5.5
Choice 3 sets field1 to 30 and field2 to 5.75
What's the fastest and easiest way to write this code? Seems easy enough, but I'm having a hell of a time with the JRadioButtons.
Thanks.
EDIT: Here's the code. Looks like I'm almost there, however, I still can't get the radio buttons to put the data in the fields. Says I need to change the type to int, but if I do that it's not an enterable field anymore...
//import all needed functionality
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.*;
public class ScrofaniWk3Alt extends JApplet{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* #param args
*/
// Declare variables and put code application logic here
String userInput = null;
JLabel loanAmountLabel = new JLabel("Loan Amount: ");
JTextField loanAmount = new JTextField();
double[] ratesList = {0.0535, 0.055, 0.0575};
JLabel rateLabel=new JLabel("Interest Rate: ");
JTextField rate=new JTextField();
String[] yearsList = {"7","15","30"};
JLabel yearsLabel=new JLabel("Years of Payment: ");
JTextField years=new JTextField();
JRadioButton sevenButton = new JRadioButton("7");
JRadioButton fifteenButton = new JRadioButton("15");
JRadioButton thirtyButton = new JRadioButton("30");
JLabel payLabel=new JLabel("Monthly Payment: ");
JLabel payment=new JLabel();
JButton calculate=new JButton("Calculate");
JButton clear=new JButton("Clear");
JButton quit=new JButton("Quit");
JTextArea payments=new JTextArea();
JScrollPane schedulePane=new JScrollPane(payments);
Container mortCalc = getContentPane();
public void init() {
//Configure the radio buttons to input data into fields
sevenButton.setActionCommand("Radio1");
fifteenButton.setActionCommand("Radio2");
thirtyButton.setActionCommand("Radio3");
ButtonGroup chooseYears = new ButtonGroup();
chooseYears.add(sevenButton);
chooseYears.add(fifteenButton);
chooseYears.add(thirtyButton);
}
public void actionPerformed(ActionEvent e) {
if ("Radio1".equals(e.getActionCommand())) {
years = 7;
rate = 5.35;
}
if ("Radio2".equals(e.getActionCommand())) {
years = 15;
rate = 5.5;
}
if ("Radio3".equals(e.getActionCommand())) {
years = 30;
rate = 5.75;
}
calculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// Perform the calculation
double yearsCalc=Integer.parseInt(years.getText())*12;
double rateCalc=Double.parseDouble(rate.getText())/12;
double principalCalc=Double.parseDouble(loanAmount.getText());
double monthlyPayment=principalCalc*Math.pow(1+rateCalc,yearsCalc)*rateCalc/(Math.pow(1+rateCalc,yearsCalc)-1);
DecimalFormat df = new DecimalFormat("$###,###.##");
payment.setText(df.format(monthlyPayment));
// Perform extra calculations to show the loan amount after each subsequent payoff
double principal=principalCalc;
int month;
StringBuffer buffer=new StringBuffer();
buffer.append("Month\tAmount\tInterest\tBalance\n");
for (int f=0; f<yearsCalc; f++) {
month=f+1;
double interest=principal*rateCalc;
double balance=principal+interest-monthlyPayment;
buffer.append(month+"\t"); buffer.append(new String(df.format(principal))+"\t");
buffer.append(new String(df.format(interest))+"\t"); buffer.append(new String(df.format(balance))+"\n");
principal=balance;
}
payments.setText(buffer.toString());
} catch(Exception ex) {
System.out.println(ex);
}
}
});
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loanAmount.setText(""); payment.setText(""); payments.setText("");
}
});
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(1);
}
});
//Config GUI
JPanel panelMort=new JPanel();
panelMort.setLayout(new GridLayout(5,2));
panelMort.add(loanAmountLabel);
panelMort.add(loanAmount);
panelMort.add(new Label());
panelMort.add(sevenButton);
panelMort.add(fifteenButton);
panelMort.add(thirtyButton);
panelMort.add(yearsLabel);
panelMort.add(years);
panelMort.add(rateLabel);
panelMort.add(rate);
panelMort.add(payLabel);
panelMort.add(payment);
JPanel buttons=new JPanel();
buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
buttons.add(calculate); buttons.add(clear); buttons.add(quit);
JPanel panelMort2=new JPanel();
panelMort2.setLayout(new BoxLayout(panelMort2, BoxLayout.Y_AXIS));
panelMort2.add(panelMort); panelMort2.add(buttons);
mortCalc.add(BorderLayout.NORTH, panelMort2);
mortCalc.add(BorderLayout.CENTER, schedulePane);
}
public static void main(String[] args) {
JApplet applet = new ScrofaniWk3Alt();
JFrame frameMort = new JFrame("ScrofaniWk3Alt");
frameMort.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameMort.getContentPane().add(applet);
frameMort.setSize(500,1000);
frameMort.setResizable(true);
frameMort.setVisible(true);
applet.init();
applet.start();
}
}
Read the section from the Swing tutorial on How to Use Radio Buttons. Basically you add an ActionListener to each button and then set the value in the text fields.
If you need more help then post your SSCCE that shows what you have attempted after reading the tutorial.
// put these where you define your buttons
radio1.setActionCommand("RADIO1");
radio2.setActionCommand("RADIO2");
radio3.setActionCommand("RADIO3");
// add this to your actionPerformed method
public void actionPerformed(ActionEvent e) {
if ("RADIO1".equals(e.getActionCommand())) {
field1 = 7;
field2 = 5.35;
}
if ("RADIO2".equals(e.getActionCommand())) {
field1 = 15;
field2 = 5.5;
}
if ("RADIO3".equals(e.getActionCommand())) {
field1 = 30;
field2 = 5.75;
}
}