So here is my question:
I would like to create a new panel that asks the user to enter Bank Account Information (Account Name, and Account Number) and when the user clicks on the Login button, it changes panels to the Withdraw/Deposit Panel and also displays your Account Name at the top. I have the Withdraw/Deposit Panel all completed, but am stumped on how to create the Information Panel and to make it appear BEFORE the Withdraw/Deposit Panel, etc.
Here is my code:
public class MyFrame extends JFrame {
private JPanel panel;
private JLabel wordsLabel;
private JLabel balanceLabel;
private JLabel choiceLabel;
private JTextField transactionAmount;
private JRadioButton depositButton;
private JRadioButton withdrawButton;
private double balance;
public MyFrame() {
final int FIELD_WIDTH = 5;
balance = 500;
panel = new JPanel();
wordsLabel = new JLabel();
balanceLabel = new JLabel();
choiceLabel = new JLabel();
transactionAmount = new JTextField(FIELD_WIDTH);
JPanel buttonPanel = new JPanel();
ButtonGroup myGroup = new ButtonGroup();
depositButton = new JRadioButton("Deposit");
withdrawButton = new JRadioButton("Withdraw");
transactionAmount.setText("0");
wordsLabel.setText("Welcome to Wes Banco! Your current balance is: ");
balanceLabel.setText(String.format("%10.2f", balance));
choiceLabel.setText("How much would you like to deposit/withdraw? ");
panel.setLayout(new GridLayout(4, 4, 5, 10));
panel.add(wordsLabel);
panel.add(balanceLabel);
panel.add(choiceLabel);
panel.add(transactionAmount);
myGroup.add(depositButton);
myGroup.add(withdrawButton);
buttonPanel.add(depositButton);
buttonPanel.add(withdrawButton);
ButtonListener myListener = new ButtonListener();
depositButton.addActionListener(myListener);
withdrawButton.addActionListener(myListener);
panel.add(buttonPanel);
this.add(panel);
}
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
double amount = Double.parseDouble(transactionAmount.getText());
if (amount == 0) {
JOptionPane.showMessageDialog(null,
"You cannot deposit or withdraw nothing!");
JOptionPane.showMessageDialog(null,
"Please enter a valid amount.");
} else {
if (event.getSource() == depositButton) {
JOptionPane.showMessageDialog(null,
"You have deposited: " + amount);
balance += amount;
} else if (event.getSource() == withdrawButton) {
if (balance < amount) {
JOptionPane.showMessageDialog(null,
"You do not have sufficient funds to complete this transaction.");
JOptionPane.showMessageDialog(null,
"Please enter a valid amount.");
} else {
JOptionPane.showMessageDialog(null,
"You have withdrawn: " + amount);
balance -= amount;
}
}
balanceLabel.setText(String.valueOf(balance));
}
}
}
}
My advice would be: DonĀ“t create the panel in your JFrame constructor. Make an InfoPanel class and a WithdrawPanel class. Then you can decide programatically which panel is displayed in your frame.
Related
I'm trying to make this application to calculate but it won't. Spend ages on it. I just want to calculate ones I press the button. I need it to display the correct price when clicking on the correct combo box. The prices have been set I think.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
public class retailsalescalcu extends JFrame {
//create the objects
JLabel department;
JLabel number;
JLabel name;
JLabel price;
JLabel discount;
JLabel sale;
JComboBox<String> dept;
JTextField itemNum;
JTextField itemName;
JTextField itemPrice;
JTextField itemDisc;
JTextField salePrice;
JButton calculate;
JButton clear;
public retailsalescalcu() {
//set object variables
super("Retail Sales Calculator"); //set window bar title
setSize(300, 300); //set window size
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set window close
GridLayout grid = new GridLayout(7, 2);
setLayout(grid);
department = new JLabel("Department");
dept = new JComboBox<String>();
dept.addItem("Select");
dept.addItem("Men's Clothing");
dept.addItem("Women's Clothing");
dept.addItem("Shoes");
dept.addItem("Belts");
dept.addItem("Electronics");
dept.addItem("Hats");
//add ItemListener - JTextField & ComboBox
dept.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
String str = (String)dept.getSelectedItem();
itemNum.setText(str);
} //end public void
}); //end item listener
number = new JLabel("Item Number");
itemNum = new JTextField(10);
name = new JLabel("Item Name");
itemName = new JTextField(10);
price = new JLabel("Original Price");
itemPrice = new JTextField(10);
discount = new JLabel("Discount");
itemDisc = new JTextField(10);
sale = new JLabel("Sale Price");
salePrice = new JTextField(10);
salePrice.setEditable(false);
calculate = new JButton("Calculate");
clear = new JButton("Clear");
//add objects to JFrame
add(department);
add(dept);
add(number);
add(itemNum);
add(name);
add(itemName);
add(price);
add(itemPrice);
add(discount);
add(itemDisc);
add(sale);
add(salePrice);
add(calculate);
add(clear);
//add event listener to calculate sale price
calculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent retail) {
String input1;
String input2;
double origPrice;
double percOff;
double clearance;
input1 = itemPrice.getText();
input2 = itemDisc.getText();
origPrice = Double.parseDouble(input1);
percOff = Double.parseDouble(input2)/100;
clearance = origPrice - (origPrice * percOff);
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
salePrice.setText(df.toString()); //output to JTextField
}
});
//add event listener to reset fields
clear.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent event) { //JButton event if clicked
dept.setSelectedIndex(0); //Combo Box will be empty and can be reset
itemNum.setText(null); //Item Number will be empty and can be reset
itemName.setText(null); //Item Name will be empty and can be reset
itemPrice.setText(null); //Item Price will be empty and can be reset
itemDisc.setText(null); //Item Discount will be empty and can be reset
salePrice.setText(null); //Item SalePrice will be empty and can be reset
}
});
setVisible(true);
} //end public retailsalescalcu
public static void main(String[] args) {
new retailsalescalcu();
} //end public static void
} //end public class retailsalescalcu
After debugging you code i found that you should remove/comment line #100 from your code
From
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
salePrice.setText(df.toString()); //output to JTextField
System.err.println(df.toString());
}
});
to
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
//salePrice.setText(df.toString()); //output to JTextField
System.err.println(df.toString());
}
});
EDIT:
One problem is here:
//salePrice.setText(df.toString());
Comment that out and you will see your price after clicking Calculate. You are already setting salesPrice here:
salePrice.setText(df.format(clearance));
The toString() is not going to give you what you want.
So for a class that I am currently taking I need to create an ATM System. So, I decided to have 2 panels. A main panel, where all of the processes take place, and an options panel, where the options are listed for the user. The problem, as mentioned above, is that I can't seem to get the main panel to be removed so I can actually replace it with the panel for, say the create account screen. In fact, all that happens is that the terminal window shows. Completely blank. As far as I have checked, the buttons event is firing and it even gets past the remove function.
In any event, I can't seem to figure out what the problem is, perhaps it is because the button being pressed is also being removed with the panel. Here's the related code.
public class AccountSystem extends JFrame implements ActionListener
{
public static Account currentuser = new Account(); //This is so that the methods know which account is currently logged in so they can perform operations on it.
public static int count=0;
public static Account acc[] = new Account[1000];
public static String parts[] = new String[3];
private JButton login, logout, createacc, deposit1, deposit2, withdraw1, withdraw2, transfer1, transfer2, nevermind;
private JPanel options, mainarea, titlecard;
private JTextField username, password, transfer, depositarea, withdrawarea, retypearea;
private JLabel userprompt, depositprompt, withdrawpromt, balancedisp, passwordprompt, mainmessage, title;
private String newuser, newpass, newpassconfirm;
BorderLayout borderlayout;
GridLayout gridlayout;
public AccountSystem()
{
borderlayout = new BorderLayout();
borderlayout.setHgap(5);
borderlayout.setVgap(5);
//Establishing our buttons here.
JButton login = new JButton("Login");
login.addActionListener(this);
JButton createacc = new JButton("New Account");
createacc.addActionListener(this);
//Establishing our panels here.
JPanel options = new JPanel();
JPanel mainarea = new JPanel();
JPanel titlecard = new JPanel();
//Establishing our JLabel here.
JLabel userprompt = new JLabel("Username: ");
JLabel passwordprompt = new JLabel("Password: ");
JLabel title = new JLabel(" LOGIN ");
//Establishing our textfields here.
JTextField username = new JTextField(20);
JTextField password = new JTextField(20);
JTextField transfer = new JTextField(20);
JTextField withdrawarea = new JTextField(20);
//Building the GUI here.
titlecard.setSize(500,50);
titlecard.setLocation (0,0);
mainarea.setSize(300,450);
mainarea.setLocation(0,50);
options.setSize(150,450);
options.setLocation(300,50);
titlecard.add(title);
mainarea.add(userprompt);
mainarea.add(username);
mainarea.add(passwordprompt);
mainarea.add(password);
mainarea.add(login);
mainarea.add(createacc);
getContentPane().setLayout(null);
getContentPane().add(titlecard);
getContentPane().add(mainarea);
getContentPane().add(options);
}
}
public void actionPerformed (ActionEvent e)
{
if ((e.getActionCommand()).equals("Login"))
{
login();
}
else if ((e.getActionCommand()).equals("New Account"))
{
accountmaker();
}
else if ((e.getActionCommand()).equals("Deposit Funds"))
{
deposit();
}
else if ((e.getActionCommand()).equals("Withdraw Funds"))
{
withdraw();
}
else if ((e.getActionCommand()).equals("Withdraw"))
{
withdrawprocedure();
}
else if ((e.getActionCommand()).equals("Create Account"))
{
accountprocedure();
}
}
public void accountmaker() //This is the screen where the user creates the account they want to. Of course, something needed to be done to differentiate this screen and the login screen.
{
currentuser = null; //This is so that the program doesn't get somehow confused when dealing with multiple uses of the program.
getContentPane().remove(mainarea);
title.setText("Create New Account");
mainarea = new JPanel();
JLabel userprompt = new JLabel ("Username: ");
JLabel passwordprompt = new JLabel("Password: ");
JLabel retype = new JLabel ("Retype: "); //This is what makes it different from the login screen
createacc = new JButton ("Create Account");
createacc.addActionListener(this);
JButton nevermind = new JButton("Cancel");
nevermind.addActionListener(this);
JTextField username = new JTextField(20);
JTextField password = new JTextField(20);
retypearea = new JTextField(20);
mainarea.setSize(300,500);
mainarea.setLocation(0,0);
mainarea.add(userprompt);
mainarea.add(username);
mainarea.add(passwordprompt);
mainarea.add(password);
mainarea.add(retype);
mainarea.add(retypearea);
getContentPane().add(mainarea);
getContentPane().invalidate();
getContentPane().validate();
getContentPane().repaint();
}
And this is the Account class that the program uses.
public class Account
{
private String username;
private String password;
private double balance=0;
public void deposit (double deposit)
{
balance += deposit;
}
public void withdraw (double withdraw)
{
balance -= withdraw;
}
public void setBalance (double newbalance)
{
balance = newbalance;
}
public void setUsername (String newusername)
{
username = newusername;
}
public void setPassword (String newpassword)
{
password = newpassword;
}
public String getUsername ()
{
return username;
}
public double getbalance ()
{
return balance;
}
public String getpassword()
{
return password;
}
}
If I understand correctly.. you basically need to replace the main panel with account panel on certain event!
I have written example code (please modify it according to your project)
In this code.. I have created 4 panels namely
Component Panel: To hold all components
Main Panel: contains the label with text "Main Panel" and its border is painted RED
Account Panel: contains the label with text "Account Panel" and its border is painted GREEN
Option Panel: empty panel with its border is painted BLUE
Two buttons:
Account Button: Which should replace Main Panel with Account Panel
Main Button: Which should replace Account Panel with Main Panel
Using GridBagLayout, all you need to do is to place Main Panel and Account Panel at the same location i.e. gridx = 0 and gridy = 0 for both. At first Main Panel shall be displayed. On event "Account Button" set Main Panel's visibility false and Account Panels' true. For event "Main Button" do the vica versa. GridBagLayout is fantastic dynamic layout which manages the empty spacing by itslef without any distortion.
public class SwingSolution extends JFrame implements ActionListener
{
private JPanel componentPanel = null;
private JPanel mainPanel = null;
private JLabel mainLabel = null;
private JPanel optionPanel = null;
private JPanel accountPanel = null;
private JLabel accountLabel = null;
private JButton replaceToAccountPanel = null;
private JButton replaceToMainPanel = null;
private final static String MAIN_TO_ACCOUNT = "MainToAccount";
private final static String ACCOUNT_TO_MAIN = "AccountToMain";
public JPanel getComponentPanel()
{
if(null == componentPanel)
{
componentPanel = new JPanel();
GridBagLayout gridBagLayout = new GridBagLayout();
componentPanel.setLayout(gridBagLayout);
GridBagConstraints constraint = new GridBagConstraints();
constraint.insets = new Insets(10, 10, 10, 10);
mainPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 0;
mainPanel.setMinimumSize(new Dimension(100, 50));
mainPanel.setPreferredSize(new Dimension(100, 50));
mainPanel.setMaximumSize(new Dimension(100, 50));
mainPanel.setBorder(
BorderFactory.createLineBorder(Color.RED));
mainLabel = new JLabel("Main Panel");
mainPanel.add(mainLabel);
componentPanel.add(mainPanel, constraint);
accountPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 0;
accountPanel.setMinimumSize(new Dimension(100, 50));
accountPanel.setPreferredSize(new Dimension(100, 50));
accountPanel.setMaximumSize(new Dimension(100, 50));
accountPanel.setBorder(
BorderFactory.createLineBorder(Color.GREEN));
accountLabel = new JLabel("Account Panel");
accountPanel.add(accountLabel);
componentPanel.add(accountPanel, constraint);
optionPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 1;
optionPanel.setMinimumSize(new Dimension(100, 50));
optionPanel.setPreferredSize(new Dimension(100, 50));
optionPanel.setMaximumSize(new Dimension(100, 50));
optionPanel.setBorder(
BorderFactory.createLineBorder(Color.BLUE));
componentPanel.add(optionPanel, constraint);
replaceToAccountPanel = new JButton("Account Button");
replaceToAccountPanel.setName(MAIN_TO_ACCOUNT);
constraint.gridx = 0;
constraint.gridy = 2;
replaceToAccountPanel.setSize(new Dimension(800, 30));
replaceToAccountPanel.addActionListener(this);
componentPanel.add(replaceToAccountPanel, constraint);
replaceToMainPanel = new JButton("Main Button");
replaceToMainPanel.setName(ACCOUNT_TO_MAIN);
constraint.gridx = 1;
constraint.gridy = 2;
replaceToMainPanel.setMinimumSize(new Dimension(800, 30));
replaceToMainPanel.addActionListener(this);
componentPanel.add(replaceToMainPanel, constraint);
}
return componentPanel;
}
public void actionPerformed (ActionEvent evt)
{
JButton buttonClicked = (JButton) evt.getSource();
if(buttonClicked != null)
{
if(buttonClicked.getName().equals(MAIN_TO_ACCOUNT))
{
mainPanel.setVisible(false);
accountPanel.setVisible(true);
}
else if(buttonClicked.getName().equals(ACCOUNT_TO_MAIN))
{
mainPanel.setVisible(true);
accountPanel.setVisible(false);
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
SwingSolution main = new SwingSolution();
frame.setTitle("Simple example");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setContentPane(main.getComponentPanel());
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
I need to add a button that "clears the calculator" and also one that quits the program on the butPanel. It also needs to be very basic Java code because I am a beginner and have an awful comp.sci. teacher. I have a sample of code that has the quit button, but I am unsure of how to put it into MY program. I've tried so much.
Also if there is a better way to "error-check" that would be much appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator2 extends JFrame implements ActionListener
{
JLabel heading = new JLabel ("2. Calculator");
JLabel intro1 = new JLabel ("This program stimulates a four-function calculator.");
JLabel intro2 = new JLabel ("It takes an operator and a number. It can add, subtract,");
JLabel intro3 = new JLabel (" multiply and divide. Enter in the format eg. '+35'. ");
JLabel inLabel = new JLabel (" Operation: ");
JLabel outLabel = new JLabel (" Total: ");
JTextField inOper = new JTextField (7);
JTextField outTota = new JTextField (7); // intro
//panels
JPanel titlePanel = new JPanel ();
JPanel intro1Panel = new JPanel ();
JPanel intro2Panel = new JPanel ();
JPanel intro3Panel = new JPanel ();
JPanel operPanel = new JPanel ();
JPanel totaPanel = new JPanel ();
JPanel butPanel = new JPanel ();
String operTemp;
String totaTemp;
public Calculator2 ()
{
setTitle ("C - 2.");
inOper.addActionListener (this);
outTota.setEditable (false);
getContentPane ().setLayout (new FlowLayout ());
titlePanel.add (heading);
intro1Panel.add (intro1);
intro2Panel.add (intro2);
intro3Panel.add (intro3);
operPanel.add (inLabel);
operPanel.add (inOper);
totaPanel.add (outLabel);
totaPanel.add (outTota); //adds components to panels
getContentPane ().add (titlePanel);
getContentPane ().add (intro1Panel);
getContentPane ().add (intro2Panel);
getContentPane ().add (intro3Panel);
getContentPane ().add (operPanel);
getContentPane ().add (totaPanel); //Adds panels to Frame
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static int isInteger (String input)
{
try
{
Integer.parseInt (input);
return Integer.parseInt (input);
}
catch (NumberFormatException nfe)
{
return 0;
}
} //isInteger method
// The application
public String calculate (String operation, String newtotal)
{
int total = isInteger (newtotal);
String totalS;
char operator;
int number = 0;
operator = operation.charAt (0);
if (operator == '+')
{
number = isInteger (operation.substring (1));
total = total + number;
totalS = Integer.toString (total);
}
else if (operator == '-')
{
number = isInteger (operation.substring (1));
total = total - number;
totalS = Integer.toString (total);
}
else if (operator == '*')
{
number = isInteger (operation.substring (1));
total = total * number;
totalS = Integer.toString (total);
}
else if (operator == '/')
{
number = isInteger (operation.substring (1));
total = total / number;
totalS = Integer.toString (total);
}
else
{
totalS = ("ERROR");
}
if (number == 0)
{
totalS = ("ERROR");
}
return totalS;
} // calculate method
public void actionPerformed (ActionEvent evt)
{
String userIn = inOper.getText ();
String totalIn = outTota.getText ();
try
{
totaTemp = calculate (userIn, totalIn);
outTota.setText (totaTemp + "");
}
catch (Exception ex)
{
outTota.setText ("ERROR");
}
repaint ();
}
public static void main (String[] args)
{
Calculator2 calc = new Calculator2 ();
calc.setSize (350, 350);
calc.setResizable (false);
calc.setVisible (true);
}
}
First declare the buttons and initialize them:
JButton exitButton = new JButton("Exit");
JButton clearButton = new JButton("Clear");
Then, make sure the butPanel has a layout and the panel is added to the content pane:
butPanel.setLayout(new FlowLayout());
getContentPane().add(butPanel);
Then add the action listeners on the new buttons:
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO: clear the stuff here
}
});
public class ATMgui extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int WIDTH = 500;
public static final int HEIGHT = 200;
private ATMbizlogic theBLU;// short for the Business Logic Unit
public JLabel totalBalanceLabel;
public JTextField withdrawTextField;
public JTextField depositTextField;
public JTextField pinTextField;
/**
* Creates a new instance of ATMgui
*/
public ATMgui() {
setTitle("ATM Transactions");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setBackground(Color.BLACK);
contentPane.setLayout(new BorderLayout());
// Do the panel for the rest stop
JLabel start = new JLabel("Welcome To Your Account", JLabel.CENTER);
Font curFont = start.getFont();
start.setFont(new Font(curFont.getFontName(), curFont.getStyle(), 25));
start.setForeground(Color.BLUE);
start.setOpaque(true);
start.setBackground(Color.BLACK);
pinTextField = new JTextField();
JLabel pinLabel = new JLabel("Enter your PIN below:", JLabel.CENTER);
pinLabel.setForeground(Color.RED);
pinLabel.setOpaque(true);
pinLabel.setBackground(Color.WHITE);
JButton pinButton = new JButton("Enter Pin OK");
pinButton.addActionListener(this);
pinButton.setBackground(Color.red);
JPanel pinPanel = new JPanel();
pinPanel.setLayout(new GridLayout(3, 1, 100, 0));
pinPanel.add(pinLabel);
pinPanel.add(pinTextField);
pinPanel.add(pinButton);
contentPane.add(pinPanel, BorderLayout.WEST);
JPanel headingPanel = new JPanel();
headingPanel.setLayout(new GridLayout());
headingPanel.add(start);
contentPane.add(headingPanel, BorderLayout.NORTH);
// Do the panel for the amount & type of transactions
withdrawTextField = new JTextField();
JLabel withdrawLabel = new JLabel("Withdraw (0.00)", JLabel.CENTER);
withdrawLabel.setForeground(Color.RED);
withdrawLabel.setOpaque(true);
withdrawLabel.setBackground(Color.WHITE);
depositTextField = new JTextField();
JLabel depositLabel = new JLabel("Deposit (0.00)", JLabel.CENTER);
depositLabel.setForeground(Color.RED);
depositLabel.setOpaque(true);
depositLabel.setBackground(Color.WHITE);
JButton txButton = new JButton("Transactions OK");
txButton.addActionListener(this);
txButton.setBackground(Color.red);
JPanel txPanel = new JPanel();
txPanel.setLayout(new GridLayout(5, 1, 30, 0));
txPanel.add(withdrawLabel);
txPanel.add(withdrawTextField);
txPanel.add(depositLabel);
txPanel.add(depositTextField);
txPanel.add(txButton);
contentPane.add(txPanel, BorderLayout.EAST);
txPanel.setVisible(true);
totalBalanceLabel = new JLabel("Your balance after transactions: ", JLabel.CENTER);
totalBalanceLabel.setForeground(Color.BLUE);
totalBalanceLabel.setOpaque(true);
totalBalanceLabel.setBackground(Color.BLACK);
contentPane.add(totalBalanceLabel, BorderLayout.SOUTH);
theBLU = new ATMbizlogic();
}
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
// Container contentPane = getContentPane();
if (actionCommand.equals("Transactions OK")) {
try {
double deposit = Double.parseDouble(depositTextField.getText().trim());
double withdraw = Double.parseDouble(withdrawTextField.getText().trim());
theBLU.computeBalance(withdraw, deposit);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
} catch (ATMexception ex) {
totalBalanceLabel.setText("Error: " + ex.getMessage());
} catch (Exception ex) {
totalBalanceLabel.setText("Error in deposit or withdraw amount: " + ex.getMessage());
}
} else if (actionCommand.equals("Enter Pin OK")) {
try {
double pin = Double.parseDouble(pinTextField.getText().trim());
theBLU.checkPin(pin);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
} catch (ATMexception ex) {
totalBalanceLabel.setText("Error: " + ex.getMessage());
} catch (Exception ex) {
totalBalanceLabel.setText("Error in pin: " + ex.getMessage());
}
} else {
System.out.println("Error in button interface.");
}
}
public static void main(String[] args) {
ATMgui gui = new ATMgui();
gui.setVisible(true);
}
}
I don't think this is the right way to implement ActionListeners for buttons.
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
// Container contentPane = getContentPane();
if (actionCommand.equals("Transactions OK"))
else ...
}
With the if-else stamements in the method actionPerformed, your program is forced to check what listener to invoke, every time whatever button is pressed, and, in this way, your code isn't easy to edit and reuse.
Also, the GUI Container is acting like a receiver of events, then you should avoid
pinButton.addActionListener(this);
Try to implement your own inner classes for each button, like this:
JButton pinButton = new JButton("Enter Pin OK");
pinButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae){
//enter here your action
txPanel.setVisible(true);
}
});
In this way, you don't need to implement the ActionListener interface for your class, because you're implementing a inner istance of the interface for your pinButton. Check this old question of SO.
Also, you should avoid to implement all your GUI elements in your class constructor, it's better to implement the GUI in a separate method, like createAndShowGui(), and call it in the constructor, to respect the Java Swing conventions and to run the Swing components in a different thread, called Event Dispatch Thread, different from the main thread of your application. Read this question.
Then include txPanel.setVisible(false); in createAndShowGui() method.
Remember that the Swing components are not thread-safe.
Since the code pasted by you is not working, I had made a small program for you, have a look, and see what changes can you do to incorporate that in your case :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelTest extends JFrame
{
private JPanel eastPanel;
public PanelTest()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
Container container = getContentPane();
eastPanel = new JPanel();
eastPanel.setBackground(Color.DARK_GRAY);
JPanel westPanel = new JPanel();
westPanel.setBackground(Color.YELLOW);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.BLUE);
container.add(eastPanel, BorderLayout.LINE_START);
container.add(centerPanel, BorderLayout.CENTER);
container.add(westPanel, BorderLayout.LINE_END);
eastPanel.setVisible(false);
JButton showButton = new JButton("Click Me to Display EAST JPanel");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
eastPanel.setVisible(true);
}
});
JButton hideButton = new JButton("Click Me to Hide EAST JPanel");
hideButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
eastPanel.setVisible(false);
}
});
container.add(hideButton, BorderLayout.PAGE_START);
container.add(showButton, BorderLayout.PAGE_END);
setSize(300, 300);
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PanelTest();
}
});
}
}
And from future, never use NORTH, EAST, WEST and SOUTH for BorderLayout. They have been replaced with PAGE_START, LINE_START, LINE_END and PAGE_END respectively.
A BorderLayout object has five areas. These areas are specified by the BorderLayout constants:
PAGE_START
PAGE_END
LINE_START
LINE_END
CENTER
Version note:
Before JDK release 1.4, the preferred names for the various areas were different, ranging from points of the compass (for example, BorderLayout.NORTH for the top area) to wordier versions of the constants we use in our examples. The constants our examples use are preferred because they are standard and enable programs to adjust to languages that have different orientations.
I had modified the checkPin(...) method of the ATMLogin class to return a boolean instead of void, so that inside the actionPerformed(...) method of the ATMgui class, if this thing returns true, then only to set the required JPanel to visible, else nothing is to be done.
Do check the code and see what changes you can do to make it work for your end.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ATMgui extends JFrame implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int WIDTH = 500;
public static final int HEIGHT = 200;
private ATMbizlogic theBLU;// short for the Business Logic Unit
private JPanel txPanel;
public JLabel totalBalanceLabel;
public JTextField withdrawTextField;
public JTextField depositTextField;
public JTextField pinTextField;
/**
* Creates a new instance of ATMgui
*/
public ATMgui()
{
setTitle("ATM Transactions");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setBackground(Color.BLACK);
contentPane.setLayout(new BorderLayout());
// Do the panel for the rest stop
JLabel start = new JLabel("Welcome To Your Account", JLabel.CENTER);
Font curFont = start.getFont();
start.setFont(new Font(curFont.getFontName(), curFont.getStyle(), 25));
start.setForeground(Color.BLUE);
start.setOpaque(true);
start.setBackground(Color.BLACK);
pinTextField = new JTextField();
JLabel pinLabel = new JLabel("Enter your PIN below:", JLabel.CENTER);
pinLabel.setForeground(Color.RED);
pinLabel.setOpaque(true);
pinLabel.setBackground(Color.WHITE);
JButton pinButton = new JButton("Enter Pin OK");
pinButton.addActionListener(this);
pinButton.setBackground(Color.red);
JPanel pinPanel = new JPanel();
pinPanel.setLayout(new GridLayout(3, 1, 100, 0));
pinPanel.add(pinLabel);
pinPanel.add(pinTextField);
pinPanel.add(pinButton);
contentPane.add(pinPanel, BorderLayout.WEST);
JPanel headingPanel = new JPanel();
headingPanel.setLayout(new GridLayout());
headingPanel.add(start);
contentPane.add(headingPanel, BorderLayout.NORTH);
// Do the panel for the amount & type of transactions
withdrawTextField = new JTextField();
JLabel withdrawLabel = new JLabel("Withdraw (0.00)", JLabel.CENTER);
withdrawLabel.setForeground(Color.RED);
withdrawLabel.setOpaque(true);
withdrawLabel.setBackground(Color.WHITE);
depositTextField = new JTextField();
JLabel depositLabel = new JLabel("Deposit (0.00)", JLabel.CENTER);
depositLabel.setForeground(Color.RED);
depositLabel.setOpaque(true);
depositLabel.setBackground(Color.WHITE);
JButton txButton = new JButton("Transactions OK");
txButton.addActionListener(this);
txButton.setBackground(Color.red);
txPanel = new JPanel();
txPanel.setLayout(new GridLayout(5, 1, 30, 0));
txPanel.add(withdrawLabel);
txPanel.add(withdrawTextField);
txPanel.add(depositLabel);
txPanel.add(depositTextField);
txPanel.add(txButton);
contentPane.add(txPanel, BorderLayout.EAST);
txPanel.setVisible(false);
totalBalanceLabel = new JLabel("Your balance after transactions: ", JLabel.CENTER);
totalBalanceLabel.setForeground(Color.BLUE);
totalBalanceLabel.setOpaque(true);
totalBalanceLabel.setBackground(Color.BLACK);
contentPane.add(totalBalanceLabel, BorderLayout.SOUTH);
theBLU = new ATMbizlogic();
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
// Container contentPane = getContentPane();
if (actionCommand.equals("Transactions OK"))
{
try
{
double deposit = Double.parseDouble(depositTextField.getText().trim());
double withdraw = Double.parseDouble(withdrawTextField.getText().trim());
theBLU.computeBalance(withdraw, deposit);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
}
/*catch (ATMexception ex)
{
totalBalanceLabel.setText("Error: " + ex.getMessage());
}*/
catch (Exception ex)
{
totalBalanceLabel.setText("Error in deposit or withdraw amount: " + ex.getMessage());
}
}
else if (actionCommand.equals("Enter Pin OK"))
{
try
{
double pin = Double.parseDouble(pinTextField.getText().trim());
if(theBLU.checkPin(pin))
txPanel.setVisible(true);
totalBalanceLabel.setText("Your balance after transactions: " + theBLU.getBalance());
}
/*catch (ATMexception ex)
{
totalBalanceLabel.setText("Error: " + ex.getMessage());
}*/
catch (Exception ex)
{
totalBalanceLabel.setText("Error in pin: " + ex.getMessage());
ex.printStackTrace();
}
}
else
{
System.out.println("Error in button interface.");
}
}
public static void main(String[] args)
{
ATMgui gui = new ATMgui();
gui.setVisible(true);
}
}
class ATMbizlogic
{
private double totalBalance;
private boolean rightPinEntered;
/**
* Creates a new instance of ATMbizlogic
*/
public ATMbizlogic()
{
totalBalance = 0.0;
rightPinEntered = true;
}
public void computeBalance(double withdraw, double deposit)
//throws ATMexception
{
if(withdraw <=0)
{
System.out.println("Negative withdraw not allowed");
//throw new ATMexception("Negative withdraw not allowed");
}
if(deposit <=0)
{
System.out.println("Negative deposit not allowed");
//throw new ATMexception("Negative deposit not allowed");
}
double balance = deposit - withdraw;
totalBalance = totalBalance + balance;
}
public boolean checkPin(double pin)
//throws ATMexception
{
if(pin <=0)
{
System.out.println("Negative pin not allowed");
rightPinEntered = false;
//throw new ATMexception("Negative pin not allowed");
}
/*else if(rightPinEntered == false)
{
System.out.println("Can not take another pin");
rightPinEntered = false;
//throw new ATMexception("Can not take another pin");
}*/
else if(pin<1111 || pin>9999)
{
System.out.println("Enter a valid pin");
rightPinEntered = false;
//throw new ATMexception("Enter a valid pin");
}
else
{
rightPinEntered = true;
}
return rightPinEntered;
}
public double getBalance()
{
return totalBalance;
}
}
In the call to constructor ATMgui(), put
txPanel.setVisible(false);
and in the actionCommand.equals("Enter Pin OK") part, you can set it to true.
Is that what you want?
I am having some issues with my code, I cant see whats wrong with the logic, but here it is. I want them to have the radio button to choose either or, and when one is selected(radio button) the text area isn't available and vise versa. Here is the segment of the code. When I go back and forth on the radio buttons, both become not selectable, and I am unsure why.
private void PriceTab()
{
pricePanel = new JPanel(new FlowLayout());
final JRadioButton poolPrice= new JRadioButton("Pool");
final JRadioButton tubPrice = new JRadioButton("Hot Tub");
poolPrice.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(poolPrice);
group.add(tubPrice);
pricePanel.add(poolPrice);
pricePanel.add(tubPrice);
final JLabel poolLabel = new JLabel("Enter the pool's volume: ");
final JTextField poolField = new JTextField(10);
pricePanel.add(poolLabel);
pricePanel.add(poolField);
final JTextField tubField = new JTextField(10);
final JLabel tubLabel = new JLabel ("Enter the tub's volume: ");
pricePanel.add(tubLabel);
pricePanel.add(tubField);
JButton calculatePrice = new JButton("Calculate Price");
calculatePrice.setMnemonic('C');
pricePanel.add(calculatePrice);
pricePanel.add(createExitButton());
pricePanel.add(new JLabel("The price is: "));
final JTextField priceField = new JTextField(10);
priceField.setEditable(false);
pricePanel.add(priceField);
final JTextArea messageArea = createMessageArea(1, 25,
"*Please only select one section");
pricePanel.add(messageArea);
calculatePrice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double pool = Double.parseDouble (poolField.getText());
double tub = Double.parseDouble(tubField.getText());
double price;
if (poolPrice.isSelected()) {
price = pool * 100;
} else {
price = tub * 75;
}
priceField.setText(df.format(price));
}
});
ActionListener priceListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == poolPrice) {
tubLabel.setEnabled(false);
tubField.setEnabled(false);
messageArea.setVisible(false);
} else if (e.getSource() == tubPrice) {
poolLabel.setEnabled(false);
poolField.setEnabled(false);
messageArea.setVisible(false);
}
}
};
poolPrice.addActionListener(priceListener);
tubPrice.addActionListener(priceListener);
}
ActionListener priceListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == poolPrice) {
tubLabel.setEnabled(false);
tubField.setEnabled(false);
// Re-enable the previously disabled labels
poolLabel.setEnabled(true);
poolField.setEnabled(true);
messageArea.setVisible(false);
} else if (e.getSource() == tubPrice) {
poolLabel.setEnabled(false);
poolField.setEnabled(false);
// Re-enable disabled labels
tubLabel.setEnabled(true);
tubField.setEnabled(true);
messageArea.setVisible(false);
}
}
};
You need to re-enable the buttons you disabled.