JButton ActionEvent ActionListener - java

How I can control the actionListener of two JButtons pressed one after another?
I have got 2 JPanels. In each JPanel I've got a matrix of JButtons named tUsuari and tUsuariCPU
void actionPerformed(ActionEvent){
/****//
for (int i=0;i<tUsuari.length;i++){
for (int j=0;j<tUsuari.length;j++ ){
if (e.getSource()==tUsuari[i][j]){
System.out.println("hello");
for (int r=0;r<tUsuariCPU.length;r++){
for (int s=0;s<tUsuariCPU.length;s++ ){
if (e.getSource()==tUsuariCPU[r][s]){
System.out.println("bye");
parent.provaAtac(i,j,r,s);
}
}
}
}
}
}
}
When I pressed the JButton from the tUsuari it prints "hello", then I pressed a JButton from the other panel ant it doesn't print "bye".

Why so many nested loops? Split in 2 parts and fill panels individually... also, what is doing the method: parent.provaAtac(i,j,r,s); ?
for (int i=0;i<tUsuari.length;i++){
for (int j=0;j<tUsuari.length;j++ ){
if (e.getSource()==tUsuari[i][j]){
System.out.println("hello berlin");
}
}
}
for (int r=0;r<tUsuariCPU.length;r++){
for (int s=0;s<tUsuariCPU.length;s++ ){
if (e.getSource()==tUsuariCPU[r][s]){
System.out.println("bye madrid");
}
}
}

Your logic is wrong. If e.getSource()==tUsuari[i][j], yes, you indeed print out "Hello". But if that condition is true, there's no way that e.getSource()==tUsuariCPU[r][s] can be true, since e.getSource can't be both your tUsari button and your tUsuariCPU button at the same time. Conversely, if you presss the CPU button, you'll fail the first check for it being the tUsuari button, and therefore never get to the check for the CPU button. I suggest creating two different actionListeners, one for each button that does what you want the particular button to do.

Related

press buttons one by one

Hello I am new to java language,and I have created a JFrame in NetBeans IDE 8.2 .
The JFrame contains 8 buttons created diretly from swing palette.The case is that I am trying to open another JFrame form after clicking for example 5 buttons.
I know that for appearing another JFrame form it is used setVisible(true) method, in the last btnActionPerformed;
What I am asking is that how to make possible clicking 5 buttons and then appear the other Jframe form??If somebody knows what I am asking please help me to find the solution?
You could have a counter variable that each time you clic on a button it increases by 1 its value and when that value is 5, you call setVisible on your second JFrame.
However I suggest you to read The use of multiple JFrames, Good / Bad practice?. The general consensus says it's a bad practice.
As you provided not code, I can only show you that it's possible with the below image and the ActionListener code, however you must implement this solution on your own:
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (e.getSource().equals(buttons[i][j])) {
clics++;
sequenceLabel.setText("Number of Clics: " + clics);
if (clics == 5) {
clics = 0;
frame2.pack();
frame2.setLocationRelativeTo(frame1);
frame2.setVisible(true);
}
}
}
}
}
};

How to get specific ID for a JButton?

I'm trying to build a program that utilizes a 3x3 grid of buttons (using Java Swing), so I initialize it with a GridLayout and a loop to create the buttons:
panel.setBorder(BorderFactory.createEmptyBorder(3,3,5,5))
panel.setLayout(new GridLayout(3,3,10,10));
String[] buttons = {"Top Left", "Top Middle", "Top Right", "Middle Left", "Middle", "Middle Right", "Bottom Left", "Bottom Middle", "Bottom Right"};
for(int i = 0; i < buttons.length; i++) {
buttray[i] = new JButton(buttons[i]);
panel.add(buttray[i]);
buttray[i].addActionListener(this);
}
The buttons load just fine, but I do not understand how to use ActionListeners to differentiate between the buttons. When I check the paramString() method from the printout, each button gives the same modifier:
Top Left
ACTION_PERFORMED,cmd=Top Left,when=1431640106712,modifiers=Button1
Top Middle
ACTION_PERFORMED,cmd=Top Middle,when=1431640107566,modifiers=Button1
Top Right
ACTION_PERFORMED,cmd=Top Right,when=1431640107978,modifiers=Button1
Does this modifier value act as the button's identifier, and if so, how do I change it?
There are multiple ways to distinguish which button fired the ActionEvent:
Set/get the action command of each button (eg if (e.getActionCommand().equals("Top Left"))
Use == to compare instances (eg if (e.getSource() == buttray[0] ))
Get the text of the JButton (eg if (e.getSource().getText().equals("Top Left"))
Set/get the name of the JButton (eg if (e.getSource().getName().equals("Top Left"))
Add a different ActionListener to each button (in other words 1:1 Listener to button)
...and perhaps more ways will be added in the comments section below.
you already keep a track of the buttons by the array index i.e. buttray[i]. Use getSource()
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
for(int i=0;i<buttray.length;i++)
if(e.getSource()==buttray[i])
{
//code here
}
}

Specify array length to call

I'll explain my problem with an example:
buttons[0][0].addActionListener(new ActionListener() {
In the code above I'm adding a listener to my button in the upper left corner. Now I was wondering if there's an option, so I can call the entire line, something like [0][0-3], so I can add the same action listener for all 4 of them (I know 0-3 will not work since it says that -3 isn't specified in the array).
I know I can do this by adding a listener to the buttons one by one, but I have to make an if statement that when all the buttons have been pressed for example, it returns something.
You can't do this in one call, the easiest way is to iterate over them:
ActionListener toAddToThoseButtons = new ActionListener() { /*...*/ };
for (int i=0; buttons[0].length; i++) {
buttons[0][i].addActionListener(toAddToThoseButtons);
}

actionListener on a JButton created from vector

I've been searching the web for an answer to my specific basic problem, but was unable to find one.
I must say I am new to programming and I have to do this for school.
I have created an interface of a 6/49 lottery, where you have to click 6 JButtons, creating your "lucky" numbers. In my interface .java, I've created my buttons this way:
JButton b;
for (i = 1; i <= 49; i ++)
{
String s = String.valueOf(i);
b = new JButton(s);
if (i % 2 == 0)
b.setForeground(new Color(3, 121, 184));
else
b.setForeground(new Color(228, 44, 44));
choixNumero.add(b);
Note: "choixNumero" is a gridLayout ( 7 x 7 )
In another .java , I'm creating an actionListener to my JButton b, but that doesn't seems to work. Here is how I wrote it:
intProjet.b.addActionListener(new EcouteurCombinaison()); // where "intProjet" is my interface.java
and heres the code of my EcouteurCombinaison:
private int [] nums;
private int nbRestant = 6;
private class EcouteurCombinaison implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if (nbRestant > 0)
{
//nums[nbRestant] = indexOf(e)); //will have to find a way to get index of the button pressed
nbRestant --;
intProjet.valNbRestant.setText("" + nbRestant);
}
else
{
JOptionPane.showMessageDialog(null, "Vous avez choisis vos 6 numéros\n Cliquer sur Soumettre pour valider", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
}
So basically, I'm trying to add the index or the value of my JButton to the vector everytime a button is pushed. I will then send it to another .java
I've implemented others actionListener to my code and they work fine ( JButton, RadioButton, JComboBox ). I don't understand why nothing happens when I click my buttons.
I tried to make this as clear as possible, without pasting all the code.
Edit: The ActionListener works with the last button only ( 49 ). How can I make it listen to all b Buttons ?
intProjet.b refers to the last button created in your loop, so the result is expected. Instead, you can give each button its own instance of a listener, as shown here.
You are continually reassigning the value of b in that loop. When the loop completes, the last JButton to be created is assigned to it. You then bind an ActionListener to that button, but none of the others. I'm not sure why you expected a single invocation of intProjet.b.addActionListener() to add it to all JButtons.

Issues with JtextArea. JAVA

I have a GUI setup with with buttons on them and a JTextArea.
I also have an array of Strings with say size of 3.
What I want to do is use an action listener in a way that when the button called "next" is pressed, the JTextArea will then show the next cell in the array. The only problem is it displays the array at the same time. I need it to display the next cell when the button is hit
Can anyone help me with the code? Please and thank you.
final ActionListener m2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
arr = new String[3];
arr[0]= "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
arr[1]= "sssssssssssssssssssssss";
arr[2]= "xxxxxxxxxxxxxxxxxxxxx";
for (int i = 0; i<arr.length; i++){
text.append(arr[i]);
}
}
};
next.addActionListener(m2);
So the basic concept is. You need a index value to maintain the current index of the array that is being displayed.
From there, each time the user clicks next, you would increment the index and display the next value in the String
public void actionPerformed(ActionEvent e) {
currentIndex++;
// You need to decide what to do when we reach the end of the array...
String value = myStrings[currentIndex];
textArea.setText(value);
}
To create the button, use the JButton class. To respond to events, use the JButton#addActionListener() method. If you are having trouble, post what you have tried. Good luck!

Categories