Basically, what I have are 2 arrays. One array of JButtons 26 long, one array of Strings with each letter of the alphabet, and a for loop to create a button for each letter of the alphabet and insert it into the JButton array:
JButton[] buttons = new JButton[26];
String letters[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton(letters[i]);
panel.add(buttons[i]);
}
What I want to do is create an event for all the buttons. Whenever a button is pressed, whatever letter it coincides with will be set as the value for a String called guess.
So far I understand that I need to do something like this:
x.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Insert what I want to happen
}
});
My problem is with where I wrote x. I am not sure what to put there. I need this to work for all 26 buttons in the array...
Sorry if this seems obvious/simple. I am obviously new to java and I just don't understand how JButtons work and how to do this.
Define an ActionListener like shown below.
ActionListener aListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event){
//find the actioncommand and do what is required.
}
};
Associate this ActionListener to every button.
for(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton(letters[i]);
buttons[i].setActionCommand(letters[i]);
buttons[i].addActionListener(aListener);
panel.add(buttons[i]);
}
Just test the actionCommand which is a String value and compare it with a the letter, and do something.
x.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals("A")
// do something
else if (e.getActionCommand().equals("B")
// do soemthing
...
...
}
});
I prefer to use a switch though for cases like this.
public void actionPerformed(ActionEvent e){
String letter = e.getActionCommand();
switch(letter) {
case "A" : do something; break;
case "B" : do something; break;
case "C" : do something; break;
...
...
}
}
Related
I am currently coding a game and part of it consist of having different tiles to be put in a board. I plan on simulating this by having different buttons that will be used to represent the tiles with their corresponding coordinates. For example, one button will say "A1", "A2", etc. What I would like to accomplish, is to have the user click on the "A1" tile and then the button on the board that represents "A1" will change colors, is there any way to go through the buttons on the board and compare its text to the selection of the user? The following is what I used to create the board:
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
panel.add(buttons[r][c]);
}
}
This is what I wrote on the code of one of the tiles
JButton tile1 = new JButton ("A1");
tile1.setBounds(60,725,60,60);
frame.getContentPane().add(tile1);
tile1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String buttonText = tile1.getText();
// iterating through all buttons:
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++)
{
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText))
{
[i][j].setBackground(Color.BLACK);
}
}
}
}
} );
However, it is given me an error saying that there is an action expected after "{"
You may add an action listener to each of the JButton you are creating in the loop like below:
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code here
}
} );
Placing the listener in your code may look like
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String buttonText = button.getText();
// now iterate over all the jbuttons you have
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++){
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText)){
// you found a match here
// and you have the positions i, j
//
}
}
}
}
} );
panel.add(buttons[r][c]);
}
}
And you could store the the colors to be changed to in global static array, and use that array in your action listener.
For information on adding listener to the JButton, you may refer this thread How do you add an ActionListener onto a JButton in Java
Hope this helps!
You need listeners.
Implement ActionListener to your class. This will require you to add public void actionPerformed(ActionEvent e) {} to your class.
Every JButton you use should have an action listener.
Apply one like that:
JButton but = new JButton();
but.addActionListener(this);
Finally, in the actionPerformed method we added, you need to add something like that:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == but)
but.setBackground(Color.BLACK);
}
P.S. you can get a button's text value by the means of:
but.getText();
I have a gridLayout of JButtons. I'd like to distinguish every JButton from each other in the actionPerformed function.
I don't want to "name" each JButton. The user press a JButton randomly. Is there any method to know which button has been pressed?
It is possible?
[....]
tUsuariCPU = new JButton[mida][mida];
for (int i=0;i<size;i++){
for (int j=0;j<size;j++){
JButton temp = new JButton();
tUsuariCPU[i][j] = temp;
temp.addActionListener(this);
panel.add(temp);
}
}
}
public void actionPerformed(ActionEvent e) {}
[....]
}
If you wish to use a single ActionListener, you can check which Component fired the event by using the getSource button and comparing the instance to the JButton instances. Below uses a loop to loop over the 2D array of JButtons:
public void actionPerformed(ActionEvent e) {}
for ( int i = 0; i < tUsuariCPU.length; i++ ){
for ( int j = 0; j < tUsuariCPU[i].length; j++ ){
if ( e.getSource() == tUsuariCPU[i][j] ){
//do something
}
}
}
}
Alternatively, you can add a single ActionListener per button, or set the ActionCommand of the JButton and use this value to determine which JButton fired the event (e.getActionCommand().equals(myButton.getActionCommand()))
Here's the significant fragment of JFrame HidingOperationView:
hideBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0){
currentPixelInImageToHide.setVisible(true);
pixelOfToHideTable.setVisible(true);
nextStep.setVisible(true);
doAll.setVisible(true);
SteganographyOperationsUtil.hidingOperation(
getSelectedFirstImageModel(), copyOfToHide, posterisation);
}
});
nextStep.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0){
SteganographyOperationsUtil.key=1;
}
});
doAll.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0){
SteganographyOperationsUtil.key2=1;
}
});
key and key2 are my controlers in the class SteganographyOperationsUtil, when to wait within the loop:
int key = 1
int key2 = 0
Key controled by the button 'next step', so the loop would go only once forward, show the results in the JTables and wait for another click.
Key2 controled by the button 'doAll', which allows the loop run till the end without stopping.
in the hiding operation:
for (int x = 0; x < hiding.getWidth(); ++x) {
for (int y = 0; y < hiding.getHeight(); ++y) {
if(temp < header.length()){
...
}else{
while (key!=1){
sleep(100);
}
key=key2;
...
if (key2 == 0){
throwToTable(HidingOperationView.pixelOfToHideTable,
colorOfToHideBinary);
}
}
}
}
The problem is that the buttons that control the loop doesn't appear at all,
they only do, when i comment the line:
SteganographyOperationsUtil.hidingOperation( getSelectedFirstImageModel(), copyOfToHide, posterisation);
Maybe it's not best way to control the loop, but i have no clue, how to do it otherwise.
In short, I would like to accumulate a bunch of JButton's to an array, and create one ActionListener class for the array.
I'm trying to create a calculator, and all the numbered buttons, such as "6", are in a JButton array, because I would like to have it input the set number into a temporary int, and it would be easier to create one method, instead of 10. I also have 40 other buttons, that I would like to apply the same principal to, but in a different array, so it would be much faster and easier to put these into a couple of ActionListener methods where the buttons data is implemented to that method.
this is the code I have:
private JButton num0, num1, num2, num3, num4, num5, num6, num7, num8, num9;
private JButton numArray[] = {num0, num1, num2, num3, num4, num5, num6, num7, num8, num9};
public GUI(){
numArray.AddActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
}
});
}
You can consider the proposal of Newb Monad. However, you can use the same listener for all your buttons, as in the following example.
public static void main(String[] args) {
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
String text = ((JButton) e.getSource()).getText();
JOptionPane.showMessageDialog(null, text);
}
}
};
JPanel panel = new JPanel(new GridLayout(4,3));
JButton[] array = new JButton[10];
for (int i = 0; i < array.length; i++) {
array[i] = new JButton(String.valueOf(i));
array[i].addActionListener(listener);
panel.add(array[i]);
}
JOptionPane.showMessageDialog(null, panel);
}
You have the right idea. However, array objects do not have an addActionListener() method. You must add an action listener to each JButton individually. You can use the same listener for every button, but then you have to figure out which button was clicked inside the actionPerformed() method. IMO, a cleaner solution is to assign a separate listener to each JButton because that way each ActionListener can know which number is pressed without checking the source of the event. For example, you can create a NumberButtonListener class which takes an int as the only argument to its constructor. You can then create the JButtons and the corresponding NumberButtonListeners at the same time in a small loop.
This seems to work well for me.
I essentially loop through all of the buttons while checking it against the action (e.getSource()).
public void actionPerformed(ActionEvent e){
//loop through allbuttons to check if clicked
for(int i = 0; i < buttonArr.length; i++){
for(int j = 0; j < buttonArr[0].length; j++){
if(e.getSource() == buttonArr[i][j]){
//do stuff
}
}
}
}
I had a similar problem with a 2D array of buttons for a game of "Connect Four". I was able to use a for loop inside ActionListener to test which of my buttons had been pushed. The key was modifying the toString() method from my button class to supply the array element as a string:
Within the JPanel class definition:
...
discs = new RoundButton[6][7]; //my 2D array
...
public class RoundButton extends JButton {
...
public String toString() {
return "discs["+i+"]["+j+"]";
}
...
}
private class ButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
for (int i = 0; i < discs.length; i++){
for (int j= 0; j < discs[i].length; j++){
if (event.getSource() == discs[i][j]){
discs[i][j].setIcon(yellowDisc); //my particular action for that button
}
}
Sorry this is messy. I've never posted on here before.
there is possible to recognize whst btn is pressed with a unique eventListener?
i tried this code, but didn't work
ActionListener one = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (gr1.getCounter1() < 5) {
gr1.setCounter1(gr1.getCounter1() + 1);
if (arraybtn[1].isSelected())
test1.setIcon(play1a);
if (arraybtn[2].isSelected())
test1.setIcon(play1b);
if (arraybtn[3].isSelected())
test1.setIcon(play1c);
if (arraybtn[4].isSelected())
test1.setIcon(play1d);
if (arraybtn[5].isSelected())
test1.setIcon(play1e);
} else {
pn5.setText("No more cards");
}
}
};
thanks, !
use the getSource method from the ActionEvent object.
Your code would look like:
if (e.getSource() == arraybtn[1])
test1.setIcon(play1a);
if (e.getSource() == arraybtn[2])
test1.setIcon(play1b);
if (e.getSource() == arraybtn[3])
test1.setIcon(play1c);
if (e.getSource() == arraybtn[4])
test1.setIcon(play1d);
if (e.getSource() == arraybtn[5])
test1.setIcon(play1e);
to get the source of the event (i.e. the button that was pressed).
http://download.oracle.com/javase/1.4.2/docs/api/java/util/EventObject.html#getSource()
Your code above is in great need of being refactored. For instance you have an array of JButtons, why not a similar array of ImageIcons, then you could get rid of all those if blocks.
For instance:
ActionListener one = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (gr1.getCounter1() < 5) {
gr1.setCounter1(gr1.getCounter1() + 1);
for (int i = 0; i < arraybtn.length; i++) {
if (arraybtn[i] == e.getSource()) {
test1.setIcon(play1Icons[i]);
}
}
} else {
pn5.setText("No more cards");
}
}
};
And don't forget my recommendation in your other thread about further refactoring including creating a Player class, a Card class, a Deck class, a GameManager and so forth.
Regarding your question, "in this script i have play1a = hand.get(1).getImage(); if i do with another array like test1.setIcon(play1Icons[i]);, how i can define the variable?"
Is hand an ArrayList? One way to solve it is to do something like
test1.setIcon(hand.get(i).getImage());
or some variant on that.