Combination Lock (Java) - java

I have a school assignment that i need to create. Below is the info:
Create a frame with ten buttons, labeled 0 through 9. To exit the program, the user must click on the correct three buttons in order, something like 7-3-5. If the wrong combination is used, the frame turns red.
I already finish the frame and the buttons with online research helps, but i just cant make the functionality to work. Please take a look at my codes and thanks in advance.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComboNumber extends JFrame implements ActionListener{
//variable declaration
int ans1 = 3;
int ans2 = 7;
int ans3 = 1;
int one, two, three;
String inData1, inData2, inData3;
JButton[] button;
//constructs the combolock object
public ComboNumber()
{
//sets flowlayout
getContentPane().setLayout(new FlowLayout());
Container c = getContentPane();
//creates buttons
button = new JButton[10];
for(int i = 0; i < button.length; ++i) {
button[i] = new JButton("" + i);
//adds buttons to the frame
c.add(button[i]);
//registers listeners with buttons
button[i].addActionListener(this);
}
//sets commands for the buttons (useless)
//sets title for frame
setTitle("ComboLock");
}
//end combolock object
//listener object
public void actionPerformed(ActionEvent evt)
{
Object o = evt.getSource();
for(int i = 0; i < button.length; ++i) {
if(button[i] == o) {
// it is button[i] that was cliked
// act accordingly
return;
}
}
}
//end listener object
//main method
public static void main (String[] args)
{
//calls object to format window
ComboNumber frm = new ComboNumber();
//WindowQuitter class to listen for window closing
WindowQuitter wQuit = new WindowQuitter();
frm.addWindowListener(wQuit);
//sets window size and visibility
frm.setSize(500, 500);
frm.setVisible(true);
}
//end main method
}
//end main class
//window quitter class
class WindowQuitter extends WindowAdapter
{
//method to close the window
public void windowClosing(WindowEvent e)
{
//exits the program when the window is closed
System.exit(0);
}
//end method
}
//end class

The basic idea is simple.
You need two things.
What the combination actually is
What the user has guessed
So. You need to add two variables. One contains the combination/secret, the other contains the guesses.
private String secret = "123";
private String guess = "";
This allows you to make the combination as long as you like ;)
Then in your actionPerformed method, you need to add the most recent button click to the guess, check it against the secret and see if they've made a good guess. If the length of the guess passes the number of characters in the secret, you need to reset the guess.
public void actionPerformed(ActionEvent evt) {
Object o = evt.getSource();
if (o instanceof JButton) {
JButton btn = (JButton) o;
guess += btn.getText();
if (guess.equals(secret)) {
JOptionPane.showMessageDialog(this, "Welcome Overloard Master");
dispose();
} else if (guess.length() >= 3) {
JOptionPane.showMessageDialog(this, "WRONG", "Wrong", JOptionPane.ERROR_MESSAGE);
guess = "";
}
}
}

Related

How to get the source of multiple JButtons in action listener?

I'm coding a memory matching game using pictures and a JButton array, but I've run into a problem when I try to compare two buttons that were clicked. How do you store the index of/get the index of the second button? All of my buttons in the button array are linked to the same actionListener but e.getSource() will only get the first button clicked, as far as I'm aware. I'd really appreciate some help. (I didn't want to paste in my entire code, because that's a lot, so I'm just putting in parts I think are relevant):
public DisplayMM(ActionListener e)
{
setLayout(new GridLayout(6, 8, 5, 5));
JButton[] cards = new JButton[48]; //JButton board
for(int x = 0; x < 48; x++) //initial setup of board
{
cards[x] = new JButton();
cards[x].addActionListener(e);
cards[x].setHorizontalAlignment(SwingConstants.CENTER);
cards[x].setPreferredSize(new Dimension(75, 95));
}
private class e implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
for(int i = 0; i < 48; i++)
{
if((e.getSource())==(cards[i]))//1st button that was clicked
{
cards[i].setIcon(new ImageIcon(this.getClass().getResource(country[i])));
currentIndex = i;
}
}
//cards[i].compareIcons(currentIndex, secondIndex);
}
}
Also, in my Panel class, I attempted to do something similar, but ended up moving it to the Display class because Panel didn't have access to the button array.
//Panel
public void actionPerformed(ActionEvent e)
{
/*every 2 button clicks it does something and decreases num of tries*/
noMatchTimer = new Timer(1000, this);
noMatchTimer.setRepeats(false);
JButton source = (JButton)e.getSource();
guess1 = source.getText(); //first button clicked
numGuess++; //keeps track of number of buttons clicked
JButton source2 = (JButton)e.getSource();
guess2 = source2.getText();
numGuess++;
if(numGuess == 1)
display.faceUp(cards, array, Integer.parseInt(e.getSource()));
else
display.compareIcons(guess1, guess2);
if(tries != 12 && count == 24)
{
displayWinner();
}
}
You can give your ActionListener class private fields, even if it's an anonymous inner class, and one of those fields can be a reference to the last button pushed. Set it to null after the 2nd button is pushed and you'll always know if the button press is for the first or second button.
e.g.,
class ButtonListener implements ActionListener {
private JButton lastButtonPressed = null;
#Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
if (lastButtonPressed == null) {
// then this is the first button
lastButtonPressed = source;
} else {
// this is the 2nd button
if (source == lastButtonPressed) {
// the dufus is pushing the same button -- do nothing
return;
} else {
// compare source and lastButtonPressed to see if same images (icons?)
// if not the same, use a Timer to hold both open for a short period of time
// then close both
lastButtonPressed = null;
}
}
}
}

Need help understanding how a specific getter affects my program

I'm very new to coding(2 months) and i attempted to make Tic-Tac-Toe in java. I'm in a little over my head but i managed to create it using swing. My main problem is in the button1 class. I was going to use the getText() method but ended up not needing it or so i thought. I tried deleting it but as it turns out my tictactoe buttons don't switch letters without it. The compiler told me it overrides AbstractButton's getText() method but i don't see why that should matter since i never actually used it i thought. I'm thinking it's maybe a scope issue handled by it being overwritten somehow but i'm not sure. I was trying to use the text variable to update the button with setText() and that doesn't seem to work like i thought it should. I also don't understand why the 3 by 3 gridlayout seems to work properly most of the time but sometimes the number of buttons added is wrong.
So in summation the program works(mostly) but i'm not fully understanding how the button1 class is working.
TicTacToe.java
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class TicTacToe extends JFrame {
public static void main(String[] args) {
JFrame window = new JFrame("Tic-Tac-Toe");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setSize(600, 600);
window.setLayout(new GridLayout(3, 3));
ArrayList<button1> buttonArrayList = new ArrayList<>(9);
for (int i = 0; i < 9; i++) {
button1 newbutton = new button1();
buttonArrayList.add(newbutton);
window.add(buttonArrayList.get(i));
}
}
}
button1.java
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
public class button1 extends JButton {
int value = 0;
String text = "";
public button1() {
class ButtonAction extends AbstractAction {
public ButtonAction() {}
#Override
public void actionPerformed(ActionEvent Switcher) {
System.out.println(text + " " + value);
value++;//value is a relic from earlier attempts that i just felt like keeping.
if (text.equals("O")) {
text = "X";
} else if (text.equals("X")) {
text = "";
} else if (text.equals("")) {
text = "O";
}
}
}
this.setAction(new ButtonAction());
this.setText(text);
this.setFont(new Font("Arial",Font.PLAIN,120));
}
public String getText()// <----culprit
{
return text;
}
}
A JButton class has a methods defined for it, including setText() (which will set the displayed text on the button) and getText() (which will return the current text that is displayed on the button).
You created a class button1 (note: classes should start with Capital Letters).
You added an Action to the button1 class, which means that when the action is activated, something happens. Note that in that actionPerformed method, you should call setText(text) to update the displayed value.
You have also defined a getText() method that overrides the getText() method defined in JButton. This approach is fine if it is a conscious design decision. As it is, I think you should remove the getText() method from the button1 class, and allow the standard JButton class to handle the update. Right now, you are attempting to keep an instance variable text with the value, but it is possible for that instance variable to not be in alignment with the actual displayed value of the button (consider another class calling .setText() on the button).
EDIT: It is true that this referring to the JButton in the ButtonAction is not available. However, the Action itself contains the button that was pressed.
#Override
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton)e.getSource();
// if desired, String cur = btn.getText() may be called to find the
// current setting; get and process if needed
btn.setText(WHAT_EVER_TEXT);
}
Unless it is a specific requirement to process the current text, however (allowing selecting an O to an X to a blank), I would implement something to keep track of the current turn. This code is something I was experimenting with, and has good and bad points to it (as it is illustrative):
static class TurnController
{
// whose turn it is; start with X
private Player whoseTurn = Player.X;
// the instance variable
private static final TurnController instance = new TurnController();
private TurnController()
{
}
public static Player currentTurn()
{
return instance.whoseTurn;
}
public static Player nextTurn()
{
switch (instance.whoseTurn) {
case X:
instance.whoseTurn = Player.O;
break;
case O:
instance.whoseTurn = Player.X;
break;
}
return instance.whoseTurn;
}
public static String getMarkerAndAdvance()
{
String marker = currentTurn().toString();
nextTurn();
return marker;
}
enum Player
{
X,
O,
;
}
}
Using this TurnController, the actionPerformed becomes:
#Override
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton)e.getSource();
btn.setText(TurnController.getMarkerAndAdvance());
}
and the Button1 class may have the String text instance variable removed.
What you have tried is Try to make a Custom Button Class and its EventHandler just by extending AbstractAction namee button1 as we See in Your Question.
You have Override the method actionPerformed(ActionEvent Switcher) which actually belongs to Class AbstractAction by your own definition (What should Performed on Action Event of Every Button).
class ButtonAction extends AbstractAction {
public ButtonAction() {}
#Override
public void actionPerformed(ActionEvent Switcher) { // Your Definition For actionPerformed..
System.out.println(text + " " + value);
value++;//value is a relic from earlier attempts that i just felt like keeping.
if (text.equals("O")) {
text = "X";
} else if (text.equals("X")) {
text = "";
} else if (text.equals("")) {
text = "O";
}
}
}
this.setAction(new ButtonAction()); // add ActionListener to each Button.
this.setText(text); // Setting Text to each Button
this.setFont(new Font("Arial",Font.PLAIN,120)); //add Font to each Button.
}
Now In this Code.
ArrayList buttonArrayList = new ArrayList<>();
for (int i = 0; i < 9; i++) {
button1 newbutton = new button1(); // Creating 9 new buttons.
buttonArrayList.add(newbutton); // add each button into the ArrayList.
window.add(buttonArrayList.get(i)); // each Button to the the AWT Window.
}
Above Code will generate 9 Button and add it to Your AWT Window. each button have actionPerformed() method which contains the overrided Definition.
Now Each button will performed action as per the definition you give to actionPerformed() Method.
Thank You.

java swing calculator two digit

I cannot enter two digit number to be calculator. I also cannot get the clear C operator working as well. My dot sign seems to be not working as well. The code below creates a calculator using java swing and does addition, multiplication,subtraction and divisiion of a single digit number.
//First the necessary packages are imported
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**#return a BODMAS calculator using Javax Swing and awt
* *#author Cihan Altunok
*#version 1
*/
//implementing ActionListener to listen to events. JFrame is also extended to add support to Swing components
public class Calculator extends JFrame implements ActionListener {
//declaring some variables to be used in our program
JFrame guiCalculatorFrame;
JPanel buttonPanel;
JTextArea numberCalculator;
int calculatorOpr=0;
int currentCalculation;
//EventQueue invokeLater is used to ensure the run method is called in the dispatch thread of the EventQueue
//declaring the constructor for the class
public Calculator()
{
//instantiating guiCalculatorFrame
guiCalculatorFrame=new JFrame();
//the red cross sign drawn to exit the window
guiCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiCalculatorFrame.setTitle("Calculator");
//setting the size of the frame
guiCalculatorFrame.setSize(400,400);
//The setLocationRelativeTo has been set to null to center the window
guiCalculatorFrame.setLocationRelativeTo(null);
//JTextField is created to allow a set of characters to be entered
numberCalculator=new JTextArea();
//setting the alignment of JTextField along the RIGHT axis
numberCalculator.setAlignmentX(JTextField.RIGHT);
//making the textfield not editable
numberCalculator.setEditable(false);
//container containing the components in the north region
guiCalculatorFrame.add(numberCalculator, BorderLayout.NORTH);
//panel is created and we will add buttons to the panel later in the program
buttonPanel=new JPanel();
//setting Layout to GridLayout to lay the components in a rectangular grid
buttonPanel.setLayout(new GridLayout(5,5));
//adding the buttons to the frame. Putting the buttons in the center
guiCalculatorFrame.add(buttonPanel,BorderLayout.CENTER);
// a following for loop is done to add the numberButtons
for (int i=0;i<10;i++)
{
addNumberButton(buttonPanel,String.valueOf(i));
}
//next the five mathematical operators are added
addActionButton(buttonPanel,1,"+");
addActionButton(buttonPanel,2,"-");
addActionButton(buttonPanel,3,"*");
addActionButton(buttonPanel,4,"/");
addActionButton(buttonPanel,5,"^2");
addActionButton(buttonPanel,6,"C");
addActionButton(buttonPanel,7,"^");
addActionButton(buttonPanel,8,".");
//equalSign Button is created
JButton equalsSignButton=new JButton("=");
//the action command for the equal sign button is set
equalsSignButton.setActionCommand("=");
equalsSignButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
//checking if the numberCalculator field is a valid mathematical operator
{
if (!numberCalculator.getText().isEmpty())
{
//turning text into integer
int number=Integer.parseInt(numberCalculator.getText());
// doing a series of if statements for the list of operations
if (calculatorOpr==1)
{
int calculate=currentCalculation+number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==2)
{
int calculate=currentCalculation-number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==3)
{
int calculate=currentCalculation*number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==4)
{
int calculate=currentCalculation/number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==5)
{
int calculate=currentCalculation*currentCalculation;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==6)
{
numberCalculator.setText("");
}
else if (calculatorOpr==7)
{
int calculate=(int) Math.sqrt(Integer.parseInt(numberCalculator.getText()));
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==8)
{
numberCalculator.append(".");
}
}
}
});
//adding equals sign to the panel
buttonPanel.add(equalsSignButton);
//setting the visibility to True so the frame can be seen
guiCalculatorFrame.setVisible(true);
}
//passing two paremeters to the addNumberButton method
private void addNumberButton(Container contain, String name) {
JButton buttonOne=new JButton(name);
//setting the action command for the button created above
buttonOne.setActionCommand(name);
buttonOne.addActionListener(this);
//adding buttonOne to the container
contain.add(buttonOne);
}
//passing three parameters to the addActionButton method
private void addActionButton(Container contain, int i, String text) {
JButton buttonOne=new JButton(text);
//setting the action command for the button created above
buttonOne.setActionCommand(text);
//creating a new class
Operators addAction=new Operators(i);
buttonOne.addActionListener(addAction);
//adding buttonOne to the container
contain.add(buttonOne);
}
public void actionPerformed(ActionEvent event) {
//returning the command string associated with this string
String i=event.getActionCommand();
//setting the Text to the specified String
numberCalculator.setText(i);
}
//creating an inner class and implementing ActionListener
private class Operators implements ActionListener
{
private int operators;
//creating a constructor and passing a parameter
public Operators(int operation)
{
operators=operation;
}
public void actionPerformed(ActionEvent event)
{
currentCalculation=Integer.parseInt(numberCalculator.getText());
calculatorOpr=operators;
}
}
}*
The problem was you were overwrting the text field. and the action listener for C button was wrong. This will solve your basic problems, but some work remaining. For instance you are not handling the . at the moment.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener {
// declaring some variables to be used in our program
JFrame guiCalculatorFrame;
JPanel buttonPanel;
JTextArea numberCalculator;
int calculatorOpr = 0;
int currentCalculation;
boolean isOperatorActive = false;
// EventQueue invokeLater is used to ensure the run method is called in the
// dispatch thread of the EventQueue
// declaring the constructor for the class
public Calculator() {
// instantiating guiCalculatorFrame
guiCalculatorFrame = new JFrame();
// the red cross sign drawn to exit the window
guiCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiCalculatorFrame.setTitle("Calculator");
// setting the size of the frame
guiCalculatorFrame.setSize(400, 400);
// The setLocationRelativeTo has been set to null to center the window
guiCalculatorFrame.setLocationRelativeTo(null);
// JTextField is created to allow a set of characters to be entered
numberCalculator = new JTextArea();
// setting the alignment of JTextField along the RIGHT axis
numberCalculator.setAlignmentX(JTextField.RIGHT);
// making the textfield not editable
numberCalculator.setEditable(false);
// container containing the components in the north region
guiCalculatorFrame.add(numberCalculator, BorderLayout.NORTH);
// panel is created and we will add buttons to the panel later in the
// program
buttonPanel = new JPanel();
// setting Layout to GridLayout to lay the components in a rectangular
// grid
buttonPanel.setLayout(new GridLayout(5, 5));
// adding the buttons to the frame. Putting the buttons in the center
guiCalculatorFrame.add(buttonPanel, BorderLayout.CENTER);
// a following for loop is done to add the numberButtons
for (int i = 0; i < 10; i++) {
addNumberButton(buttonPanel, String.valueOf(i));
}
// next the five mathematical operators are added
addActionButton(buttonPanel, 1, "+");
addActionButton(buttonPanel, 2, "-");
addActionButton(buttonPanel, 3, "*");
addActionButton(buttonPanel, 4, "/");
addActionButton(buttonPanel, 5, "^2");
addActionButton(buttonPanel, 6, "C");
addActionButton(buttonPanel, 7, "^");
addActionButton(buttonPanel, 8, ".");
// equalSign Button is created
JButton equalsSignButton = new JButton("=");
// the action command for the equal sign button is set
equalsSignButton.setActionCommand("=");
equalsSignButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// checking if the numberCalculator field is a valid mathematical
// operator
isOperatorActive = true;
if (!numberCalculator.getText().isEmpty()) {
// turning text into integer
int number = Integer.parseInt(numberCalculator.getText());
// doing a series of if statements for the list of
// operations
int calculate = 0;
switch (calculatorOpr) {
case 1:
calculate = currentCalculation + number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 2:
calculate = currentCalculation - number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 3:
calculate = currentCalculation * number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 4:
calculate = currentCalculation / number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 5:
calculate = currentCalculation * currentCalculation;
numberCalculator.setText(Integer.toString(calculate));
break;
case 7:
calculate = (int) Math.sqrt(Integer
.parseInt(numberCalculator.getText()));
numberCalculator.setText(Integer.toString(calculate));
break;
case 8:
numberCalculator.append(".");
break;
default:
break;
}
}
}
});
// adding equals sign to the panel
buttonPanel.add(equalsSignButton);
// setting the visibility to True so the frame can be seen
guiCalculatorFrame.setVisible(true);
}
// passing two parameters to the addNumberButton method
private void addNumberButton(Container contain, String name) {
JButton buttonOne = new JButton(name);
// setting the action command for the button created above
buttonOne.setActionCommand(name);
buttonOne.addActionListener(this);
// adding buttonOne to the container
contain.add(buttonOne);
}
// passing three parameters to the addActionButton method
private void addActionButton(Container contain, int i, String text) {
JButton buttonOne = new JButton(text);
// setting the action command for the button created above
buttonOne.setActionCommand(text);
// creating a new class
Operators addAction = new Operators(i);
buttonOne.addActionListener(addAction);
// adding buttonOne to the container
contain.add(buttonOne);
}
public void actionPerformed(ActionEvent event) {
// returning the command string associated with this string
String i = event.getActionCommand();
// setting the Text to the specified String
if(isOperatorActive){
numberCalculator.setText(i);
isOperatorActive = false;
} else {
numberCalculator.setText(numberCalculator.getText() + i);
}
}
// creating an inner class and implementing ActionListener
private class Operators implements ActionListener {
private int operators;
// creating a constructor and passing a parameter
public Operators(int operation) {
operators = operation;
}
public void actionPerformed(ActionEvent event) {
isOperatorActive = true;
switch (operators) {
case 6:
numberCalculator.setText("");
currentCalculation = 0;
calculatorOpr = 0;
break;
case 8:
isOperatorActive = false;
default:
currentCalculation = Integer.parseInt(numberCalculator.getText());
calculatorOpr = operators;
break;
}
}
}
}
import javax.swing.*;
import java.awt.*;
/*
# Author 12CSE54
# Date 29.10.14
*/
public class calculator1 extends JFrame
{
public calculator1() {
initComponents();
}
int a,b,c;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a+b;
jTextField3.setText(String.valueOf(c));
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a-b;
jTextField3.setText(String.valueOf(c));
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a*b;
jTextField3.setText(String.valueOf(c));
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a/b;
jTextField3.setText(String.valueOf(c));
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
}
public static void main(String ar[])
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new calculator1().setVisible(true);
}
});
}

java calculator decimal point

I have fully working calculator using java.Can tell me how to add decimal point.I already have the button and the variables are in type double.I just can't make the button work.
I tried to do it myself,but I ended up with error messages every time.
Here is the code:
package oop;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Kalkulator2 extends Applet {
String arg1= "", arg2="";
double ergebnis;
Button zahl[] =new Button[10];
Button funktion[] = new Button[4];
Button ausfuehren;
Button decimalpoint;
char dec='.';
Panel zahlPanel,funktionPanel,ergebnisPanel;
TextField ergebnisFeld = new TextField(5);
int operationArgument;
char operation;
public void init () {
operationArgument= 1; operation =' ';
setLayout(new BorderLayout());
zahlPanel = new Panel();
zahlPanel.setLayout(new GridLayout (4,3));
for (int i=9; i>=0; i--) {
zahl[i] = new Button(String.valueOf(i));
zahl[i].addActionListener(new ButtonZahlen());
zahlPanel.add(zahl[i]);
}
decimalpoint = new Button(String.valueOf(dec)); //decimal point
//decimalpoint.addActionListener(new Button ());
ausfuehren = new Button("=");
ausfuehren.addActionListener(new ButtonAusfuehren()); //zu dem Listener
zahlPanel.add(decimalpoint);
zahlPanel.add(ausfuehren);
add("Center",zahlPanel);
funktionPanel = new Panel();
funktionPanel.setLayout(new GridLayout(4,1));
funktion[0] = new Button("+");
funktion[0].addActionListener(new ButtonOperation());
funktionPanel.add(funktion[0]);
funktion[1] = new Button("-");
funktion[1].addActionListener(new ButtonOperation());
funktionPanel.add(funktion[1]);
funktion[2] = new Button("*");
funktion[2].addActionListener (new ButtonOperation());
funktionPanel.add(funktion[2]);
funktion[3] = new Button("/");
funktion[3].addActionListener (new ButtonOperation());
funktionPanel.add(funktion[3]);
add("East",funktionPanel);
ergebnisPanel = new Panel();
ergebnisPanel.add(ergebnisFeld);
add("North",ergebnisPanel);
}
class ButtonZahlen implements ActionListener{
public void actionPerformed(ActionEvent e) {
switch (operationArgument) {
case 1 : {
arg1+=e.getActionCommand();
ergebnisFeld.setText(arg1);
break;
}
case 2 : {
arg2 +=e.getActionCommand();
ergebnisFeld.setText(arg2);
break;
}
default: { }
}
}
}
class ButtonAusfuehren implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(operation =='+')
ergebnis = new Double(arg1) + new Double(arg2);
else if (operation == '-')
ergebnis = new Double(arg1) - new Double(arg2);
else if(operation =='*')
ergebnis = new Double(arg1) * new Double(arg2);
else if(operation =='/')
ergebnis = new Double(arg1) / new Double(arg2);
ergebnisFeld.setText(String.valueOf(ergebnis));
}
}
class ButtonOperation implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("+")) {
operation = '+'; operationArgument = 2;
}
else if(e.getActionCommand().equals("-")) {
operation = '-'; operationArgument = 2;
}
else if(e.getActionCommand().equals("*")) {
operation = '*' ; operationArgument =2;
}
else if(e.getActionCommand().equals("/")) {
operation = '/' ; operationArgument =2;
}
}
}
}
public void paint(Graphics g){ }
}
When the button got clicked, it is trying to create a new button object which doesn't implement an actionListener. Thus it will throw an error saying " what must i do with a new button while i need an object with 'actionPerformed' method " Here is a possible solution;
// create button object
decimalpoint = new Button(".");
// not good : decimalpoint.addActionListener(new Button ());
// event on click
decimalpoint.addActionListener(new YourClassName());
and YourClassName is an instance to handle the button event
class YourClassName implements ActionListener {
public void actionPerformed(ActionEvent e) {
// add decimal point
}
}
I also agree with Andrew Thompson that AWT is not a preferred way to handle your tasks. If your teacher has suggested you to use AWT, then please use Swing. Swing is far better then AWT and should be educated to people who is writing GUI-based java for the first time.
To answer the question, to add a DECIMAL POINT to java code (my example is for GUI NetBeans IDE 8.0.2) I have stumbled across this code. I must admit I have not come across this code having looked for an answer on the net.
private void PointActionPerformed(java.awt.event.ActionEvent evt) {
txtDisplay.setText(txtDisplay.getText()+Point.getText());
}
you can do that simply
specify the button -
Button Decimal;
caste the button you specified in your xml file to (Button)Decimal -
Decimal = findViewById(R.id.the id you gave to the button);
Now set on click listener
Decimal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.setText(edit.getText().toString() + ".");
}
where edit is the field you want the text to be filled.

Making a TicTacToe game; how can I get the tictactoe buttons to alternate between X and O?

I just need to get it to alternate between "X" and "O" for the turns but it's only giving me X's.
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class tictactoe {
public static final int FRAME_WIDTH = 700;
public static final int FRAME_HEIGHT = 200;
public static void main(String[] args)
{
int slots = 9;
final JButton[] gameButton = new JButton[9];
JPanel ticTacToeBoard = new JPanel();
ticTacToeBoard.setLayout(new GridLayout(3, 3));
JButton clearButtons = new JButton("New Game");
for (int i = 0; i < slots; i++)
{
gameButton[i] = new JButton();
ticTacToeBoard.add(gameButton[i]);
final int countTurns = i;
gameButton[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object clicked = e.getSource();
int turns = 1;
for (int p = 0; p < 9; p++)
{
if(clicked == gameButton[countTurns] && turns < 10)
{
if (!(turns % 2 == 0))
{
((JButton)e.getSource()).setText("X");
turns++;
}
else
{
((JButton)e.getSource()).setText("O");
turns++;
}
}
}
}
});
final int integerHack = i;
clearButtons.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
gameButton[integerHack].setText("");
}
});
}
JButton exit = new JButton("Exit");
exit.setActionCommand("EXIT");
exit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd == "EXIT")
{
System.exit(FRAME_WIDTH);
}
}
});
JPanel rightPanel = new JPanel();
JLabel wonLabel = new JLabel();
rightPanel.setLayout(new GridLayout(1, 3));
rightPanel.add(wonLabel);
rightPanel.add(clearButtons);
rightPanel.add(exit);
JFrame mainFrame = new JFrame();
mainFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
mainFrame.setVisible(true);
mainFrame.setLayout(new GridLayout(1,2));
mainFrame.add(ticTacToeBoard);
mainFrame.add(rightPanel);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Look at your actionPerformed method. Every time a click happens, you set turns to 1. As a result, !(turns % 2 == 0) will always evaluate true, and you'll always draw an X.
Just by quickly looking at your code, I would guess it is because your turn variable is local in all the ActionListener objects. Therefore, the turn variable is always 1 and you always run into the first if case. So the turn variable is always recreated on the stack as soon as you get a callback in the actionPerformed method. For a quick fix and test, try to put the turn variable in the tictactoe class and see if that helps.
The trouble is with the turns variable in your actionPerformed. If you want to keep a track of it you should move that out from your method.
Firstly, as the other people have also said, you want "turns" to be initialized outside all your loops.
Secondly, I would like to point out a typo:
if(clicked == gameButton[countTurns] && turns < 10)
should be
if(clicked == gameButton[p] && turns < 10)
...unless you really want to change each button's text from X to O nine times each time a button is clicked.
But even fixing that typo is pointless. Why loop through to find a specific button when it doesn't matter which specific button it is? All the buttons have the same action handler, anyway, just nine separate copies of it, because you are creating nine identical copies each time around.
Instead, because all the buttons do the same thing, you should have one action handler for all the buttons. If you're not sure how that's done, you create it outside your button making loop and assign it to a variable, and then you put in that variable when you assign each button's action handler, e.g.
gameButton[i].addActionListener(myActionListener);

Categories

Resources