Adding values using checkbox? - java

I am trying to create an enrollment system. I have 6 checkboxes, what I want to happen is if I check one of the checkbox and press the button compute, it should give the label a value of 2640. When I click on another checkbox and press the button compute again the value of the label is 5280 and so on if I click all of the 6 checkboxes.
IF ONE OF THE CHECKBOX IS NOT CLICKED AND I PRESS THE COMPUTE BUTTON, IT SHOULD SUBTRACT 2640 from the current total. Here is my code:
if (chkPLF.isSelected() == true) {
tFee = 2640;
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee + tFee));
if (chkPLF.isSelected() == false) {
tFee = tFee - 2640;
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee));
}
}
if (chkSAD.isSelected() == true) {
tFee = 2640 * 3;
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee));
if (chkSAD.isSelected() == false) {
tFee = tFee - 2640;
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee));
}
}
it only displays the current value but doesn't subtract. PLEASE HELP!

Why not just count the number of checkboxs that are clicked an multiple the result by 2640. Right now, you seem to be overriding the result with each check box...
For example...
int checkCount = 0;
if (chk1.isSelected()) {
checkCount++;
}
if (chk2.isSelected()) {
checkCount++;
}
if (chk3.isSelected()) {
checkCount++;
}
if (chk4.isSelected()) {
checkCount++;
}
if (chk5.isSelected()) {
checkCount++;
}
if (chk6.isSelected()) {
checkCount++;
}
tFee = 2640 * checkCount;
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee));
Right now, I'm going, this could be more easily done with a loop...
JCheckBox[] boxes = new JCheckBox[]{chk1, chk2, chk3, chk4, chk5, chk6};
tFee = 0;
for (JCheckBox box : boxes) {
if (box.isSelected()) {
tFee += 2640;
}
}
lblMis.setText(Double.toString(misFee));
lblT.setText(Double.toString(tFee));
But maybe that's because I'm crazy...

double amount = 0;
int sel = 0;
if(jCheckBox1.isSelected()) sel++;
if(jCheckBox2.isSelected()) sel++;
if(jCheckBox3.isSelected()) sel++;
if(jCheckBox4.isSelected()) sel++;
if(jCheckBox5.isSelected()) sel++;
if(jCheckBox6.isSelected()) sel++;
amount = 2640 * sel;
JOptionPane.showMessageDialog(rootPane, String.valueOf(amount));
Put this code in the "Compute" Click ActionListener

Related

Adding .wav and .png/.jpg files to a GUI

I have a created a simple tic tac toe GUI GAME. I want to extend it by changing what is displayed on the buttons from just text "X" and "O" to fancy graphic "X" and "O" (by providing jpg or png files) and also add sounds using .wav files.
This is my code for my game: (It works perfectly.. I just need help with the extensions.. Thanks)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TicTacToeGUI implements ActionListener
{
//Class constants
private static final int WINDOW_WIDTH = 300;
private static final int WINDOW_HEIGHT = 300;
private static final int TEXT_WIDTH = 30;
private static final String PLAYER_X = "X"; // player using "X"
private static final String PLAYER_O = "O"; // player using "O"
private static final String EMPTY = ""; // empty cell
private static final String TIE = "T"; // game ended in a tie
private String player; // current player (PLAYER_X or PLAYER_O)
private String winner; // winner: PLAYER_X, PLAYER_O, TIE, EMPTY = in progress
private int numFreeSquares; // number of squares still free
private JMenuItem resetItem; // reset board
private JMenuItem quitItem; // quit
private JLabel gameText; // current message
private JButton board[][]; // 3x3 array of JButtons
private JFrame window = new JFrame("TIC-TAC-TOE");
/**
* Constructs a new Tic-Tac-Toe GUI board
*/
public TicTacToeGUI()
{
setUpGUI(); // set up GUI
setFields(); // set up other fields
}
/**
* Set up the non-GUI fields
*
*/
private void setFields()
{
winner = EMPTY;
numFreeSquares = 9;
player = PLAYER_X;
}
/**
* reset the game so we can start again.
*
*/
private void resetGame()
{
// reset board
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
board[i][j].setText(EMPTY);
board[i][j].setEnabled(true);
}
}
gameText.setText("Game in Progress: X's turn");
// reset other fields
setFields();
}
/**
* Action Performed (from actionListener Interface).
* (This method is executed when a button is selected.)
*
* #param the action event
*/
public void actionPerformed(ActionEvent e)
{
// see if it's a menu item
if(e.getSource() instanceof JMenuItem)
{
JMenuItem select = (JMenuItem) e.getSource();
if (select==resetItem)
{
resetGame();// reset
return;
}
System.exit(0); // must be quit
}
// it must be a button
JButton chose = (JButton) e.getSource(); // set chose to the button clicked
chose.setText(player); // set its text to the player's mark
chose.setEnabled(false); // disable button (can't choose it now)
numFreeSquares--;
//see if game is over
if(haveWinner(chose))
{
winner = player; // must be the player who just went
}
else if(numFreeSquares==0)
{
winner = TIE; // board is full so it's a tie
}
// if have winner stop the game
if (winner!=EMPTY)
{
disableAll(); // disable all buttons
// print winner
String s = "Game over: ";
if (winner == PLAYER_X)
{
s += "X wins";
}
else if (winner == PLAYER_O)
{
s += "O wins";
}
else if (winner == TIE)
{
s += "Tied game";
}
gameText.setText(s);
}
else
{
// change to other player (game continues)
if (player==PLAYER_X)
{
player=PLAYER_O;
gameText.setText("Game in progress: O's turn");
}
else
{
player=PLAYER_X;
gameText.setText("Game in progress: X's turn");
}
}
}
/**
* Returns true if filling the given square gives us a winner, and false
* otherwise.
*
* #param Square just filled
*
* #return true if we have a winner, false otherwise
*/
private boolean haveWinner(JButton c)
{
// unless at least 5 squares have been filled, we don't need to go any further
// (the earliest we can have a winner is after player X's 3rd move).
if(numFreeSquares>4)
{
return false;
}
// find the square that was selected
int row=0, col=0;
outerloop: // a label to allow us to break out of both loops
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (c==board[i][j])
{
// object identity
row = i;
col = j; // row, col represent the chosen square
break outerloop; // break out of both loops
}
}
}
// check row "row"
if( board[row][0].getText().equals(board[row][1].getText()) && board[row][0].getText().equals(board[row][2].getText()) )
{
return true;
}
// check column "col"
if (board[0][col].getText().equals(board[1][col].getText()) &&board[0][col].getText().equals(board[2][col].getText()) )
{
return true;
}
// if row=col check one diagonal
if (row == col)
{
if( board[0][0].getText().equals(board[1][1].getText()) && board[0][0].getText().equals(board[2][2].getText()) )
{
return true;
}
}
// if row=2-col check other diagonal
if (row == 2-col)
{
if( board[0][2].getText().equals(board[1][1].getText()) && board[0][2].getText().equals(board[2][0].getText()) )
{
return true;
}
}
// no winner yet
return false;
}
/**
* Disables all buttons (game over)
*/
private void disableAll()
{
if (numFreeSquares==0)
{
return; // nothing to do
}
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
board[i][j].setEnabled(false);
}
}
}
/**
* Set up the GUI
*
*/
private void setUpGUI()
{
// for control keys
final int SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
window.setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set up the menu bar and menu
JMenuBar menubar = new JMenuBar();
window.setJMenuBar(menubar); // add menu bar to our frame
JMenu fileMenu = new JMenu("Game"); // create a menu called "Game"
menubar.add(fileMenu); // and add to our menu bar
resetItem = new JMenuItem("Reset"); // create a menu item called "Reset"
fileMenu.add(resetItem); // and add to our menu (can also use ctrl-R:)
resetItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, SHORTCUT_MASK));
resetItem.addActionListener(this);
quitItem = new JMenuItem("Quit"); // create a menu item called "Quit"
fileMenu.add(quitItem); // and add to our menu (can also use ctrl-Q:)
quitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
quitItem.addActionListener(this);
window.getContentPane().setLayout(new BorderLayout()); // default so not required
JPanel gamePanel = new JPanel();
gamePanel.setLayout(new GridLayout(3, 3));
window.getContentPane().add(gamePanel, BorderLayout.CENTER);
gameText = new JLabel("Game in Progress: X's turn");
window.getContentPane().add(gameText, BorderLayout.SOUTH);
// create JButtons, add to window, and action listener
board = new JButton[3][3];
Font font = new Font("Dialog", Font.BOLD, 24);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
board[i][j] = new JButton(EMPTY);
board[i][j].setFont(font);
gamePanel.add(board[i][j]);
board[i][j].addActionListener(this);
}
}
window.setVisible(true);
}
}
To assign an image to a JButton you can either use constructor or a method below:
JButton myButton = new JButton(new ImageIcon("D:\\icon.png"));
setIcon(new ImageIcon("D:\\icon.png"));
Of course provide your own file path.
To play some .wav sounds you can use this:
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class MusicPlayer {
private Clip clip;
public void play() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:\\sound.wav").getAbsoluteFile());
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
}
catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
}

Memory Game Action Listener Debugging

After much time spent trying to get my actionlistener to do what I want, Ive come to a few issues debugging that Im just not comprehending.
After finding a correct pair in the game, the first correct pair works properly, disables the two selected buttons, and moves on. After this the comparisons stop working. I can't seem to find out why. After setting up System.out.print checks to see if the programming was progressing through the clicks again it was, but its not allowing another comparison to happen or button reset from the else statement.
Below I've listed my main actionlistener and my pause action listener. Thank you, and if you need more data id be happy to update.
ActionListener timerPause = new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < jToggleLength; i++) {
jToggleButtons[i].setEnabled(true);
tempIconThree = ((ImageIcon)
jToggleButtons[i].getSelectedIcon()).getDescription();
//flip the selected buttons back over
if(jToggleButtons[i].isSelected()){
jToggleButtons[i].doClick();
}
}
}
};
/**
* sets the pause timer period to 1.5 seconds
* sets it to the actionListener Timerpause
*/
pause = new Timer(1500, timerPause);
public void actionPerformed(ActionEvent ae) {
//starts timer
//increments click on each action
pause.stop();
timer.start();
click++;
//if jtogglelength = 0 the user has completed the game and the timer stops
if (jToggleLength == 0) {
timer.stop();
click = 0;
}
//on first click the jtoggle button source is set to temp and the temp icon gets description
if (click == 1) {
temp = (JToggleButton) ae.getSource();
tempIcon = ((ImageIcon) temp.getSelectedIcon()).getDescription();
}
// on click two the jtoggle button source is set to tempTwo and the tempTwo icon gets description
if (click == 2) {
tempTwo = (JToggleButton) ae.getSource();
tempIconTwo = ((ImageIcon) tempTwo.getSelectedIcon()).getDescription();
//if the button is the same button set click to zero and do nothing else
if (temp == tempTwo) {
click = 0;
//if the temp icon descriptions are equivalent move forward
} else if (tempIcon.equals(tempIconTwo)) {
click = 0;
//this for loop sets tempIconThree in every loop to compare to my first two icon descriptions
//if they match, disable that button and set the button to null
//if the button is not null add it to an arraylist
for (int j = 0; j < jToggleLength; j++) {
tempIconThree = ((ImageIcon) jToggleButtons[j].getSelectedIcon()).getDescription();
if (tempIcon.equals(tempIconThree) || tempTwo.equals(tempIconThree)) {
jToggleButtons[j].setEnabled(false);
jToggleButtons[j] = null;
if (jToggleButtons[j] != null) {
arrayEdit.add(jToggleButtons[j]);
}
}
}
//reduce the length of the array by 2
//make a new version of the main jtogglebutton array with reduced length
//add the non null elements from the arrayList to the array
jToggleLength = -2;
for (int k = 0; k < jToggleLength; k++) {
jToggleButtons = new JToggleButton[jToggleLength];
jToggleButtons[k] = arrayEdit.get(k);
}
click = 0;
//if the icon descriptions did not match
//disable all buttons, pause for 1.5 seconds, flip the
selected buttons back up
} else {
for (int i = 0; i < jToggleLength; i++) {
jToggleButtons[i].setEnabled(false);
}
pause.start();
click = 0;
}
}

NumberFormatException and other problems while making a calculator in java

So I'm making a Java Calculator and walking into some errors upon clicking the function buttons (it compiles perfectly fine though).
The error on the 1st line in my CMD was a NumberFormat Exception. After some searching I figured out that somewhere in my code I was trying to get a double out of an empty string (basically what I'm trying to do is parse a double from the label text). I'm guessing it's this part:
// if statement that puts the labels text into the first or second number
if(firstNumber)
{
number1 = Double.parseDouble(label.getText().trim());
} else {
number2 = Double.parseDouble(label.getText().trim());
}
Basically the problems are when i push the / * + or - button i get a NumberFormatExeption: For input string "/" etc.
I can't quite figure out how i have to fix this error (I'm still (somewhat) a beginner in Java).
Further down the line of errors (there were quite alot) were a whole lot of errors I didn't understand such as EventDispatchThread, EventQueue and many others. I couldn't find an explanation on my level of experience either so I'm asking for help here.
The numeric buttons all work fine.
At run: [http://gyazo.com/71cb4dde449ccf7ece44017388a71a0f]
Putting in numbers: [http://gyazo.com/5c7ab6c54ac6da180845c66866d66f8f]
All other buttons give errors in my CMD.
Here's my code (the spacing might be messed up in some parts):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
// import for Nimbus look
import javax.swing.UIManager.*;
public class Calculator extends JFrame implements ActionListener
{
private JPanel bottom = new JPanel(); private JPanel top = new JPanel();
private JLabel label = new JLabel(" ");
private JButton[] buttons = new JButton[16];
// booleans for calculator functions
boolean add = false, substract = false, devide = false, multiply = false, firstNumber = true;
// numbers that will be calculated
double number1, number2;
public Calculator()
{
setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
// bottom panel
bottom.setPreferredSize(new Dimension(100,100));
bottom.setLayout(new BorderLayout());
//add bottom panel to frame
add(bottom);
// top panel
top.setPreferredSize(new Dimension(300,400));
top.setLayout(new GridLayout(4,4,3,3));
top.setBackground(Color.BLACK);
//dont add top panel to frame: you want top to be on bottom
// add top panel to bottom panel
bottom.add(top);
// label
label.setFont(new Font("Courier", Font.PLAIN, 20));
label.setBackground(Color.BLACK);
label.setForeground(Color.WHITE);
label.setHorizontalAlignment(SwingConstants.RIGHT); // text is right-aligned
label.setOpaque(true);
// add the label to the bottom panel
bottom.add(label, BorderLayout.NORTH);
// creating buttons
for(int i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton("789/456*123+c0=-".substring(i, i+1));
buttons[i].addActionListener(this);
// add them to the top panel
top.add(buttons[i]);
}
// Nimbus look
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
//set to default somehow o.o
}
// frame setters
setTitle("Calculator");
setSize(400,400);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void Clear()
{
label.setText(" ");
}
#Override
public void actionPerformed(ActionEvent e)
{
//if's for all function buttons
if(e.getSource() == buttons[3])
{
// devide
devide = true;
substract = false;
add = false;
multiply = false;
firstNumber = false;
Clear();
label.setText("/");
}
if(e.getSource() == buttons[7])
{
// multiply
multiply = true;
substract = false;
devide = false;
add = false;
firstNumber = false;
Clear();
label.setText("*");
}
if(e.getSource() == buttons[11])
{
// add
add = true;
substract = false;
devide = false;
multiply = false;
firstNumber = false;
Clear();
label.setText("+");
}
if(e.getSource() == buttons[12])
{
// clear
label.setText("0");
number1 = 0.00;
number2 = 0.00;
add = false;
substract = false;
devide = false;
multiply = false;
firstNumber = true;
Clear();
}
if(e.getSource() == buttons[15])
{
// substract
substract = true;
add = false;
devide = false;
multiply = false;
firstNumber = false;
Clear();
label.setText("-");
}
// for loops that add the numbers on the buttons to the label
for(int i = 0; i < 3; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}
for(int i = 4; i < 7; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}
for(int i = 8; i < 11; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}
for(int i = 13; i < 14; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}
// if statement that puts the labels text into the first or second number
if(firstNumber)
{
number1 = Double.parseDouble(label.getText().trim());
} else {
number2 = Double.parseDouble(label.getText().trim());
}
// calculation
if(e.getSource() == buttons[14])
{
// calculate
if(devide){number1 = ((double)(number1) / (double)(number2)); }
if(multiply){number1 = ((double)(number1) * (double)(number2)); }
if(add){number1 = ((double)(number1) + (double)(number2)); }
if(substract){number1 = ((double)(number1) - (double)(number2)); }
label.setText(Double.toString(number1));
}
}
public static void main(String[] args)
{
new Calculator();
}
}
Lastly, the calculations made by the calculator are incorrect. I also can't wrap my head around what's causing that. Please bear in mind that I'm a beginner at Java and this is my first question on stackoverflow. Thanks in advance for helping me, whoever will :)
UPDATE: i fixed the errors by putting my code as follows:
if(e.getSource() == buttons[15])
{
// substract
substract = true;
add = false;
devide = false;
multiply = false;
firstNumber = false;
isNumberKey = false;
if(isNumberKey)
{
if(firstNumber)
{
label.setText(label.getText().replace("/",""));
label.setText(label.getText().replace("*",""));
label.setText(label.getText().replace("+",""));
label.setText(label.getText().replace("-",""));
number1 = Double.parseDouble(label.getText().trim());
} else {
label.setText(label.getText().replace("/",""));
label.setText(label.getText().replace("*",""));
label.setText(label.getText().replace("+",""));
label.setText(label.getText().replace("-",""));
number2 = Double.parseDouble(label.getText().trim());
}
}
Clear();
label.setText("-");
}
All i need to do now is fix the calculations...
Thanks for the help everyone!
Cannot delve totaly into your logic there, but here's some hints:
First, you don't have to guess where the error is. In case of uncaught exception like here, thread that produced it will print it's stack trace to console. It looks like this:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "/"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.parseDouble(Double.java:510)
at mypackage.Calculator.actionPerformed(Calculator.java:229)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6297)
From here you see that exception happened in thread named AWT-EventQueue-0, which is swing's standard event dispatching thread (all GUI applications handles events in single thread). Another thing you search in stack trace is to find what line in your code thrown it. Here it's the line:
at mypackage.Calculator.actionPerformed(Calculator.java:229)
In source, it is line:
number2 = Double.parseDouble(label.getText().trim());
, so you guessed right. What you can do is add another boolean there which will be set only if number button is hit, and then change that part of code to something like:
if( isNumber){
if(firstNumber)
{
number1 = Double.parseDouble(label.getText().trim());
} else {
number2 = Double.parseDouble(label.getText().trim());
}
}
Apart from that, instead of using multiple boolean flags for operation, use Java enum type
enum Operation {devide, substract, add, multiply};
your code will be more readable and "java" styled.
Good starting point, just go ahead!
Disclaimer: I'm on my phone so it's hard to parse your code; with that being said, I believe your number format exception deals with what is stored in the label text.
From the looks of it if you hit an operator button (like multiply), the labelText will be "*", then if you hit number button (like 5), the labelText will be "*5". Finally, if you hit the enter button now to go calculate the answer, Double.parseDouble(label.getText().trim()), will be ran which will throw the NumberFormatException. Using the operation flags, it looks like you don't even need to store the operator (unless you're trying to display the operator to the user); in that case you need to strip the operator from the string before trying the parse the double.
label.setText(label.getText().replace("/",""));
label.setText(label.getText().replace("*",""));
label.setText(label.getText().replace("+",""));
label.setText(label.getText().replace("-",""));
As for the other exceptions, in eclipse you can set a breakpoint to halt the program when a specific exception occurs. This will help you debug your code further.
more info on that here

Java GUI - Calling value from other if statements into getSource() event

So I am making a very basic cash register program currently for my college class. Basically every time I press a button it adds to a total, and when I press total it sums it all up. The the problem is that I can't seem to call the value from the variable into the total button. It always stays 0.0 even though I am making that variable have a value when I press the other events. I need to get past this point so I can check to see if the if statements are working properly.
The end result would be a register that I can always change its total by pressing a different combination of buttons. If I press one button, it will come up with a sum. So if I press button one once, it will only be 1.50 for example. But if I press it two times, it will be 3.0. I know I probably should use a counter for each event and get the product of that counter with the predetermined value that I am setting. But right now I can't seem to get past the problem with my total button event. Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BobsBurgerPanel extends JPanel
{
private int test1 = 1;
private double totalResult;
private double total1, total2, total3, total4, total5, total6;
private JButton push1, push2, push3, push4, push5, push6, total;
private JTextField text;
private JLabel label;
public BobsBurgerPanel()
{
push1 = new JButton("Small Drink");
push2 = new JButton("Large Drink");
push3 = new JButton("Small Fry");
push4 = new JButton("Large Fry");
push5 = new JButton("Veggie Burger");
push6 = new JButton("Bison Burger");
total = new JButton("Total");
label = new JLabel(" Your total is: ");
// Lining the text up with the JTectfield. \t or \n do not work.
text = new JTextField(10);
total.addActionListener(new TempListener());
add(push1);
add(push2);
add(push3);
add(push4);
add(push5);
add(push6);
add(total);
add(label);
add(text);
setPreferredSize(new Dimension(400,300));
setBackground(Color.red);
}
private class TempListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
int counter1 = 0, counter2 = 0, counter3 = 0,
counter4 = 0, counter5 = 0, counter6 = 0, counter7 = 0;
double totalR;
if (event.getSource() == push1)
{
counter1++;
total1 = counter1 * 1.50;
}
if (event.getSource() == push2)
{
counter2++;
total2 = counter2 * 2.10;
}
if (event.getSource() == push3)
{
counter3++;
total3 = counter3 * 2.00;
}
if (event.getSource() == push4)
{
counter4++;
total4 = counter4 * 2.95;
}
if (event.getSource() == push5)
{
counter5++;
total5 = counter5 * 4.55;
}
if (event.getSource() == push6)
{
counter6++;
total6 = counter6 * 7.95;
}
if (event.getSource() == total)
totalResult =
(total1+total2+total3+total4+total5+total6);
text.setText(Double.toString(totalResult));
}
}
Any help or additional ideas would be great. Thanks for reading.
Your counter variables are declared local and therefore are 0 at every iteration. I recommend you declare them outside of your method since you need them to be incremented every time an action is performed.
Also, since your code can only be in one state at a time, you would benefit from else statements instead of just if.
Dude you've added listener only to your JButton total. So the actionPerformed method always and only gets through
if (event.getSource() == total)
totalResult =(total1+total2+total3+total4+total5+total6);
statement, because JButton total is the only source of click event. That's why you're getting 0 over and over again.

Checking if user input matches any number in the same column

Program is 10x10 board, I need to check if the user's input is a duplicate of any number in that same column, but I can't figure it out. When I tried it, it always check the same box. For example, if I entered 4 in [1][1] (going by 10x10 grid), it automatically checks right after I entered that [1][1] is the same as my input and erases it. My professor wants me to check it with the "CheckWinner" method. This is my code so far in my eventhandler:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package firstgui;
import java.awt.event.*;
import java.util.Scanner;
import javax.swing.*;
/**
*
* #author douglas moody
*/
public class EventHandler implements ActionListener{
// EventBoard is the name of the array containing all the JButton withi teh EventHandler
// board (in the other program) is the name of the array containing all the JButton withi the FirstGui program
JButton[][] EventBoard;
private static String player = " ";
// this method is called from FirstGui to tell the Eventhandler the board array
public void setEventBoard (JButton[][] inboard){
EventBoard = inboard;
}
public void actionPerformed(ActionEvent e) {
JButton clickedbutton;
// clickedbutton will now point to the Button actually clicked
clickedbutton = (JButton) e.getSource();
player = JOptionPane.showInputDialog("Enter a number from 1-10");
if(player.matches("[1-9]|10")){
clickedbutton.setText(player);
}else{
JOptionPane.showMessageDialog(null, "Invalid Input", "Invalid Input", JOptionPane.ERROR_MESSAGE);
}
// call the routine to check if the player who just moved won
if (CheckWinner(player)){
JOptionPane.showMessageDialog(null, "Player: " + player + " won");
}
}
private boolean CheckWinner(String inplayer) {
int count = 0, count2 = 0;
// this loop checks the columns on the Board
for (int i=0; i<=9; i++){
for (int j=0; j<=9; j++) {
if (EventBoard[i][j].getText().equals( inplayer )){
JOptionPane.showMessageDialog(null, "copy");
EventBoard[i][j].setText("");
}
}
if (count == 10 && count2 == 10) return true;
}
return false;
}
}
Pass the reference the JButton that triggered the action to the CheckWinner method and simply ignore it when performing you checks...
For example...
private boolean CheckWinner(JButton source, String inplayer) {
//...
if (EventBoard[i][j] != source &&
EventBoard[i][j].getText().equals( inplayer )){
JOptionPane.showMessageDialog(null, "copy");
EventBoard[i][j].setText("");
}
Updated...
To check the values in a given column, you need to know which column to check. I've not tested this, but something like the example below, should help...
private boolean CheckWinner(JButton source, String inplayer) {
int buttonColumn = -1;
for (int col = 0; col < EventBoard.length; col++) {
for (JButton item : EventBoard[col]) {
if (item == source) {
buttonColumn = col;
break;
}
}
}
boolean match = false;
for (JButton item : EventBoard[buttonColumn]) {
if (source != item && item.getText().equals(inplayer)) {
match = true;
break;
}
}
return match;
}

Categories