Enter button error in java swing - java

I'm doing a programming exercise.
Miles and kilometer converter.(both case)
However, If I input number and press "Enter", nothing happened.
I don't know what part I need to modify... :(
Help me please..
public class Grid1 extends JFrame{
private JLabel label1,label2;
private JTextField textField1,textField2;
private Container container;
private GridLayout grid1;
// set up GUI
public Grid1(){
super( "Miles to Km / Km to Mile" );
grid1 = new GridLayout( 2, 2 );
container = getContentPane();
container.setLayout( grid1 );
label1 = new JLabel("Mile");
container.add(label1);
textField1 = new JTextField("");
container.add( textField1 );
label2 = new JLabel("Kilometer");
container.add(label2);
textField2 = new JTextField( "" );
container.add( textField2 );
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener(handler);
JButton submit = new JButton("Submit");
submit.addActionListener(handler);
setSize(300, 100);
setVisible(true);
}
private class TextFieldHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
float miles = 0, km = 0;
String string = "";
if(event.getSource() == textField1){
string = "textField1: " + event.getActionCommand();
km = miles * 1.609344f;
}else if(event.getSource() == textField2){
string = "textField2: " + event.getActionCommand();
miles = km / 1.609344f;
}
}
}
public static void main( String args[]){
Grid1 application = new Grid1();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} // end class GridLayoutDemo

You should remove handler from variable textField1 if you need to update data from button click. And in handler class you shold store data into result field/label.
In your case it looks like:
private class TextFieldHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
// In both cases you should get value from textField,
// parse it and store computed values in another field
float miles = 0, km = 0;
try {
if(event.getSource() == textField1){
// Value form field stored in String, you should parse Integer from it
miles = Integer.parseInt(textField1.getText());
km = miles * 1.609344f;
textField2.setText(String.format("%f", km));
}else if(event.getSource() == textField2){
// Value form field stored in String, you should parse Integer from it
km = Integer.parseInt(textField2.getText());
miles = km / 1.609344f;
textField1.setText(String.format("%f", km));
}
} catch(NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Wrong value", "Input error");
}
}
}

Since you are working with a single frame and a single button, I would suggest to set the following line:
frame.getRootPane().setDefaultButton(submitButton);
You can set a default button on each frame you control, the button you set in this method, will automatically listen to enter and invoke your actionPerformed.
You can also use a KeyListener and extend the functionality for your button in this case or in future exercises or projects.
Hope it helps.
All the best... and happy coding :)

Related

How can I set up a JFrame button to open another JFrame, and then receive information once the second jframe is closed?

This is part of a project for school, and I'm stuck and need someone to bounce ideas off of. I have a game where there is an option to sign up or sign in for a machine-local game so a record can be kept of the person's scores. The game is run from a base GUI JFrame, and I want to make buttons to bring up secondary windows for the person to sign in or sign up, before closing out of them. I need to pass the validated username back to the initial GUI/game class so I can store it for the following game so the game score can be added under that user. I just need to pass the username back and I'm not sure how to go about it. This is the main GUI code up to where I'm having my issue:
public class MathFactsGUI extends JFrame
{
// instance variables
private JTextField problemJTextField, answerJTextField;
private JLabel equalJLabel;
private JButton additionJButton, multiplicationJButton;
private JButton signupJButton, signinJButton;
private JButton submitJButton;
private JLabel scoreJLabel,resultJLabel;
//private JButton reviewButton;
private String username;
private Userbase userbase;
private JLabel introJLabel;
Quiz quiz;
/**
* Constructor for objects of class MathFactsGUI
*/
public MathFactsGUI()
{
super("Math Facts Quiz");
userbase = Userbase.getUserbase();
username = "guest";
/* code here has been removed to be abbreviated */
// Action listener for buttons
additionJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('+');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}
});
multiplicationJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('x');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}
});
signinJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JDialo
}
});
signupJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
MathFactsSignUpGUI signUpGUI = new MathFactsSignUpGUI();
gui.setVisible(true);
}
});
}
This is the JFrame I wrote for the sign-up button:
public class MathFactsSignUpGUI extends JDialog {
private JTextField usernameJTextField, userPassJTextField, userFirstNameJTextField;
private JLabel usernameJLabel, userPassJLabel, userFirstNameJLabel;
private JButton submitJButton;
private String username;
private String userPass;
private String userFirstName;
public MathFactsSignUpGUI(){
usernameJLabel = new JLabel("Username:");
usernameJTextField = new JTextField();
userPassJLabel = new JLabel("Password:");
userPassJTextField = new JTextField();
userFirstNameJLabel = new JLabel("Player First Name:");
userFirstNameJTextField = new JTextField();
Box usernameBox = Box.createHorizontalBox();
usernameBox.add(usernameJLabel);
usernameBox.add(usernameJTextField);
Box userPassBox = Box.createHorizontalBox();
userPassBox.add(userPassJLabel);
userPassBox.add(userPassJTextField);
Box userFirstBox = Box.createHorizontalBox();
userFirstBox.add(userFirstNameJLabel);
userFirstBox.add(userFirstNameJTextField);
submitJButton = new JButton("Submit");
submitJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
username = usernameJTextField.getText();
userPass = userPassJTextField.getText();
userFirstName = userFirstNameJTextField.getText();
if (!checkValid(username) || !checkValid(userPass) || !checkValid(userFirstName)){
JOptionPane.showMessageDialog(null, "All fields must have values.");
} else if (Userbase.getUserbase().userExist(username)==true){
JOptionPane.showMessageDialog(null, "Username is taken, please choose another.");
} else {
Userbase.getUserbase().addUser(username, new User(username, userPass, userFirstName));
MathFactsGUI.setUsername(username);
}
}
});
JPanel mfSignUp = new JPanel()
mfSignUp.setLayout(new GridLayout(0,1));
mfSignUp.add(usernameBox);
mfSignUp.add(userPassBox);
mfSignUp.add(userFirstBox);
mfSignUp.add(submitJButton);
}
public String signIn(){
return username;
}
public boolean checkValid(String a){
if (a == null || a.length() == 0){
return false;
} else {
return true;
}
}
}```
I was thinking of implementing a WindowListener action for when the sign-up/sign-in frames close, but I'm not sure that will work. I was also looking into JDialog, but I'm not sure if it has the layout/text verification properties I need.
Use a JOptionPane. It will simplify your layout without the need for creating a separate JFrame and easily pass values back to wherever it was called from. You can then make it check for valid username when you click OK.
Try this site. It gives a good rundown with example images
First you need to understand that this is an object, so you can create some global variables which will contains this information(username,password,Nickname), i recommend to pull info from MathFactsSignUpGUI by using ScheduledExecutorService. It will pull info from this sign up gui in every 100ms, than it will destroy itself, here is an example:
MathFactsSignUpGUI su = new MathFactsSignUpGUI ();
su.setVisible(true);
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable(){
public void run(){
if(!su.username.isEmpty() && !su.userPass.isEmpty() && !su.userFirstName.isEmpty() ){
if(su.isLogin){ //if player is loggining
//do something here
}else{//if user is registered
//do something here
}
System.out.println("Check complete");
service.shutdown();//to destroy this service after recieving the data
}
}
}, 100, TimeUnit.MICROSECONDS);

How to add text and delete text using GUI in Java

I am creating a dumb phone (like old traditional phone) and I'm using GUI programming. I need help with dialing the numbers. I don't know how to get the numbers to pop up on the display and stay there, and also use the delete button to delete the numbers that is up on the display too. I will post a youtube link so you can see a sample run.
I am currently stuck on passing the text from the button of each number that should display the number, however it's displaying the text of the button. I also, don't know how to keep the number there when other buttons are pressed without it being reset.
Here is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.*;
public class DumbPhone extends JFrame
{
private static final long serialVersionUID = 1L;
private static final int WIDTH = 300;
private static final int HEIGHT = 500;
private static final String CALL_BUTTON_TEXT = "Call";
private static final String TEXT_BUTTON_TEXT = "Text";
private static final String DELETE_BUTTON_TEXT = "Delete";
private static final String CANCEL_BUTTON_TEXT = "Cancel";
private static final String SEND_BUTTON_TEXT = "Send";
private static final String END_BUTTON_TEXT = "End";
private static final String CALLING_DISPLAY_TEXT = "Calling...";
private static final String TEXT_DISPLAY_TEXT = "Enter text...";
private static final String ENTER_NUMBER_TEXT = "Enter a number...";
private JTextArea display;
private JButton topMiddleButton;
private JButton topLeftButton;
private JButton topRightButton;
private JButton[] numberButtons;
private JButton starButton;
private JButton poundButton;
private boolean isNumberMode = true;
private String lastPressed = "";
private int lastCharacterIndex = 0;
private Date lastPressTime;
public DumbPhone()
{
setTitle("Dumb Phone");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
topLeftButton.setEnabled(false);
}
private void createContents()
{
//create JPanel, and JTextArea display
JPanel panel = new JPanel(new GridLayout(5,3));
display = new JTextArea();
display.setPreferredSize(new Dimension(280, 80));
display.setFont(new Font("Helvetica", Font.PLAIN, 32));
display.setLineWrap(true);
display.setEnabled(false);
panel.add(display);
//create JButtons
topLeftButton = new JButton(DELETE_BUTTON_TEXT);
topMiddleButton = new JButton((CALL_BUTTON_TEXT));
topRightButton = new JButton((TEXT_BUTTON_TEXT));
numberButtons = new JButton[10];
numberButtons[1] = new JButton("<html><center>1<br></center></html>");
numberButtons[2] = new JButton("<html><center>2<br>ABC</center></html>");
numberButtons[3] = new JButton("<html><right>3<br>DEF</right></html>");
numberButtons[4] = new JButton("<html><center>4<br>GHI</center></html>");
numberButtons[5] = new JButton("<html><center>5<br>JKL</center></html>");
numberButtons[6] = new JButton("<html><center>6<br>MNO</center></html>");
numberButtons[7] = new JButton("<html><center>7<br>PQRS</center></html>");
numberButtons[8] = new JButton("<html><center>8<br>TUV</center></html>");
numberButtons[9] = new JButton("<html><center>9<br>WXYZ</center></html>");
numberButtons[0] = new JButton("<html><center>0<br>space</center></html>");
poundButton = new JButton("#");
starButton = new JButton("*");
//add JButtons to buttons JPanel
panel.add(topLeftButton);
panel.add(topMiddleButton);
panel.add(topRightButton);
panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(numberButtons[4]);
panel.add(numberButtons[5]);
panel.add(numberButtons[6]);
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
panel.add(numberButtons[9]);
panel.add(starButton);
panel.add(numberButtons[0]);
panel.add(poundButton);
//add Listener instance (inner class) to buttons
topLeftButton.addActionListener(new Listener());
topMiddleButton.addActionListener(new Listener());
topRightButton.addActionListener(new Listener());
//JButton[] array = new JButton[10];
for (int i = 0; i < numberButtons.length; i++)
{
numberButtons[i].addActionListener(new Listener());
numberButtons[i] = new JButton(String.valueOf(i));
}
starButton.addActionListener(new Listener());
poundButton.addActionListener(new Listener());
//add display and buttons to JFrame
setLayout(new BorderLayout());
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == topLeftButton)
{
if(lastPressTime == null)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
topLeftButton.setEnabled(true);
lastCharacterIndex--;
lastPressed = lastPressTime.toString();
}
}
else if(e.getSource() == topMiddleButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else if(e.getSource() == topRightButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(TEXT_DISPLAY_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
//String text = ((JButton) e.getSource()).getText();
display.setText(lastPressed + " f" + numberButtons[lastCharacterIndex].getText());
}
}
Date currentPress = new Date();
long currentTime = currentPress.getTime();
if(lastPressTime != null)
{
//long lastPressTime = lastPressTime.getTime();
//subtract lastPressTime from currentPress time to find amount of time elapsed since last button pressed.
}
lastPressTime = currentPress;
String buttonLetters = ""; // Parse Letter from button (e.g "abc").
//update lastCharacterIndex.
lastCharacterIndex++;
lastCharacterIndex = lastCharacterIndex % buttonLetters.length();
}
}
for example, if I push the button 2, instead of giving me "2", it will give me < html>< center>2ABC < / center >< / html >
Therefore, I need help with
Having the numberButtons, when pushed to show the numbers that were pushed.
Be able to delete those numbers.
Here is the link to the sample run: https://www.youtube.com/watch?v=evmGWlMSqqg&feature=youtu.be
Try starting the video 20 seconds in.
to delete the number, you can use the labelname.setText("")
At a basic level, you simply want to maintain the "numbers" separately from the UI. This commonly known as a "model". The model lives independently of the UI and allows the model to be represented in any number of possible ways based on the needs of the application.
In your case, you could use a linked list, array or some other simple sequential based list, but the easiest is probably to use a StringBuilder, as it provides the functionality you require (append and remove) and can make a String very simply.
So, the first thing you need to do is create an instance of model as an instance level field;
private StringBuilder numbers = new StringBuilder(10);
this will allow the buffer to be accessed any where within the instance of the class.
Then you need to update the model...
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
String text = numberButtons[lastCharacterIndex].getText();
numbers.append(text);
}
}
To remove the last character you can simply use something like...
if (numbers.length() > 0) {
numbers.deleteCharAt(numbers.length() - 1);
}
Then, when you need to, you update the UI using something like...
display.setText(numbers.toString());
Now, this is just basic concepts, you will need to take the ideas and apply it to your code base

Determining the right answer in my quiz

So my current quiz generates panes and buttons which go in the panes, there is a array which holds all the answers and questions as you can see below
int total = 0;
int counter = 0;
JTabbedPane quiz = new JTabbedPane();
Problem[] probList = new Problem[6];
JLabel lblOutput;
JPanel finishQuiz = new JPanel();
JButton finish = new JButton("Finish Quiz");
public QuizEasy(){
problems();
CreateTabs();
setTitle("Easy Questions");
setSize(680,300);
getContentPane().add(quiz);
ButtonHandler phandler = new ButtonHandler();
finish.addActionListener(phandler);
setVisible(true);
}
public void CreateTabs() {
JPanel question = null;
JLabel lbQuestion = null;
JButton ansA = null;
JButton ansB = null;
JButton ansC = null;
for (int i=0;i<probList.length;i++) {
question = new JPanel();
lbQuestion = new JLabel(probList[i].getQuestion());
question.add(lbQuestion);
ansA = new JButton(probList[i].getAnsA());
ansB = new JButton(probList[i].getAnsB());
ansC = new JButton(probList[i].getAnsC());
lblOutput = new JLabel("Please click on your answer");
question.add(ansA);
question.add(ansB);
question.add(ansC);
question.add(lblOutput);
quiz.addTab("Question " + (i+1), question);
}
quiz.addTab("Finish Quiz", finishQuiz);
finishQuiz.add(finish);
}
public void problems(){
probList[0] = new Problem(
"What is the meaning of life?",
"Only god knows",
"42",
"huh?",
"B"
);
probList[1] = new Problem(
"What level woodcutting do you need to cut oaks in runescape",
"15",
"20",
"99",
"C"
);
probList[2] = new Problem(
"Who has recieved the highest amount of oscars?",
"Walt Disney",
"You",
"Leonardo Di Caprio",
"A"
);
probList[3] = new Problem(
"What is the most spoken native tounge in the world?",
"English",
"Kek",
"Mandarin",
"C"
);
probList[4] = new Problem(
"Deva was the Roman name for which British city?",
"Bristol",
"Chester",
"London",
"B"
);
probList[5] = new Problem(
"Which herb is one of the main ingredients of Pesto Sauce?",
"Basil",
"Chester",
"London",
"A"
);
}
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
showSummary();
}
}
public void showSummary(){
JOptionPane.showMessageDialog(null,"You have completed the quiz, here are your results" + counter
);
System.exit(0);
}
public static void main(String[] args) {
QuizEasy tab = new QuizEasy();
}
}
I'm not quite sure how to make the buttons correspond to the right answer, any advice? I've tried to mess around with counters and such but I didn't manage to get it working in the end. any help is appreciated!
You can assign a JButton to each position in the array.
JButton button1 = new JButton("Button 1");
Then you need an action listener which goes like this
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
// Go ahead and do what you like
}
}
});

How to change a Jbutton's function on clicking another Jbutton?

I am writing a program which will convert weight in pounds to kilograms and also weight in Kilograms to pounds. The output window is as follows:
When I want to convert Kilograms to Pounds I click switch button and the output changes as follows:
But the problem is when I click "Convert" it still converts weight to Kilogram instead of Pounds.
I want the "Convert" button's function to change when I click the "Switch" button so it will convert the weight in Kilograms to pounds. Please help.
My source code is as follows:
public class convertApp extends JFrame implements ActionListener {
private JLabel poundlbl = new JLabel("Weight in Pounds");
private JLabel kglbl = new JLabel("Weight in Kilograms");
private JTextField poundbx= new JTextField(12);
private JTextField kgbx= new JTextField(12);
private JButton conbtn=new JButton("Convert");
private JButton switchbtn=new JButton("Switch");
private JButton newconbtn=new JButton("Convert");
private JPanel bxPanel = new JPanel();
public convertApp(){
super("Weight Converter");
bxPanel.setLayout(new GridLayout(5,29,5,5));
bxPanel.add(poundlbl);
bxPanel.add(poundbx);
bxPanel.add(kglbl);
bxPanel.add(kgbx);
bxPanel.add(conbtn);
bxPanel.add(switchbtn);
//bxPanel.setBackground(Color.gray);
this.setLayout(new GridLayout(1,1,0,0));
this.add(bxPanel);
this.setVisible(true);
//what to do if i close
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//put window in the center
this.setLocationRelativeTo(null);
//disable resize
this.setResizable(false);
//pack all the components within the window
this.pack();
conbtn.addActionListener(this);
switchbtn.addActionListener(this);
}
public void actionPerformed(ActionEvent evnt){
if(evnt.getSource()==conbtn){
String poundtext = poundbx.getText();
int pound = Integer.parseInt(poundtext);
double kilo = pound * 0.453592;
kgbx.setText(""+kilo);
}
else if(evnt.getSource()==switchbtn)
{
poundlbl.setText("Weight in Kilograms:");
kglbl.setText("Weight in Pounds:");
if(evnt.getSource()==conbtn){
String kilotext = poundbx.getText();
int kilo = Integer.parseInt(kilotext);
double pound = kilo * 2.20462;
kgbx.setText(""+pound);
}
}
}
}
Create boolean Variable
boolean switch=true;
void kiloGramToPound{
//Convert Codes Here
}
void PoundToKiloGram{
//Convert Codes Here
}
Convert Button actionPerformed
if(switch==true){
kiloGramToPound();
}else{
PoundToKiloGram();
}
Switch Button actionPerformed
if(switch==true){
switch=false;
}else{
switch=true;
}
You cannot change the function itself. You can create a flag that sets true or false (your choice) when you click the 'switch' button. Then check the value of that flag when you click 'convert' and perform the appropriate conversion according to your flag convention.
i.e.
Boolean isPtoK = true;
// [...]
if(isPtoK){
// convert pounds to kilos
} else{
// kilos to pounds
}
I would create a separate function that switches the value of your flag when 'switch' is clicked.
Apologies for not answering your question, but may I suggest you to try KeyListener/KeyAdapter instead of the combination of ActionListeners and buttons.
Example:
textField1.addKeyListener(new ConverterListener(textField2, "2.20462"));
textField2.addKeyListener(new ConverterListener(textField1, "0.453592"));
class ConverterListener extends KeyAdapter {
JTextField destination;
String multiplier;
public ConverterListener(JTextField destination, String multiplier) {
this.destination = destination;
this.multiplier = multiplier;
}
#Override
public void keyReleased(KeyEvent e) {
JTextField source = (JTextField) e.getSource();
String result = convert(source.getText(), multiplier);
destination.setText(result);
}
private String convert(String value, String multiplier) {
String result = "0";
try {
double dblValue = value.isEmpty() ? 0d : Double.parseDouble(value);
double dblMultiplier = value.isEmpty() ? 0d : Double.parseDouble(multiplier);
result = Double.toString(dblValue * dblMultiplier);
} catch (Exception e) {
System.out.println(e);
}
return result;
}
}

Calculating the total price

How do you calculate the total price of of groceries purchased? At the moment, I can only calculate only one of the grocery with its quantity.
Below are the classes that I have used:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.text.DecimalFormat;
/**
Long Distance Calls
*/
public class GroceryMain extends JFrame
{
private RatePanel ratePanel; // A panel for rates
private QuantityPanel quantityPanel; // A panel for minutes
private JPanel buttonPanel; // A panel for the buttons
private JButton calcButton; // Calculates everything
private JButton exitButton; // Exits the application
/**
Constructor
*/
public GroceryMain()
{
// Display a title.
setTitle("Grocery Shop");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a RatePanel object.
ratePanel = new RatePanel();
// Create a MinutesPanel object.
quantityPanel = new QuantityPanel();
// Build the panel that contains the buttons.
buildButtonPanel();
// Add the panels to the content pane.
add(ratePanel, BorderLayout.WEST);
add(quantityPanel, BorderLayout.EAST);
add(buttonPanel, BorderLayout.SOUTH);
// Pack and display the window.
pack();
setVisible(true);
}
/**
The buildButtonPanel method creates a panel containing
buttons.
*/
private void buildButtonPanel()
{
// Create a button to calculate the charges.
calcButton = new JButton("Calculate Charges");
// Add an action listener to the button.
calcButton.addActionListener(new CalcButtonListener());
// Create a button to exit the application.
exitButton = new JButton("Exit");
// Add an action listener to the button.
exitButton.addActionListener(new ExitButtonListener());
// Put the buttons in their own panel.
buttonPanel = new JPanel();
buttonPanel.add(calcButton);
buttonPanel.add(exitButton);
}
/**
CalcButtonListener is an action listener class for the
calcButton component.
*/
private class CalcButtonListener implements ActionListener
{
/**
actionPerformed method
#param e An ActionEvent object.
*/
public void actionPerformed(ActionEvent e)
{
double rate; // Applicable rate
double totalCharges; // Total charges
// Create a DecimalFormat object to format output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Get the applicable rate.
rate = ratePanel.getRate();
// Get the total charges
totalCharges = quantityPanel.getCharges(rate);
// Display the message.
JOptionPane.showMessageDialog(null, "Total Charges: £" +
dollar.format(totalCharges));
}
} // End of inner class
/**
ExitButtonListener is an action listener class for the
exitButton component.
*/
private class ExitButtonListener implements ActionListener
{
/**
actionPerformed method
#param e An ActionEvent object.
*/
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
} // End of inner class
/**
The main method creates an instance of the LongDistance
class, causing it to display its window.
*/
public static void main(String[] args)
{
GroceryMain ld = new GroceryMain();
}
}
import java.awt.*;
import javax.swing.*;
/**
MinutesPanel class
Long Distance Calls
*/
public class QuantityPanel extends JPanel
{
private JTextField quantity; // To get minutes
private JTextField quantity2; // To get minutes
private JTextField baked_beans_JT; // JTextField box for baked_beans
private JTextField Cornflakes_JT; // JTextField box for cornflakes
private JTextField Sugar_JT; // JTextField box for sugar box
private JTextField Tea_Bags_JT; // JTextField box for tea bag
private JTextField Instant_Coffee_JT; // JTextField box for Instant_Coffee_Box
private JTextField Bread_JT; // JTextField box for bread box
private JTextField Sausage_JT; // JTextField box for sausage box
private JTextField egg_JT; // JTextField box for egg box
private JTextField milk_JT; // JTextField box for milk
private JTextField potatoes_JT; // JTextField box for potatoes
/**
Constructor
*/
public QuantityPanel()
{
// Create a label prompting the user and a text field.
//JLabel minutesMsg = new JLabel("Quantity:");
quantity = new JTextField(5);
quantity2 = new JTextField(5);
baked_beans_JT = new JTextField(5);
Cornflakes_JT = new JTextField(5);
Sugar_JT = new JTextField(5);
Tea_Bags_JT = new JTextField(5);
Instant_Coffee_JT = new JTextField(5);
Bread_JT = new JTextField(5);
Sausage_JT = new JTextField(5);
egg_JT = new JTextField(5);
milk_JT = new JTextField(5);
potatoes_JT = new JTextField(5);
//initialize text field to 0
baked_beans_JT.setText("0");
Cornflakes_JT.setText("0");
Sugar_JT.setText("0");
Tea_Bags_JT.setText("0");
Instant_Coffee_JT.setText("0");
Bread_JT.setText("0");
Sausage_JT.setText("0");
egg_JT.setText("0");
milk_JT.setText("0");
potatoes_JT.setText("0");
// Create a GridLayout manager.
setLayout(new GridLayout(15, 1));
// Create a border.
setBorder(BorderFactory.createTitledBorder("QTY"));
// Add the labels and text fields to this panel.
//add(minutesMsg);
//add(quantity);
// add(quantity2);
add(baked_beans_JT);
add(Cornflakes_JT);
add(Sugar_JT);
add(Tea_Bags_JT);
add(Instant_Coffee_JT);
add(Bread_JT);
add(Sausage_JT);
add(egg_JT);
add(milk_JT);
add(potatoes_JT);
}
/**
The getCharges method uses the specified rate to calculate
the charges for the number of minutes entered.
#param rate The per-minute rate.
#return The charges for the number of minutes used.
*/
public double getCharges(double rate)
{
double charges = Double.parseDouble(baked_beans_JT.getText()) * rate;
return charges;
}
}
import java.awt.*;
import javax.swing.*;
import java.text.DecimalFormat;
/**
RatePanel class
Long Distance Calls
*/
public class RatePanel extends JPanel
{
// Named constants for rates
private final double BAKED_BEANS= 0.35;
private final double CORNFLAKES = 1.75;
private final double SUGAR = 0.75;
private final double TEA_BAGS = 1.15;
private final double INSTANT_COFFEE = 2.50;
private final double BREAD = 1.25;
private final double SAUSAGES = 1.30;
private final double EGGS = 0.75;
private final double MILK = 0.65;
private final double POTATOES = 2.00;
private JCheckBox bakedbeans; // Radio button for daytime rate
private JCheckBox cornflakes; // Radio button for evening rate
private JCheckBox sugar; // Radio button for off peak rate
private JCheckBox teabags; // Radio button for off peak rate
private JCheckBox instantcoffee; // Radio button for off peak rate
private JCheckBox bread; // Radio button for off peak rate
private JCheckBox sausages; // Radio button for off peak rate
private JCheckBox eggs; // Radio button for off peak rate
private JCheckBox milk; // Radio button for off peak rate
private JCheckBox potatoes; // Radio button for off peak rate
//private ButtonGroup bg; // Radio button group
/**
Constructor
*/
public RatePanel()
{
// Create a DecimalFormat object.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Create the check boxes.
bakedbeans = new JCheckBox("Bakedbeans (£" +
dollar.format(BAKED_BEANS) + " per packet)");
cornflakes = new JCheckBox("Cornflakes (£" +
dollar.format(CORNFLAKES) + " per packet)");
sugar = new JCheckBox("Sugar (£" +
dollar.format(SUGAR) + " per packet)");
teabags = new JCheckBox("Teabags (£" +
dollar.format(TEA_BAGS) + " per item)");
instantcoffee = new JCheckBox("Instantcoffee (£" +
dollar.format(INSTANT_COFFEE) + " per packet)");
bread = new JCheckBox("Bread (£" +
dollar.format(BREAD) + " per packet)");
sausages = new JCheckBox("Sausages (£" +
dollar.format(SAUSAGES) + " per packet)");
eggs = new JCheckBox("Eggs (£" +
dollar.format(EGGS) + " per packet)");
milk = new JCheckBox("Milk (£" +
dollar.format(MILK) + " per packet)");
potatoes = new JCheckBox("Potatoes (£" +
dollar.format(POTATOES) + " per packet)");
// Create a GridLayout manager.
setLayout(new GridLayout(15, 12));
// Create a border.
setBorder(BorderFactory.createTitledBorder("Select a Category"));
// Add the check boxes to this panel.
add(bakedbeans);
add(cornflakes);
add(sugar);
add(teabags);
add(instantcoffee);
add(bread);
add(sausages);
add(eggs);
add(milk);
add(potatoes);
}
/**
The getRate method returns the rate for the selected
rate category.
#return One of the constants DAYTIME_RATE, EVENING_RATE, or
OFF_PEAK_RATE.
*/
public double getRate()
{
double rate = 0.0;
if (bakedbeans.isSelected())
rate += BAKED_BEANS;
if (cornflakes.isSelected())
rate = CORNFLAKES;
else if (sugar.isSelected())
rate += SUGAR;
else if (teabags.isSelected())
rate += TEA_BAGS;
else if (instantcoffee.isSelected())
rate += INSTANT_COFFEE;
else if (bread.isSelected())
rate += BREAD;
else if (sausages.isSelected())
rate += SAUSAGES;
else if (eggs.isSelected())
rate += EGGS;
else if (milk.isSelected())
rate += MILK;
else if (potatoes.isSelected())
rate += POTATOES;
return rate;
}
}
I want to be able to calculate the total price of groceries when the user select a multiple of check-boxes with its quantities..
Try if - if instead of if-else if.
if - else if condition is satisfied, the appropriate statements are executed and the remaining conditions are not evaluated.
if -if will evaluate each condition.
public double getRate()
{
double rate = 0.0;
if (bakedbeans.isSelected())
rate += BAKED_BEANS;
if (cornflakes.isSelected())
rate += CORNFLAKES;
if (sugar.isSelected())
rate += SUGAR;
if (teabags.isSelected())
rate += TEA_BAGS;
if (instantcoffee.isSelected())
rate += INSTANT_COFFEE;
if (bread.isSelected())
rate += BREAD;
if (sausages.isSelected())
rate += SAUSAGES;
if (eggs.isSelected())
rate += EGGS;
if (milk.isSelected())
rate += MILK;
if (potatoes.isSelected())
rate += POTATOES;
return rate;
}
As I understand it, getCharges is intended to return the total cost of the selected items. The current implementation is:
public double getCharges(double rate)
{
double charges = Double.parseDouble(baked_beans_JT.getText()) * rate;
return charges;
}
Unfortunately, you cannot use the number of baked beans selected to predict what else the customer is buying :)
There are several ways this could be fixed, and I'm afraid all of them will need modifications elsewhere in the code. I would recommend looking into the use of arrays. If you'd rather avoid that, you'll have to do something similar to this:
double charges = 0;
charges += Integer.parseInt(baked_beans_JT.getText()) * BAKED_BEANS;
charges += Integer.parseInt(cornflakes_JT.getText()) * CORNFLAKES;
...
Since the getRate method wouldn't be needed anymore, you could adapt that and save some copy-pasting.
But really, look into arrays or collections. Without them, you're in for a frustrating future.

Categories