My program has one button, and the other one is a JTextField. The action listener for the button and the textfield are different. I'm using:
textfield.addActionListener(this);
button.addActionListener(this);
... inside my constructor.
They both do the same actionListener. How can I call their respective methods?
You are implementing ActionListener in the class of both components. So, when an action happens, actionPerformed method of the class is called for both of them. You can do following to separate them:
1-Create a separate class and implement ActionListener interface in it and add it as a actionListener for one of the components.
2-In actionPerformed method, there is a parameter with ActionEvent type. Call getSource method of it and check if it returns the object of JTextField or JButton by putting an if statement and do separate things accordingly.
Obviously both components share an ActionListener. If you want to determine which component generated the ActionEvent, invoke getSource(). And from there, you can typecast (if needed), and then invoke that particular component's methods.
For me the easiest way to do what is asked is the following:
textfield.addActionListener(this);
button.addActionListener(this);
...
public void actionPerformed(ActionEvent e){
if( e.getSource().getClass().equals(JTextField.class) ){
System.out.println("textfield");
//Código para el textfield
}
if( e.getSource().getClass().equals(JButton.class) ){
System.out.println("JButton");
//Código para el JButton
}
}
When an action listener is activated, because someone click your button, the method actionPerformed is called. As you havae set this as an action listener, you should have a method actionPerformed in your class. This is the method called in both cases.
Something like:
class MyClass implements ActionListener {
public MyClass() {
...
textfield.addActionListener(this) ;
button.addActionListener(this) ;
...
}
public void actionPerformed(ActionEvent e) {
// This is the method being called when:
// - the button is clicked and
// - the textfield activated
}
}
Though if you have not given your sample code, but I can understand what is there.
Here is an example of how to add listener to any JComponent. (Dont try to run this code!!!)
import java.awt.Button;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class EventListeners extends JFrame implements ActionListener {
TextArea txtArea;
String Add, Subtract, Multiply, Divide;
int i = 10, j = 20, sum = 0, Sub = 0, Mul = 0, Div = 0;
public void init() {
txtArea = new TextArea(10, 20);
txtArea.setEditable(false);
add(txtArea, "center");
Button b = new Button("Add");
Button c = new Button("Subtract");
Button d = new Button("Multiply");
Button e = new Button("Divide");
// YOU ARE DOING SOMETHING LIKE THIS
// THIS WILL WORK, BUT CAN BE A BAD EXMPLE
b.addActionListener(this);
c.addActionListener(this);
d.addActionListener(this);
e.addActionListener(this);
add(b);
add(c);
add(d);
add(e);
}
public void actionPerformed(ActionEvent e) {
sum = i + j;
txtArea.setText("");
txtArea.append("i = " + i + "\t" + "j = " + j + "\n");
Button source = (Button) e.getSource();
// you can work with them like shown below
Button source = (Button) e.getSource();
if (source.getLabel() == "Add") {
txtArea.append("Sum : " + sum + "\n");
}
if (source.getLabel() == "Subtract") {
txtArea.append("Sub : " + Sub + "\n");
}
if (source.getLabel() == "Multiply") {
txtArea.append("Mul = " + Mul + "\n");
}
if (source.getLabel() == "Divide") {
txtArea.append("Divide = " + Div);
}
}
}
UPDATE
You should do something like below
Button b = new Button("Add");
Button c = new Button("Subtract");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// implement what is expected for b button
}
});
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// implement what is expected for c button
}
});
// and so on...
// but yes we can improve it
Just set different ActionCommands on each component.
In the actionPerformed method you can check the ActionCommand of the event:
private static final String TEXT_CMD = "text"; // or something more meaningful
private static final String BUTTON_CMD = "button";
...
textfield.setActionCommand(TEXT_CMD);
textfield.addActionListener(this);
button.setActionCommand(BUTTON_CMD);
button.addActionListener(this);
...
public void actionPerformed(ActionEvent ev) {
switch (ev.getActionCommand()) {
case TEXT_CMD:
// do textfield stuff here
break;
case BUTTON_CMD:
// do button stuff here
break;
default:
// error message?
break;
}
}
Related
I'd like to change value of my variable "name" when I select right button and click "ok" on my JRadio Frame.
For example when i select r1 and hit "ok" I'd like to have name=="Fast" in the entire package.
package Snake;
public class Radio extends JFrame {
private int delay = 100;
private String name;
JTextField t1;
JButton b;
JRadioButton r1, r2;
JLabel l;
public void selectSpeed() {
b = new JButton("Ok");
r1 = new JRadioButton("Fast");
r2 = new JRadioButton("Slow");
l = new JLabel("Speed: ");
ButtonGroup bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
add(b);
add(r1);
add(r2);
add(l);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
} else {
name = "Slow";
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});
if (name == "Fast") { // and now name is empty...
delay = 50;
}
if (name == "Slow") {
delay = 500;
}
setLayout(new FlowLayout());
setSize(400, 400);
setVisible(true);
}
public int setSpeed() {
selectSpeed();
return delay;
}
}
If you want to change the delay on button click, You need to write the logic in the ActionListener itself because the code you have written to change the delay will run only once and that too at the start of the execution of your program and at that time, name will be empty.
Then when ever you click the button, It will only execute the ActionListener So delay will not be changed at any time. And other mistake you are making is that you are comparing Strings in wrong way. For more information take a look at it How do I compare Strings in Java?
To change delay dynamically on button click, you need to change it in the ActionListener.
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
delay = 50;
} else {
name = "Slow";
delay = 500;
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});
You need to do it in your JRadioButton listener. For example, like here, at first you change the variable "name" and later in the current listener you check conditions, but you need remember that to compare the strings you need to use "equals":
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
} else {
name = "Slow";
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
if (name.equals("Fast")) { // and now name is empty...
delay = 50;
}
if (name.equals("Slow")) {
delay = 500;
}
} // name=="Slow" when r2 is selected
});
Well I see my mistake now, Thank you.
But it still does not work the way I like. I'd like to change the "delay" value every time I select right button on JRadio and hit "ok" and with this changed value I'd like to go to the other class.
There is the code of a class where I need value of "delay":
package Snake;
public class Gameplay extends Paint implements KeyListener, ActionListener {
private Timer timer;
private int q = 0;
Radio radio = new Radio();
public Gameplay() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(radio.selectSpeed(), this); //here i need flexible "delay" value
timer.start();
}
Is there a way to know if a JButton was clicked consecutively? Consider my code.
public void actionPerformed(ActionEvent arg0) {
String bucky[] = new String[2];
String firstclick = null, secondclick = null;
clicks++;
if (clicks == 1) {
bucky[0] = firstclick;
} else if(clicks == 2) {
bucky[1] = secondclick;
if (bucky[0] == bucky[1]) {
//This JButton was clicked twice in a row.
}
}
This code checks the entire number of times my JButton was clicked and displays the message "This button was clicked twice in a row". What I want is to compare two clicks from that button and see if they come one after the other rather than counting the number of clicks made. Or is there a built-in function that does this?
Just use a field remembering what the last clicked button was:
private JButton lastButtonClicked;
...
someButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (lastButtonClicked == e.getSource()) {
displayError();
}
else {
lastButtonClicked = (JButton) e.getSource();
doSomething();
}
}
});
Of course, you'll have to do the same thing with all the other buttons.
I have a different approach to your problem:
You want to not allow the user to press the same button in some group of buttons twice in a row.
You're solutions so far have tried to check which button was pressed last, and then warn the user if the same button has been pressed in a row.
Perhaps a better solution is to create a construct that simply doesn't allow the user to press the same button twice in a row.
You can create your ButtonGroup like object that selectively disables the last button pressed, and enables all the other buttons.
You would give this class an add(AbstractButton btn) method to allow you to add all the buttons that you wish to behave this way to it. The button would then be added to an ArrayList.
You would give it a single ActionListener that listens to all the buttons. Whenever the actionPerformed method has been pressed, it enables all of the buttons, and then selectively disables the last button pressed.
For instance consider my class below:
public class NoRepeatButtonGroup implements ActionListener {
private List<AbstractButton> btnList = new ArrayList<>();
public void add(AbstractButton btn) {
btnList.add(btn);
btn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent evt) {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
((AbstractButton) evt.getSource()).setEnabled(false);
}
public void reset() {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
}
}
If you create a single object of this in your class that creates the buttons, and add each button to the object of this class, your code will automatically disable the last button pressed, and re-enable it once another button has been pressed.
You could use it like so:
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
NoRepeatButtonGroup noRepeatButtonGroup = new NoRepeatButtonGroup();
JButton yesButton = new JButton(new YesAction());
noRepeatButtonGroup.add(yesButton);
buttonPanel.add(yesButton);
JButton noButton = new JButton(new NoAction());
noRepeatButtonGroup.add(noButton);
buttonPanel.add(noButton);
JButton maybeButton = new JButton(new MaybeAction());
noRepeatButtonGroup.add(maybeButton);
buttonPanel.add(maybeButton);
For example, here is a proof of concept minimal runnable example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class NoneInARowBtns {
private static void createAndShowGui() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
NoRepeatButtonGroup noRepeatButtonGroup = new NoRepeatButtonGroup();
int buttonCount = 5;
for (int i = 0; i < buttonCount; i++) {
JButton btn = new JButton(new ButtonAction(i + 1));
noRepeatButtonGroup.add(btn);
buttonPanel.add(btn);
}
JOptionPane.showMessageDialog(null, buttonPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class ButtonAction extends AbstractAction {
public ButtonAction(int i) {
super("Button " + i);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand() + " Pressed");
}
}
class NoRepeatButtonGroup implements ActionListener {
private List<AbstractButton> btnList = new ArrayList<>();
public void add(AbstractButton btn) {
btnList.add(btn);
btn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent evt) {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
((AbstractButton) evt.getSource()).setEnabled(false);
}
public void reset() {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
}
}
When the above program runs, and when the second button is pressed, you will see that it is disabled:
Then when the 3rd button has been pressed, the 2nd is re-enabled, and the 3rd one is disabled:
And etc for the 4th button....
A global variable arrau of booleans, one for each button, set true on first click, set false or second, sjould do it
I have written a program with two buttons for a Java class that I am taking. I now need to count and display the number of clicks each button gets. I have some code for counting clicks but am fairly certain that it is wrong.
The error I have is "identifier expected", how can I fix this?
Here is my updated code:
import java.awt.*;
import java.awt.event.*;
public class FinalProj1 extends Frame implements ActionListener,WindowListener {
FinalProj1() {
setTitle("Click Counter");
setSize(400,400);
show();
}
public static void main(String args[]) {
Frame objFrame;
Button objButton1;
Button objButton2;
TextField count = new TextField(20);
TextField count2 = new TextField(20);
Label objLabel;
Label objLabel2;
objFrame= new FinalProj1();
objButton1= new Button("Agree");
objButton2= new Button("Dissagree");
objLabel= new Label();
objLabel2= new Label();
objLabel2.setText("Mexican Food Is Better Than Chineese Food");
objButton1.setBounds(110,175,75,75);
objButton2.setBounds(190,175,75,75);
objLabel2.setBounds(80,95, 250,25);
objFrame.add(objButton2);
objFrame.add(objButton1);
objFrame.add(objLabel2);
objFrame.add(objLabel);
}
private int numClicks = 0;
private int numClicks2 = 0;
objButton1.addActionListener(this)
objButton2.addActionListener(this)
public void actionPerformed(ActionEvent e) {
numClicks++;
numClicks2++;
count.setText("There are " + numClicks + " who agree");
count2.setText("There are " + numClicks2 + " who dissagree");
}
}
The error he's having ("identifier expected") is specified in the previous question.
You're getting this error because these two lines of code are outside any method or initializer block:
objButton1.addActionListener(this)
objButton2.addActionListener(this)
Put them in your constructor after creating the two controls and you should be fine.
One approach is to have one actionListener for every button. Try this:
objButton1.addActionListener(myFirstActionListener)
objButton2.addActionListener(mySecondActionListener)
ActionListener myFirstActionListener = new ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
numClicks++;
}
}
ActionListener mySecondActionListener = new ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
numClicks2++;
}
}
First you should add the action listeners to each button,(explained above).
However,you are incrementing both counts whenever you press one of the two buttons,which is wrong.
So you should modify your action performed method to smthg like this
public void actionPerformed(ActionEvent e)
{
if(e.getSource().equals("Agree"))//if you push the button agree,increment only numClicks
numClicks++;
if(e.getSource().equal("Disagree"))//if you click on disagree,increment numClicks2
numClicks2++;
count.setText("There are " + numClicks + " who agree");
count2.setText("There are " + numClicks2 + " who dissagree");
}
EDIT-Btw,are you implementing the windows listener methods?You have to.
Jeroen's answer is correct for solving your compilation error, so definitely do that first before you proceed.
In regards to your actual counters, the problem you're having is that both your numClicks and numClicks2 variables are being incremented simultaneously whenever either objButton1 or objButton2 is clicked. This is because they are being handled by the same event handler method. You have two choices:
Option 1: let the single event handler method handle both clicks, but distinguish between the two, and only increment the relevant counter, like so:
public void actionPerformed(ActionEvent e){
if(e.getSource() == objButton1){
numClicks++;
} else {
numClicks++;
}
// the rest if your method
}
Option 2: specify separate event handlers for each button, something like this:
objButton1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
numClicks++;
// display your message to user
}
});
objButton2.addActionListener(new ActionListrner(){
public void actionPerformed(ActionEvent e){
numClicks2++;
// display your message to user;
}
});
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.
Okay so I am making a 2d array of JToggleButtons. I got the action listener up and going, but I have no way to tell which button is which.
If I click one, all it returns is something like
javax.swing.JToggleButton[,59,58,19x14,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#53343ed0,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=]
Is there anyway to stick some sort of item or number in the button object to associate each button?
And then when the button is clicked I can retrieve that item or number that was given to it?
Here is my button generator code. (How could I make "int l" associate (and count) to each button made, when it is called, it will return that number, or something along those lines.
JToggleButton buttons[][] = new JToggleButton[row][col];
int l = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
buttons[i][j] = new JToggleButton("");
buttons[i][j].setSize(15,15);
buttons[i][j].addActionListener(new e());
panel.add(buttons[i][j]);
l++;
}
}
ActionListner
public class e implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
System.out.println(source);
}
}
variable "source" is what I use to get my data, so how can int l, be returned through "source" (as its unique value for the unique button clicked) as a button is clicked?
Thanks,
-Austin
very simple way is add ClientProperty to the JComponent, add to your definition into loop e.g.
buttons[i][j].putClientProperty("column", i);
buttons[i][j].putClientProperty("row", j);
buttons[i][j].addActionListener(new MyActionListener());
rename e to the MyActionListener and change its contents
public class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JToggleButton btn = (JToggleButton) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
EDIT:
for MinerCraft clone isn't required to implements ony of Listeners, there is only about Icon, find out that in this code (don't implement any of Listeners anf remove used ItemListener)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonsIcon extends JFrame {
private static final long serialVersionUID = 1L;
private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ButtonsIcon t = new ButtonsIcon();
}
});
}
public ButtonsIcon() {
setLayout(new GridLayout(2, 2, 4, 4));
JButton button = new JButton();
button.setBorderPainted(false);
button.setBorder(null);
button.setFocusable(false);
button.setMargin(new Insets(0, 0, 0, 0));
button.setContentAreaFilled(false);
button.setIcon((errorIcon));
button.setRolloverIcon((infoIcon));
button.setPressedIcon(warnIcon);
button.setDisabledIcon(warnIcon);
add(button);
JButton button1 = new JButton();
button1.setBorderPainted(false);
button1.setBorder(null);
button1.setFocusable(false);
button1.setMargin(new Insets(0, 0, 0, 0));
button1.setContentAreaFilled(false);
button1.setIcon((errorIcon));
button1.setRolloverIcon((infoIcon));
button1.setPressedIcon(warnIcon);
button1.setDisabledIcon(warnIcon);
add(button1);
button1.setEnabled(false);
final JToggleButton toggleButton = new JToggleButton();
toggleButton.setIcon((errorIcon));
toggleButton.setRolloverIcon((infoIcon));
toggleButton.setPressedIcon(warnIcon);
toggleButton.setDisabledIcon(warnIcon);
toggleButton.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (toggleButton.isSelected()) {
} else {
}
}
});
add(toggleButton);
final JToggleButton toggleButton1 = new JToggleButton();
toggleButton1.setIcon((errorIcon));
toggleButton1.setRolloverIcon((infoIcon));
toggleButton1.setPressedIcon(warnIcon);
toggleButton1.setDisabledIcon(warnIcon);
toggleButton1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (toggleButton1.isSelected()) {
} else {
}
}
});
add(toggleButton1);
toggleButton1.setEnabled(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
}
Just add the row and column data to each listener. You could add an explicit constructor, but I suggest adding a little method (which may have more added to it later).
buttons[i][j].addActionListener(e(i, j));
...
private ActionListener e(final int i, final int j) {
return new ActionListener() {
// i and j available here
...
(In JDK8 you should be able to use a lambda to reduce the syntax clutter.)
And then renaming it with a better name.
I made a minesweeper game and ran into a similar problem. One of the only ways you can do it, is to get the absolute location of the clicked button, then divide that by the x and y between buttons, so for me it was
if ((e.getComponent().getX() != (randx) * 25 && e.getComponent().getY() != (randy) * 25) &&bomb[randx][randy] == false) {
This code was to check if the area had bombs. So I had 25 x and y difference between location of bombs. That will just give you a general idea on how to do this.
I believe: (x - x spacing on left side) / buffer - 1 would work.
Instead of 'e.getSource()' you can always call 'e.getActionCommand()'. For each button you can specify this by:
JButton button = new JButton("Specify your parameters here"); /*you get these from getActionCommand*/
button.setText("title here"); /*as far as I remember*/