How can my program randomly press a button? - java

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.

Related

Swing How to identify which jbutton user is clicking

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()
}
});

Java generate next set of chronologic buttons when button is pressed in GUI

This is my first post on stackOverflow and I would love to hear about the proper etiquette for posting question on this website.
My problem in a brief couple statements:
I want to be able to change the numbers of a label in a Java GUI by clicking a button. As I click the button the 15 labels on the screen should go from 1-15, to 16-31. And with every click the labels should generate the labels with the next 15 numbers.
Images:
Currently what happens is when I press the "Next" button is the following:
GUI screen prior to pressing the next button
After the next button is pressed, the screen changes to the following
The problem I face is, that after I press the next button again, the screen does not change and stays with the labels from 16-31.
Objective: To have a functional "Previous" and "Next button that orderly refreshes the GUI with the previous 15 or next 15 labels, respectively.
The following is the code for the event handlers for the "Previous" and Next" buttons:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
int updateLabelBy = 16;
int multiplyingFactor = 1;
int sum = multiplyingFactor * updateLabelBy ;
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//When this button is pressed, JPanel2,3,4,5 will all show the next instance of solutions
if (NumOfExplanations > 15)
{
//Clearing out JPannels
jPanel1.removeAll();
jPanel1.updateUI();
jPanel2.removeAll();
jPanel2.updateUI();
jPanel3.removeAll();
jPanel3.updateUI();
jPanel4.removeAll();
jPanel4.updateUI();
jPanel5.removeAll();
jPanel5.updateUI();
//To update the label index numbers
//int multiplied = multiplyingFactor * updateLabelBy;
for ( int i = 16; i < NumOfExplanations; i++ )
{
JLabel label = new JLabel( "Exp " + i );
label.setSize(100,35);
label.setMaximumSize(new Dimension (140,40));
label.setMinimumSize(new Dimension (100,30));
label.setFont(new Font("Serif", Font.BOLD, 15));
jPanel2.setLayout(new BoxLayout(jPanel2, BoxLayout.Y_AXIS));
jPanel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 15, 0));
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jPanel2.add(label);
}
}
else
{
final JFrame parent = new JFrame();
JButton button = new JButton();
button.setText("This document only contains " + NumOfExplanations + " explanations" );
parent.add(button);
parent.pack();
parent.setVisible(true);
parent.setSize(400,200);
parent.setLocationRelativeTo(null);
}
}
This is quite easy to do. To change the text displayed on a button, just do
btn.setText( "New message" )

evaluating button clicks java

I have the following code:
for (int i = 0; i < dynamicVariable; i++) {
String tmpString = myArray[i];
JToggleButton tButton = new JToggleButton(tmpString);
myJPanel.add(tButton);
tButton.addActionListener(this);
}
JButton go = new JButton("go");
myJPanel.add(submit);
Where I create x amount of buttons and add them to my panel. What I now need to do is, when the user selects the correct buttons and hits go. I evaluate all the selected buttons. If they are all right, then print true, otherwise print false. If they select all the correct answers except one, then it should evaluate to false. I just have no idea how to evaluate each button selected inside the actionPerformed() method.
Put all the buttons into a List or array, then iterate over this when the go button is clicked
private List<JToggleButton> listOfButtons;
//...
listOfButtons = new ArrayList<>(dynamicVariable);
for (int i=0; i<dynamicVariable;i++){
String tmpString= myArray[i];
JToggleButton tButton = new JToggleButton (tmpString);
listOfButtons.add(tButton);
myJPanel.add(tButton);
tButton.addActionListener(this);
}
JButton go= new JButton("go");
myJPanel.add(submit);
//...
// ActionListener of go button
public void actionPerformed(ActionEvent evt) {
for (JToggleButton btn : listOfButtons) {
if (btn.isSelected()) {
// Evaluate the state, set some flags
// get funky tonight
}
}
// Evaluate the final state once you know what
// buttons are actually selected
}
You should first map the correct values for each button, then if the user clicks on the Go button, then iterate over the buttons, checking for each button if it is correctly toggled on or off.
In short:
First we define the correct answers as a map with each toggle button bound to a boolean indicating whether the statement is correct or not;
Then we add all toggle buttons to the panel;
Then we add a listener to the Go button, which determines whether the selected button is correctly pressed or left unpressed.
Here's the code:
// Put all values into a map. If the mentioned fruit has the mentioned
// color, then the answer is correct.
private Map<JToggleButton, Boolean> correctAnswers = new HashMap<JToggleButton, Boolean>() {{
put(new JToggleButton("A strawberry is red"), true);
put(new JToggleButton("A banana is blue"), false);
put(new JToggleButton("A lemon is yellow"), true);
put(new JToggleButton("An orange is orange"), true);
}};
void init() {
for (JToggleButton button : map.keySet()) {
// button.setActionListener(this); // The toggle buttons themselves
// do not need to have a listener, do they? Only when the user clicks
// "go", then the buttons should be evaluated, right?
myJPanel.add(button);
}
JButton submitButton = new JButton("go");
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
boolean wrong = false; // It's all good now, until a wrong
// answer is found.
// Iterate over all entries of our map.
for (JToggleButton button : this.buttons.keySet()) {
// Check if the selection state of the toggle button is
// equal to whether the answer is yes or no.
if (button.isSelected() != this.buttons.get(button)) {
// A button is pressed while it should not be pressed
// OR vice versa. Let's mark that at least one button
// is incorrect.
wrong = true;
}
}
// We found at least one incorrect button.
if (wrong) {
// DO SOMETHING
}
}
});
myJPanel.add(submitButton);
}
I haven't tested this code, but it should work.

Move icon from jbutton to jbutton

I setup a gridlayout, with 16 buttons in the center. I placed an icon on the first button.
How would I loop through, and when the user select the next button on the grid, it moves the icon from old position to new position?
private ArrayList<JButton> grid = new ArrayList<JButton>();
JPanel gridBtnPanel = new JPanel();
gridBtnPanel.setLayout(new GridLayout(4, 4));
for(int i = 0; i <= 16; i++){
JButton innerButton = new JButton();
gridBtnPanel.add(innerButton);
grid.add(innerButton);
}
ImageIcon player= new ImageIcon("player.JPG");
//starting position
grid.get(0).setIcon(player);
//wanting to move to next button when I select the near by button
for(int i = 0; i < grid.lastIndexOf(theifPerson); i++){
grid.get(i).setIcon(null);
}
Any help would be great.
Thank you.
You could add actionlisteners to the buttons, and once a button is pressed it searches through all the buttons to find one with a non-null icon, and switches the pressed button's icon with the non-null icon
Presumably you have some kind of ActionListener attached to each JButton so you know when the user clicks on one, if you don't, take a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener
When the user clicks on a button, the actionPerformed method is called. Here you want to determine which button was clicked, set the icon property of the last button to null and set the icon of the clicked button...
This will require you to know the last "active" button
private int activeButton;
private ImageIcon player;
//...
grid.get(0).setIcon(player);
activeButton = 0;
Then you simply want to update the current state...
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source instanceof JButton) {
JButton clicked = (JButton)source;
grid.get(activeButton).setIcon(null);
clicked.setIcon(player);
activeButton = grid.indexOf(clicked);
}
}
For example...

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