Swing How to identify which jbutton user is clicking - java

i am creating a seats researvation system in java.....i have created an array of jbuttons. Is there any way i can identify which button is clicked or maybe i can get the index of the button when it is clicked.
for(int i=0; i<20; i++){
btn1[i] = new JButton(String.valueOf(i+1));
btn1[i].setPreferredSize(new Dimension(60, 30));
btn1[i].setBackground(Color.green);
panel.add(btn1[i]);
}

There are multiple ways to distinguish which button fired the ActionEvent:
Set/get the action command of each button (eg if (e.getActionCommand().equals("Button Name"))
Use == to compare instances (eg if (e.getSource() == buttray[0] ))
Get the text of the JButton (eg if (e.getSource().getText().equals("Button Name"))
Set/get the name of the JButton (eg if (e.getSource().getName().equals("Button Name"))
In your case you have a name.. so #4 should work inside your buttton event
btn1[i].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String bName = e.getSource().getText()
}
});

Related

How to activate a Jbutton by clicking another Jbutton

There are 7 buttons in my project. 6 of them are categories and RandomSoru button is the one which randomly chooses one of the categories. I want to access the chosen category. "r" is the random generator.
RandomSoru.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TriviaLinked tl = new TriviaLinked();
tl.insertAtBack(tl.CogHmap);
tl.insertAtBack(tl.TarihHmap);
tl.insertAtBack(tl.SporHmap);
tl.insertAtBack(tl.BilimHmap);
tl.insertAtBack(tl.FilmHmap);
tl.insertAtBack(tl.SanatHmap);
TriviaNode current = tl.root;
int n = r.nextInt(tl.sizeCounter());
for (int i = 0; i < n; i++) {
current = current.next;
}
if(current.hmap==tl.CogHmap)
JOptionPane.showMessageDialog(null,"Your Category is Cografya");
else if(current.hmap==tl.SporHmap)
JOptionPane.showMessageDialog(null,"Your Category is Spor");
....
Here is the Spor button
Spor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
......
My expectation was like
else if(current.hmap==tl.SporHmap)
JOptionPane.showMessageDialog(null,"Your Category is Spor");
Spor();
else if(current.hmap.....
One way is to add the 6 buttons to an ArrayList.
Then in the ActionListener of the random button you could do something like:
Use the Collections.shuffle(...) method to randomize the buttons in the List.
Then you get the first button from the List.
Finally you invoke the doClick() method on the button.

actionlistener for multiple jradiobutton

i have a multiple jradiobutton that is inside a for loop and i am trying to put listener on it and this is what i found:
Action listener for multiple radio buttons
Create two dimensional JRadioButton array like
JRadioButton[][] jRadioButtons = new JRadioButton[8][];
ButtonGroup bg = new ButtonGroup();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 8));
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
JRadioButton btn = new JRadioButton();
btn.addActionListener(listener);
btn.setName("Btn[" + i + "," + j + "]");
bg.add(btn);
panel.add(btn);
// can be used for other operations
jRadioButtons[i][j] = btn;
}
}
Here is single ActionListener for all JRadioButtons
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton btn = (JRadioButton) e.getSource();
System.out.println("Selected Button = " + btn.getName());
}
};
i kinda understand it but i still have few clarifications:
what's the purpose of two dimensional jradiobutton? i mean i kinda see that it is to set a name for the jradiobuttons but as far as my understanding goes, it's only for display. yes to confirm that that is the jradiobutton you've selected but i don't get what's the purpose of it in putting actionlistener
is the two dimensional jradiobutton really that necessary?
can i just use the name of jradiobuttons
to do something like this:
if(NameOfJRadioButton.isSelected())
{
//some procedures
}
^(i can't seem to convert that into code :/)
if so, how can i do it? or do you have any other suggestions on how to put listener for multiple jradiobuttons? thank you for any of your suggestions :)
On your first and second point, the reason for the two dimensional array is unknown as it is not your code, but is not necessary at all for the use of JRadioButtons. However it is useful to have all your buttons in some type of array, whether it be an arraylist, or a buttonGroup (swing list for buttons) for checking things with the buttons when an action is called. e.g. on your 3rd point, this array list would allow you to iterate through and check which buttons have been selected and act accordingly.
The purpose for the action listener is for executing an action when the user clicks on a button. The most general use for this is making it so the user is only allowed to select a certain amount of JRadioButtons or to disable them once they have been selected. e.g. at a character selection menu.

How do I make a program where I can keep adding 1 to a value when a button is clicked?

I know this sounds very basic, but I never really learned how to do this.
I know about for loops where you can just use for example:
for(int i=0; i<=10; i++)
System.out.println(i);
But that just prints out numbers from 0 to 10 with a gap of 1...which isn't what I'm looking for.
I'm looking for some code where the program starts at a value and adds 1 (or another number) whenever the a button is clicked.
I already have the code for the button and everything, but I have an empty ActionListener as I don't know what to place inside it.
In the ActionListener actionPerformed method write the following code:
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == button_name)
{
count_variable += 1;
}
}
Just add something like this.
int counter = 0;
JButton button = new JButton(" Click me ");
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
counter++;
}
});
This will make counter++ execute whenever the button is pressed. If you want another number, say 10, then just replace counter++ with counter+=10
**disclaimer**
Make sure that counter is accessible inside of ActionPerformed. You can do this by making it a field variable of an encapsulating class, making it a mutable object, and many other ways.

How can my program randomly press a button?

I'm trying to make a game where the button would light up and the user would have to press the button in a given time.
Currently, my program has 12 buttons that do something. I'm trying to make it so that these buttons are randomly called by the program. So far, I just have these for 12 buttons that just change the text when pressed by the user.
Now I need a way of making it so that they are randomly pressed the program itself and not the user. Any idea's on how this is done in java?
// **** Panels for buttons ****
JPanel panelButtons = new JPanel(); // making the panel for the buttons
panelButtons.setLayout(new GridLayout(3, 4)); // setting the layout of the buttons to 3x4 as shown above
b1 = new JButton(" ⃝"); // creating button and setting its default text
b1.setFont(fontText); // setting the font
b1.addActionListener(new ActionListener(){ // action listener to do something when pressed
public void actionPerformed(ActionEvent e) {
sendMessage(user + "1" ); // sends the name of the user that pressed the button and which button
String field1 = b1.getText(); // gets the text from the button and stores it in a String
if(field1 == " ⃝"){ // checks if the string is equal to an empty circle
b1.setText("⬤"); // if true then change to a full circle
}
else if (field1 == "⬤"){ // opposite of the above if statement
b1.setText(" ⃝");
}
}
});
panelButtons.add(b1); // adding the button to the panel
b2 = new JButton(" ⃝"); // creating button and setting its default text
b2.setFont(fontText); // setting the font
b2.addActionListener(new ActionListener(){ // action listener to do something when pressed
public void actionPerformed(ActionEvent e) {
sendMessage(user + "2" ); // sends the name of the user that pressed the button and which button
String field2 = b2.getText(); // gets the text from the button and stores it in a String
if(field2 == " ⃝"){ // checks if the string is equal to an empty circle
b2.setText("⬤"); // if true then change to a full circle
}
else if (field2 == "⬤"){ // opposite of the above if statement
b2.setText(" ⃝");
}
}
});
panelButtons.add(b2); // adding the button to the panel
You can create a list that holds your button. Use the random number generator to create a random number within the length of the list. Use that (random) index to modify the corresponding button.
Put your twelve buttons in an ordered collection.
Put your twelve corresponding actions in another ordered collection in form of a Consumer<JButton>'(useCallable`(and ignore the return) or just create something like that if you are not using java 8).
Perform a mapping from the Button collection to the action collection.
Create a class implementing ActionListener like this:
private static class Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
button2action.get((JButton)e.getSource()).accept(a);
}
}
pick up a random element from the value set of the map if you want to get random button pressed.
int randomIndex = new random().nextInt(button2action.entrySet().size());
Iterator<Entry<JButton, Consumer<JButton>>> iter = button2action.entrySet().iterator();
for (int i = 0; i < randomIndex; i++){
Entry<JButton, Consumer<JButton>> entry = iter.next();
}
entry.getValue().accept(entry.getKey());
add new button action pairs to the map if you want to add new buttons.

How do I get input from buttons I created using a loop?

I'm trying to make a simple calculator in Java using Swing, and I've created my buttons the following way:
//Our number keypad
public static JPanel numbers(){
//our panel to return
JPanel panel = new JPanel();
//Create and add 3x4 grid layout to panel
GridLayout gl = new GridLayout(3, 4);
panel.setLayout(gl);
//For creating and adding buttons to panel
for(int i = 0; i < 10; i++){
//Create a new button where the name is the value of i
String name = "" + i + "";
JButton button = new JButton(name);
//add action listener
button.addActionListener(handler);
//Add button to panel
panel.add(button);
}
return panel;
}
My question is how do I reference each specific button in my event handler? I can't think of a way to do this without having to manually create each button rather than using a loop.
Thanks.
In your listener, call event.getSource(), and that will return the button which has been pressed. Get the text of the button, and you have its number.
Or create a different instance of your handler for every button, and pass the value of the button (i) to the constructor of the handler. This last solution is cleaner, IMO, because it doesn't depend on the text of the button. If you replaced the text by an image, for example, the first technique wouldn't work anymore.
You can distinguish created buttons by adding the following inside handler:
String buttonText = ((JButton) e.getSource()).getText();
if (<text1>.equals(buttonText)){
//do the stuff
} else if (<text2>.equals(buttonText)){
//do the stuff
} else {
//do the stuff
}
Method #1: go through the child components of the parent JPanel (quite tedious, has to be rebuilt every time you modify the contents of that JPanel). Make sure they're JButtons by using an if . . instanceof clause.
Method #2: as you create them in that loop, add them to a List (or even better, a Map). I prefer a Map personally as it lets me customise the key for that specific JComponent
i.e.
HashMap<String, JComponent> buttonList = new HashMap<String, JComponent>();
for(. .) {
buttonList.put("nameForEachButton", button);
}
I recommend generating the button name based off of the loop counter. Either use your existing name value, or just set it to "button" + i;
Declare your buttons using an array.
JButton[] button = new JButton[9]; //outside the for loop
for (int i = 0; i < 10; i++) {
//put your code
button[i] = new JButton(name);
//your code
}

Categories

Resources