Adding a new button after an event - java

Writing a program to increment a counter when a +1 button is pressed, then when the counter reaches a certain number, remove the +1 button and replace it with a +2 button and so on. I create both buttons at first but just set btnCount1 to setVisible(false). When the certain number passes, I make btnCount invisible and btnCount1 visible and increment by two from there. When it reaches 10 clicks, the btnCount disappears, but btnCount1 does not appear.
I have tried making an if(arg0.equals(btnCount1)), and incrementing by two from there. I tried putting the add(btnCount1) inside the else if statement to create it after the elseif condition is true.
public class AWTCounter extends Frame implements ActionListener
private Label lblCount;
private TextField tfCount;
private Button btnCount;
private Button btnCount1;
private int count = 0;
public AWTCounter() {
setLayout(new FlowLayout());
lblCount = new Label("Counter");
add(lblCount);
tfCount = new TextField(count + "",10);
tfCount.setEditable(false);
add(tfCount);
btnCount = new Button("Add 1");
btnCount1 = new Button("Add 2");
add(btnCount);
add(btnCount1);
btnCount1.setVisible(false);
btnCount.addActionListener(this);
btnCount1.addActionListener(this);
setTitle("AWT Counter");
setSize(500,500);
}
public static void main(String[]args) {
AWTCounter app = new AWTCounter();
}
public void actionPerformed(ActionEvent arg0) {
if(count <= 10) {
++count; //Increase the counter value
tfCount.setText(count + "");
}else if(count > 10) {
btnCount.setVisible(false);
btnCount1.setVisible(true);
count += 2;
tfCount.setText(count + "");
}
}

The better solution here is to just have one button object and a separate variable for the current increment amount. When you hit the required count, increase the increment amount and change the button's label to the new value.
There are also a few other things you could do better here.
Use String.valueOf() instead of int + "" for String representations of integers if you're not adding words before or after the integer.
Don't add obvious comments for code. (e.g. 'increment variable x', 'set textString to the new value')
Use descriptive names for method parameters and variables.
Use Labels instead of TextFields for text that doesn't need to be editable or selectable like counter displays.
I'd personally change the name of lblCount to something like lblTitle as well, since changing your tfCount to a Label would logically take up that name and lblTitle makes more sense.
Here's a better way to implement actionPerformed:
private int increment = 1;
private Label lblCount;
...
public void actionPerformed(ActionEvent ignore) {
if(count == 10) {
btnCount.setLabel("Add " + (++increment));
}
lblCount.setText(String.valueOf(count += increment));
}

Related

Clear button only makes counter JLabel blank but does not reset it.

I have made this application:
For example when I click on the clear button when the counter JLabel (pointsAvailable) is 19 then the counter JLabel goes blank as expected, however when I start adding points again it starts from 19 not 40 as set on the start. I would like to make it to reset back to 40 instead of just making it blank
Code for the clear button
private void JButtonActionPerformed(java.awt.event.ActionEvent evt) {
speedPoints.setText("");
attackPoints.setText("");
defencePoints.setText("");
powerPoints.setText("");
agilityPoints.setText("");
focusPoints.setText("");
availablePoints.setText("");
}
Code for Jlabel counter
public class addingPointsUI extends javax.swing.JFrame {
int pointsAvailable=40;
int speed=0;
int power=0;
int focus=0;
int agility=0;
int defence=0;
int attack=0;
Code for buttons +/-: to allow me to add or decrease value "example power - button"
private void powerMinusActionPerformed(java.awt.event.ActionEvent evt) {
if (power > 0 ){
if (pointsAvailable <= 0) {
JOptionPane.showMessageDialog(null, "You are out of available points");
return;
}
power = power - 1;
pointsAvailable = pointsAvailable +1;
availablePoints.setText(String.valueOf(pointsAvailable));
powerPoints.setText(String.valueOf(power));
}else {
JOptionPane.showMessageDialog(null,"You cannot take anymore points from Power");
}
}
Thank your for your kind replies.
Use a JSpinner with SpinnerNumberModel. Change the value of the model. The component will update and further changes will act on the current value of the model.
I can quickly think of two solutions:
1. In the event handler of your clear button include the following:
private void JButtonActionPerformed(ActionEvent evt){
...
pointsAvailable=40;
speed=0;
power=0;
focus=0;
agility=0;
defence=0;
attack=0;
}
This will reset all of your stats.
2. Or you can add an if statement to the listeners of every button that adds or subtracts a stat that will check if the specific statistic is empty. For example, for the speed buttons the code would look like so:
if (speedPoints.getText() == ""){
pointsAvailable += speed;
speed = 0;
}
Found my own solution on google:
private void ClearActionPerformed(java.awt.event.ActionEvent evt) {
speedPoints.setText(String.valueOf(0));
powerPoints.setText(String.valueOf(0));
agilityPoints.setText(String.valueOf(0));
defencePoints.setText(String.valueOf(0));
focusPoints.setText(String.valueOf(0));
attackPoints.setText(String.valueOf(0));
availablePoints.setText(String.valueOf(40));
}
Works perfectly

Java determining if which JRadioButton was selected

I know that it is possible in an event driven program in Java to find out what object caused an event (e.g. JRadioButton was selected, therefore a certain action will take place). My question is, if you have 2 JRadioButtons in a buttongroup, both with action listeners added to them, and you keep selecting from one to the other, is it possible to find out what JRadioButton was previously selected? In other words, if I selected another JRadioButton, is it possible to write code that determines which JRadioButton was previously selected before selecting the current JRadioButton?
public class Drinks extends JPanel implements ActionListener{
double drinksPrice = 2.10;
double noDrinks = 0;
static String selectedDrink;
JRadioButton btnPepsi = new JRadioButton("Pepsi"); //add a button to choose different drinks
JRadioButton btnMtDew = new JRadioButton("Mt Dew");
JRadioButton btnDietPepsi= new JRadioButton("Diet Pepsi");
JRadioButton btnCoffee = new JRadioButton("Coffee");
JRadioButton btnTea = new JRadioButton("Tea");
JRadioButton btnNone = new JRadioButton("None");
JLabel lblDrinksHeading = new JLabel("Choose a drink (each drink is $2.10):");
ButtonGroup drinksButtonGroup = new ButtonGroup();
private static final long serialVersionUID = 1L;
public Drinks(){
setLayout(new FlowLayout()); //Using GridLayout
btnPepsi.setActionCommand(btnPepsi.getText()); //set the ActionCommand to getText so I can retrieve the name for the receipt
btnMtDew.setActionCommand(btnMtDew.getText());
btnDietPepsi.setActionCommand(btnDietPepsi.getText());
btnCoffee.setActionCommand(btnCoffee.getText());
btnTea.setActionCommand(btnTea.getText());
btnNone.setActionCommand(btnNone.getText());
drinksButtonGroup.add(btnPepsi);
drinksButtonGroup.add(btnMtDew);
drinksButtonGroup.add(btnDietPepsi);
drinksButtonGroup.add(btnCoffee);
drinksButtonGroup.add(btnTea);
drinksButtonGroup.add(btnNone);
btnNone.setSelected(true); //set default to "none"
btnPepsi.addActionListener(this);
btnMtDew.addActionListener(this);
btnDietPepsi.addActionListener(this);
btnCoffee.addActionListener(this);
btnTea.addActionListener(this);
btnNone.addActionListener(this);
add(lblDrinksHeading);
add(btnPepsi);
add(btnDietPepsi);
add(btnMtDew);
add(btnCoffee);
add(btnTea);
add(btnNone);
repaint();
revalidate();
selectedDrink = drinksButtonGroup.getSelection().getActionCommand();
//add the drink price to totalPrice, it is adding it every time though, even if its none
/*if(drinksButtonGroup.getSelection() == btnNone){
MenuFrame.totalPrice += 0;
}
else{
MenuFrame.totalPrice += drinksPrice;
}
*/
// buttonGroup1.getSelection().getActionCommand()
//String selectedDrink = drinksButtonGroup.getSelection().toString();
//class
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == btnNone) {
MenuFrame.totalPrice += 0;
TaxAndGratuityFrame.subtotalTextField.setText("$" + MenuFrame.totalPrice);
TaxAndGratuityFrame.subtotalVariable = MenuFrame.totalPrice;
TaxAndGratuityFrame.taxVariable = TaxAndGratuityFrame.subtotalVariable * TaxAndGratuityFrame.TAX_RATE;
TaxAndGratuityFrame.taxTextField.setText("$" + TaxAndGratuityFrame.taxVariable);
Receipt.receiptTotal.setText("Total: $" + (MenuFrame.totalPrice));
Receipt.receiptsubtotal.setText("Subtotal: " + (TaxAndGratuityFrame.subtotalVariable));
}
else {
MenuFrame.totalPrice += drinksPrice;
TaxAndGratuityFrame.subtotalTextField.setText("$" + MenuFrame.totalPrice);
TaxAndGratuityFrame.subtotalVariable = MenuFrame.totalPrice;
TaxAndGratuityFrame.taxVariable = TaxAndGratuityFrame.subtotalVariable * TaxAndGratuityFrame.TAX_RATE;
TaxAndGratuityFrame.taxTextField.setText("$" + TaxAndGratuityFrame.taxVariable);
Receipt.receiptTotal.setText("Total: $" + (MenuFrame.totalPrice));
Receipt.receiptsubtotal.setText("Subtotal: " + (TaxAndGratuityFrame.subtotalVariable));
}
}
Edit: I'll be more specific. I am creating an "imaginary" restaurant program. In it, I list several drinks that have the same price (e.g. Pepsi: $2.10, Mountain Due: $2.10, etc). These listed drinks are JRadioButtons. Once a customer clicks one of these buttons to "order a drink", $2.10 will be added to a "total" variable. However, a problem occurs when a user wants to change there drink, because if they click a different JRadioButton, $2.10 will still be added to the "total" variable. I want to make it so that they can change there drink without adding $2.10 to the order every time.
I think the problem is at this line:
MenuFrame.totalPrice += drinksPrice;
Because "+=" increments a value by another value instead of simply adding two values.
So every time the user clicks on one of the radio buttons, it will continuously add 2.10 to your total value, whereas if you were you just say:
MenuFrame.totalPrice = MenuFrame.totalPrice + drinksPrice;
It will set your total price equal to the current total price plus the price of drinks, instead of adding 2.10 to the total value every time a button is pressed.
Perhaps I am misunderstanding the question, but I am thinking along the lines of creating a public variable, and then inside the action listeners updating the variable with the radio button that was just selected. When the selected event fires, you can look at the variable to see which radio button had last been selected, do what you want to about it, and then update it with the new radio button.

Guess Number Game GUI - Infinite Loop

I'm making a guess the number program and I'm having trouble with my loop. When I run the program and input a number into the textfield and hit enter it freezes. I figured out that this might be happening because of an infinite loop. Feel free to correct me if I'm wrong. Basically when I enter a number into the textfield and press enter it suppose to change a label and change background color but this doesn't happen and I think its because my loop runs until win becomes true and when I type in my number it keeps running that number instead of outputting the correct label and letting me input a different number into the textfield. P.S: I know the newGame button does not work yet
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GuessingGame implements ActionListener
{
JFrame guessFrame;
JPanel guessPanel;
JTextField guessText;
JButton newGame;
JLabel rangeLbl, enterGuessLbl, winLbl;
Random rand = new Random();
int numToGuess = rand.nextInt(1000)+1;
int numOfTries = 0;
int guess;
public GuessingGame()
{
// Create the frame and container.
guessFrame = new JFrame("Guess the Number");
guessPanel = new JPanel();
guessPanel.setLayout(new GridLayout(5,0));
// Add the widgets.
addWidgets();
// Add the panel to the frame.
guessFrame.getContentPane().add(guessPanel, BorderLayout.CENTER);
// Exit when the window is closed.
guessFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Show the converter.
guessFrame.pack();
guessFrame.setVisible(true);
}
// Create and add the widgets for converter.
private void addWidgets()
{
// Create widgets.
guessText = new JTextField();
guessText.setHorizontalAlignment(JTextField.CENTER);
rangeLbl = new JLabel("I have a number between 1 and 1000. Can you guess my number?", SwingConstants.LEFT);
enterGuessLbl = new JLabel("Please enter your guess", SwingConstants.LEFT);
winLbl = new JLabel(" ", SwingConstants.CENTER);
newGame = new JButton("New Game");
// Listen to events from Convert textfield.
guessText.addActionListener(this);
// Add widgets to container.
guessPanel.add(rangeLbl);
guessPanel.add(enterGuessLbl);
guessPanel.add(guessText);
guessPanel.add(winLbl);
guessPanel.add(newGame);
}
// Implementation of ActionListener interface.
public void actionPerformed(ActionEvent event)
{
boolean win = false;
guess = Integer.parseInt(guessText.getText());
if ( guess == numToGuess)
{
win = true;
}
else if ( guess < numToGuess)
{
winLbl.setText("Too Low");
guessPanel.setBackground(Color.red);
guess = Integer.parseInt(guessText.getText());
}
else if ( guess > numToGuess)
{
winLbl.setText("Too High");
guessPanel.setBackground(Color.blue);
guess = Integer.parseInt(guessText.getText());
}
winLbl.setText("Correct!");
guessPanel.setBackground(Color.green);
}
public static void main(String[] args)
{
GuessingGame game = new GuessingGame();
}
}
Your while-loop is inappropriate here, because you are in a actionPerformed() Method. This method is most likely to be called on a gui action (e.g. button kicked).
It should do one action corresponding to your needs and then terminate, since this method is invoked within the EDT. Your gui will not perform any updates until this method is finished.
Thus nothing will change (e.g. your win status) until the user makes some additional action, which he can't because your gui is frozen.
You don't update the value of guess. You'll need to read guess at the end of your loop, or at least in those cases that guess and numToGuess don't have the same value.
In the current case: if the values are not equal the first iteration, it will never become.
add
guess = Integer.parseInt(guessText.getText());
as last statement to each else if block
EDIT: a better way, as Marcinek points out, would be to remove the while loop, but since I don't know your requirements, I won't go as far as to claim it's the correct sollution.
Your loop keep runing because this condition if ( guess == numToGuess) never verfied
boolean win = false;
while (win == false){
if ( guess == numToGuess){
win = true;
}
.......
}
and
win still false, and while loop go a head runing.
while (win == false)
{
.....}

JTextField - Moving cursor using a button

I'm really struggling to find the functionality (if it even exists),
to move a JTextFields cursor by clicking a Button, instead of using the mouse.
For instance, I have my text field with a string added.
By clicking a back button, the cursor will move back through the string, 1 position at a time or forward depending on which button is pressed.
I can do it with the mouse, just click and type, but I actually need to have it button based so that the user can choose to use the keypad to enter a name or just click into the JTextArea and type away.
Is it possible? What methods should I look for if so.
Thank you.
These are sample buttons that are doing what you're asking for:
btnMoveLeft = new JButton("-");
btnMoveLeft.setFocusable(false);
btnMoveLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txtAbc.setCaretPosition(txtAbc.getCaretPosition() - 1); // move the carot one position to the left
}
});
// omitted jpanel stuff
btnmoveRight = new JButton("+");
btnmoveRight.setFocusable(false);
btnmoveRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtAbc.setCaretPosition(txtAbc.getCaretPosition() + 1); // move the carot one position to the right
}
});
// omitted jpanel stuff
They are moving the carot in the textfield txtAbc with 1 position per click. Notice, that you need to disable the focusable flag for both buttons, or the focus of your textfield will be gone if you click one of these buttons and you can't see the carot anymore.
To avoid exceptions if you're trying to move the carot out of the textfield boundaries (-1 or larger than the text length), you should check the new values (for example in dedicated methods):
private void moveLeft(int amount) {
int newPosition = txtAbc.getCaretPosition() - amount;
txtAbc.setCaretPosition(newPosition < 0 ? 0 : newPosition);
}
private void moveRight(int amount) {
int newPosition = txtAbc.getCaretPosition() + amount;
txtAbc.setCaretPosition(newPosition > txtAbc.getText().length() ? txtAbc.getText().length() : newPosition);
}

JCombobox and JTextfield

I'm trying to work to display a number of jtextfield according to one of the given values in a combobox.
So, I will have a drop down menu with let's say 1 to 4. If the user selects number 3, 3 textfields will be displayed. I've created the jcombobox with a selection of numbers. But I'm not sure how to implement this. If I'm not mistaken I need to use
ItemEvent.SELECTED
I think I need to create a reference to the JTextField object that will be available to the JComboBox's itemListener object.
Any help would be greatly appreciated.
I've added this to my class :
// aOption is the combobox I declared
aOptionComboBox.setModel(new DefaultComboBoxModel(new String[]{"1","2","3"}));
public void itemStateChanged(ItemEvent event) {
String num = (String)aOptionComboBox.getSelectedItem();
int num1 = Integer.parseInt(num);
JTextField[] textfields = new JTextField[num1];
for (int i = 0; i < num1; i++)
{
textfields[i] = new JTextField("Field");
getContentPane().add(textfields[i]);
textfields[i].setBounds(200, 90, 100, 25);
}
}
am I on a right track?
use the getSelectedItem() on the combobox. This will either yield a string or an integer (depending on how you implemented it). Next use a for-loop to determine the amount of JTextField's and store them in an array.
int amount = myJComboBox.getSelectedItem();
JTextField[] textfields = new JTextField[amount];
for (int i = 0; i < amount; i++) {
textfields[i] = new JTextField("awesome");
this.add(textfields[i]);
}
this way you can easily store the textfields and add them to your panel.
Some added information.
The textfield-array must be accesible outside the eventListener, so you must implement it in your class. that way the whole class can use it.

Categories