Counting clicks in Java - java

introduceButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
int agex = Integer.parseInt(datafield.getText());
String box[] = {"paws quantity", "tail(cm)","paws qy"};
ArrayList<Integer> objdata = new ArrayList<Integer>();
for(int z = 0; z < 3;){
introduceButton
txtvar.setText(box[z]);
if (introduceButton.getModel().isEnabled() == true){
z++;
}
}
}
});
Hey guys, I try to count step by step how many times the button was pressed, to later navigate in an array.
The problem is that the variable z is not incrementing itself only by 1 after the button was clicked once but it reaches its max instantly after the first click. How can I fix it?
As well I tried to make a class with method counter but it the value remains 0:
class click{
int _incr;
public click(int incr){
_incr = incr;
}
public int count(){
_incr++;
return _incr;
}
}
...
introduceButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
int agex = Integer.parseInt(datafield.getText());
String box[] = {"paws quantity", "tail(cm)","paws qy"};
ArrayList<Integer> objdata = new ArrayList<Integer>();
click clck = new click(0);
txtvar.setText(Integer.toString(clck._incr));
/*for(int z = 0; z < 3;){
txtvar.setText(box[z]);
if(introduceButton.getModel().isEnabled() == true){
z++;
}
}*/
objdata.add(agex);
dog abstractdog = new dog(agex, agex, agex);
}
});

I made a example code.
Please have a look at it:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CountClick {
static int clicks = 0;
public static void main(String[] args) {
Frame f = new Frame("Button Example");
Button btn = new Button("Click me");
btn.setBounds(50, 100, 80, 30);
f.add(btn);
// set size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
// add listener
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// increase click int
clicks++;
// print clicks
System.out.println(clicks);
}
});
}
}
Note that the code in "addActionListener" is triggered each time you press the button. Therefore, unnecessary operations in it should be avoided. Initialisations should also be used with care in the "addActionListener" method.
Edit:
If you want to have a separate click class you can have a look at following code example:
class Click {
private int click = 0;
public void increaseClick() {
click++;
}
public int getClick() {
return click;
}
}
public class CountClicks {
public static void main(String[] args) {
Frame f = new Frame("Button Example");
Button btn = new Button("Click me");
btn.setBounds(50, 100, 80, 30);
f.add(btn);
// set size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
Click click = new Click();
// add listener
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// increase click int
click.increaseClick();
// print clicks
System.out.println(click.getClick());
}
});
}
}

Related

Determining the sequence of two clicks a user makes

public class GlassActionListener{
JButton first;
JButton second;
#Override
public void actionPerformed(ActionEvent e) {
if(first == null)
{
first = (JButton) e.getSource();
}
else
{
second = (JButton) e.getSource();
// do something
// clean up
first = null;
second = null;
}
}
}
public class GUIControl {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
showGUI();
}
});
}
public static void showGUI() {
JFrame frame = new JFrame("MyFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JButton glass1 = new JButton("glass1");
JButton glass2 = new JButton("glass2");
JButton glass3 = new JButton("glass3");
frame.getContentPane().add(glass1);
frame.getContentPane().add(glass2);
frame.getContentPane().add(glass3);
frame.pack();
frame.setVisible(true);
glass1.addActionListener(??);
glass2.addActionListener(??);
glass3.addActionListener(??);
// I want to store the first two clicks in these variables
from = "glassX";
to = "glassY";
puzzle.move(from, to);
}
The user will spill soda between the glasses. The first JButton the user clicks out of the three available determines the "from" initial glass and the second JButton the user clicks out of the three available determines the "to" destination glass.
How can I determine the specific two JButtons that the user clicked?
Everytime the user clicks two out of the three JButtons I want to store the string associated with those two JButtons in a "from" and "to" variable.
Is there any way to do this?
make an ActionListener and use JButton#addActionListener to add it to all three buttons. The event has a source field you can use.
ActionListener listener = new ActionListener() {
JButton first;
JButton second;
#Override
public void actionPerformed(ActionEvent e) {
if(first == null)
{
first = (JButton) e.getSource();
}
else
{
second = (JButton) e.getSource();
// do something
// clean up
first = null;
second = null;
}
}
};
glass1.addActionListener(listener);
glass2.addActionListener(listener);
glass3.addActionListener(listener);
Handling the logic inside the listener is a little dirty, but that's the idea.
firstbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//do something here first button is clicked
}
} );
you can add listeners to buttons like this.and use a class variable to track how many times the buttons are clicked.
eg:
public class GUIControl {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
showGUI();
}
});
}
public static void showGUI() {
JFrame frame = new JFrame("MyFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JButton glass1 = new JButton("glass1");
JButton glass2 = new JButton("glass2");
JButton glass3 = new JButton("glass3");
String from = "";
String to = "";
int click_count = 0;
glass1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(click_count ==0)
{
from = "glassX";
click_count = 1;
}else if(click_count ==1)
{
from = "glassY";
click_count = 0;
}
}
} );
glass2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(click_count ==0)
{
from = "glassX";
click_count = 1;
}else if(click_count ==1)
{
from = "glassY";
click_count = 0;
}
}
} );
glass3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(click_count ==0)
{
from = "glassX";
click_count = 1;
}else if(click_count ==1)
{
from = "glassY";
click_count = 0;
}
}
} );
frame.getContentPane().add(glass1);
frame.getContentPane().add(glass2);
frame.getContentPane().add(glass3);
frame.pack();
frame.setVisible(true);
// I want to store the first two clicks in these variables
}

first Calculator GUI in Java Eclipse

hey guys I am having trouble with my subtraction button and my division button not working, not sure what i did wrong.. Let me know if you can guide me so I can correct my code! - Ben :)
enter code here
package week07_Ben_Calculator;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class AdvancedCalculatorGUI implements ActionListener {
JFrame frame;
JPanel butPanel;
JTextField res;
JTextField res2;
int oper = 0;
int currentCalc;
double last;
int memory = 0;
public static void main(String[] args) {
// Invocation
EventQueue.invokeLater(new Runnable() {
// Override run
#Override
public void run() {
// Call constructor
new AdvancedCalculatorGUI();
}
});
}
// Create GUI
public AdvancedCalculatorGUI() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Calculator");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
// New text field
res = new JTextField();
res.setHorizontalAlignment(JTextField.RIGHT);
res.setEditable(false);
frame.add(res, BorderLayout.NORTH);
butPanel = new JPanel();
// 2nd text field
res2 = new JTextField();
res2.setHorizontalAlignment(JTextField.LEFT);
res2.setEditable(false);
frame.add(res2, BorderLayout.SOUTH);
// Create grid
butPanel.setLayout(new GridLayout(6, 3));
frame.add(butPanel, BorderLayout.CENTER);
// Add button
for (int i = 0; i < 10; i++) {
addButton(butPanel, String.valueOf(i));
}
//read button
JButton readButton = new JButton("Read");
readButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
memory = Integer.parseInt(res.getText());
res.setText("");
}
});
//store button
JButton storeButton = new JButton("Store");
storeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
res.setText(memory+"");
}
});
// Add button +
JButton additionButton = new JButton("+");
//additionButton.setActionCommand("+");
additionButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
oper = 1;
res2.setText(res2.getText()+"+");}
});
operAct additionAction = new operAct(1);
additionButton.addActionListener(additionAction);
// Subtract button
JButton subtractionButton = new JButton("-");
subtractionButton.setActionCommand("-");
subtractionButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
oper = 1;
res2.setText(res2.getText()+"-");}
});
operAct subtractionAction = new operAct(2);
subtractionButton.addActionListener(subtractionAction);
// Equal button
JButton eqButton = new JButton("=");
eqButton.setActionCommand("=");
eqButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
System.out.println(oper);
if (!res.getText().isEmpty()) {
int number = Integer.parseInt(res.getText());
if (oper == 1) {
int value = currentCalc + number;
last = value;
res.setText(Integer.toString(value));
res2.setText(res2.getText()+ "=" + Integer.toString(value));
} else if (oper == 2) {
int value = currentCalc - number;
last = value;
res.setText(Integer.toString(value));
res2.setText(res2.getText()+ "=" + Integer.toString(value));
} else if (oper == 3) {
int value = currentCalc * number;
last = value;
res.setText(Integer.toString(value));
res2.setText(res2.getText()+ "=" + Integer.toString(value));
} else if (oper == 4) {
if (number == 0)
res.setText("ERR");
double value = currentCalc / number;
last = value;
res.setText(Double.toString(value));
res2.setText(res2.getText()+ "=" + Double.toString(value));
}
}
}
});
// multiplication button
JButton mulButton = new JButton("*");
mulButton.setActionCommand("*");
mulButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
oper = 1;
res2.setText(res2.getText()+"*");}
});
operAct mulAction = new operAct(3);
mulButton.addActionListener(mulAction);
// division button
JButton divButton = new JButton("/");
divButton.setActionCommand("/");
divButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
oper = 1;
res2.setText(res2.getText()+"/");}
});
operAct divAction = new operAct(4);
divButton.addActionListener(divAction);
butPanel.add(additionButton);
butPanel.add(subtractionButton);
butPanel.add(eqButton);
butPanel.add(mulButton);
butPanel.add(divButton);
butPanel.add(readButton);
butPanel.add(storeButton);
frame.setVisible(true);
}
private void addButton(Container par, String nam) {
JButton b = new JButton(nam);
b.setActionCommand(nam);
b.addActionListener(this);
par.add(b);
}
#Override
public void actionPerformed(ActionEvent ev) {
String act = ev.getActionCommand();
res.setText(act);
System.out.println(ev);
res2.setText(res2.getText() + "" + act);
}
private class operAct implements ActionListener {
private int opt;
public operAct(int oper) {
opt = oper;
}
public void actionPerformed(ActionEvent ev) {
currentCalc = Integer.parseInt(res.getText());
oper = opt;
System.out.println(oper+" "+opt+" "+ currentCalc);
}
}
}
I have gone through your code; first I would suggest to make things simpler.
To make it simpler, first use getText() on the strings entry and then convert them into integers.
For both Input TextFields, distinctly save them in separate variables of respective data-types and then do whatever operations you need by defining their methods .
Instead of overriding the 'action performed method' every time, you can use the getAction Command. It will make your code more readable and you can find errors easier.

How to write a 'count' for buttons using e.getSource()?

I'm not sure how to write this line of code correctly, but what I'm trying to get is, " if the count of the e.getSource is 1, set it to 0".
Would that be written as:
if (count.(e.getSource()) == 1)
{
count = 0;
}
What would be the correct way of writing count.(e.getSource()) ?
e.getSource returns the object on which the Event initially occurred. You can get the JButton which triggers the event by casting it:
((JButton)e.getSource())
However, the button itself will not keep track of the number of times it has been clicked. You can just declare a variable to keep track of the clicks.
class DrawingSpace extends JPanel
{
private JButton btn;
private int count;
public DrawingSpace(){
count = 0;
btn = new JButton("Click me");
btn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if (count == 1)
count = 0;
}
});
}
}
To illustrate the point where you do not need a variable name to access the instance of the button being clicked. Take a look at this working example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CountClicks{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
JFrame frame = new JFrame("Counting individual clicks");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawingSpace());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Your customized Button class:
class MyButton extends JButton
{
private int numOfClicks; //Add additional property for JButton
public MyButton(String name){
super(name);
numOfClicks = 0;
}
public int getClicks(){
return numOfClicks;
}
public void setClicks(int clicks){
this.numOfClicks = clicks;
}
}
A container to contain your components for testing:
class DrawingSpace extends JPanel
{
private MyButton[] btn;
private JLabel lblDisplay;
public DrawingSpace(){
setPreferredSize(new Dimension(450, 100));
init();
}
private void init(){
btn = new MyButton[5];
ButtonHandler bh = new ButtonHandler();
for(int x=0; x<btn.length; x++){
btn[x] = new MyButton("Button " + (x+1));
btn[x].addActionListener(bh);
add(btn[x]);
}
lblDisplay = new JLabel("Watch here..");
add(lblDisplay);
}
private class ButtonHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
MyButton myBtn = (MyButton)e.getSource();
myBtn.setClicks(myBtn.getClicks()+ 1);
lblDisplay.setText(myBtn.getText() + " was clicked, it has gathered " + myBtn.getClicks() + " so far.");
}
}
}
An alternative solution if you want each Button to remembers how many times it has been clicked, you may create a customized JButton:
class MyButton extends JButton
{
private int numOfClicks; //Add additional property for JButton
public MyButton(String name){
super(name);
numOfClicks = 0;
}
public int getClicks(){
return numOfClicks;
}
public void setClicks(int clicks){
this.numOfClicks = clicks;
}
}
Now each of your customized buttons can remember the number of times each of them is being clicked:
class DrawingSpace extends JPanel
{
private MyButton btn;
public DrawingSpace(){
btn = new MyButton("Click me");
btn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
MyButton myBtn = (MyButton)e.getSource();
if (myBtn.getClicks() == 1)
myBtn.setClicks(0);
}
});
}
}

action listener doesnt work

I am new in java swing unfortunately when i want to set action listener to one of the button that it has to get the textArea content and send that to another class it doesn't work in a way that i expect and instead it works when i change the text area's content, i don't know What's happened?
first button i named Button and the same problem happened when i use another action listener inside the Button's action listener named Clac
here is my code:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class FFT_Main_Frame extends JFrame {
JLabel label;
JButton button;
TextPanel txtPanel;
JButton Button;
JLabel label1;
// JTextArea[] BoxArray;
makePolynomial mp;
JButton Calc;
Complex[] Nums;
Complex[] Result;
int input;
FFT_Main fft_main;
ShowResult shr;
public FFT_Main_Frame() {
Button.addActionListener(new ActionListener() {
// Test t;
// Integer content;
#Override
public void actionPerformed(ActionEvent arg0) {
try {
Integer content = new Integer(Integer.parseInt(txtPanel.getTextArea()));
input = content;
System.out.println(input);
// inputt=input;
mp = new makePolynomial(content);
setLayout(new FlowLayout());
add(mp);
// setLayout(new BorderLayout());
add(Calc);
Nums = new Complex[input + 1];
Calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
for (int i = input; i >= 0; i--) {
Nums[i] = new Complex(Double.parseDouble(mp.BoxArray[2 * (i + 1) - 1].getText()),
Double.parseDouble(mp.BoxArray[2 * i].getText()));
}
for (int i = 0; i <= input; i++) {
System.out.println(Nums[i]);
}
fft_main = new FFT_Main();
Result = new Complex[input];
Result = fft_main.Recursive_FFT(Nums);
shr = new ShowResult(Result);
setLayout(new BorderLayout());
add(shr, BorderLayout.CENTER);
System.out.println("Result\n\n");
for (int i = 0; i <= input; i++) {
System.out.println(Result[i]);
}
}
});
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "Please Enter Just Numbers! ", "Wrong Value",
JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
thanks for your help
You are using action listener wrong way here is an example how to use it
public FFT_Main_Frame() {
JButton Button = new JButton("Button");
Button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
// Code Here
}catch(Exception e) {
// Code Here
}
});
JButton Calc = new JButton("Calc");
Calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// Code Here
}
});
}
}
Some tutorials on how to use action listener
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
http://www.tutorialspoint.com/swing/swing_action_listener.htm

How can I get the source of the button and get this to work?

package game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public interface Listeners
{
static PatternGame game = new PatternGame();
InputGame game2 = new InputGame();
static class inst implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("inst".equals(e.getActionCommand()))
{
}
}
}
static class play implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("play".equals(e.getActionCommand()))
{
menu.mf.dispose();
PatternGame.gameStart();
}
}
}
static class exit implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("exit".equals(e.getActionCommand()))
{
System.exit(0);
}
}
}
static class input implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (InputGame.numOfClicks != 0)
{
InputGame.button = (JButton) e.getSource();
InputGame.button.setText("X");
InputGame.numOfClicks--;
}
else
{
if (InputGame.checkCorrect())
{
JOptionPane.showConfirmDialog(null, "Would you like another pattern?");
PatternGame.order++;
PatternGame.gameStart();
}
else
{
JOptionPane.showMessageDialog(null, "Incorrect!");
menu.start();
}
}
}
}
}
package game;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class InputGame implements Properties,Listeners{
public static JFrame gf = new JFrame();
public static JButton button = new JButton();
public static int height = 800;
public static int width = 600;
public static int gsize = 4;
public static int order =1;
public static Dimension size = new Dimension(height,width);
public static menu Menu = new menu();
public static GridLayout Ggrid = new GridLayout(gsize,gsize);
public static int numOfClicks =0;
public static int numCorrect=0;
public static int[][] input = new int[][]{
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0}
};
//public static Thread d;
public static void setup() {
gf.dispose();
gf = new JFrame();
gf.setLocation(300,100);
gf.setSize(size);
gf.setResizable(false);
gf.setLayout(Ggrid);
gf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PatternGame.clear();
blank();
gf.setVisible(true);
System.out.print(numOfClicks);
}
public static void blank()
{
for (int a =0;a<4;a++)
{
for (int b =0;b<4;b++)
{
button = new JButton("");
button.setActionCommand("");
button.addActionListener(new input());
gf.add(button);
}
}
}
public static void input()
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
String x = button.getText();
if (x.equals("X"))
{
input[a][b] = 1;
}
else if (x.equals(""))
{
input[a][b] = 0;
}
System.out.println(input[a][b]);
}
}
}
public static boolean checkCorrect()
{
input();
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (order == 1)
{
if (handlebars[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 2)
{
if (ys[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 3)
{
if (spaceShip[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 4)
{
if (flock[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 5)
{
if (percent[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 6)
{
if (square[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
}
}
return false;
}
}
Ok, this is my code. Now what I want the program to accomplish is for the program to display the blank screen(which I have done) then when the user clicks one of the buttons and it places a X on that button. Then after 6 clicks for the program to translate the pattern they put in to the input array, so I can compare the input array to the pattern array, and be able to tell the user if its correct or not and move on. What this program does now is it displays the blank screen then when a button is pressed it displays the X. I got it to check for one button but I don't know how to check for all of them. So how could I check each button for the text it holds.
You can call getComponents() on the parent container- whether panel, frame or window and then check if it is an instance of button, then check the text set on it like this:
Component[] comps = parent.getComponents();
for(Component c:comps){
if(c instanceof JButton){
JButton btn = (JButton) c;
String text = btn.getText();
//Use text for whatever, add it to an array or something
}
}
Hope you get the idea

Categories