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.
Related
I have problem with getting id of previous overlap of jTabbedPane.
ksiegiWieczysteTabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
KsiegaWieczystaPanel księgaWieczystaPanel = (KsiegaWieczystaPanel) ksiegiWieczysteTabbedPane.getSelectedComponent();
if(MainApp.main.showPytanieBox("Czy chcesz zapisać zmiany?")) {
if(księgaWieczystaPanel != null) {
księgaWieczystaPanel.zapiszWszystko();
}
}
}
});
Now I can get the actual clicked overlap but do I have chance to get the previous one? Assume I have 3 overlaps: A,B,C. Now if I click A it is easy to recognize that it is A by ksiegiWieczysteTabbedPane.getSelectedComponent() but when I click B is it possible to know that the previous overlap which was selected were A?
as far as i know this is how to set and get selected index in jtabbedPane
JTabbedPane pane = new JTabbedPane();
// this represents previously selected tab.
int selectedIndex = pane.getSelectedIndex();
//with this method you can change the selected index.
pane.setSelectedIndex(yourIndex);
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.
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...
I am trying to make a java GUI program "game".
There are five buttons, each with a character as the button caption. When a button is clicked, the caption of that button is exchanged with the right hand neighbor. If the far right button is clicked, then the far left button has that caption, so they both switch (it wraps around).
The goal is to have them arranged alphabetically, thus ending the game.
I can't think of an intuitive way to have the characters switching without having to make five buttons.
String str = "abcde"; // DEBUG ARGUMENT STRING
setCaptions(str);
Method that takes the string, creates a char array out of them, and creates buttons...
void setCaptions(String string){
char[] charArray = string.toCharArray();
ArrayList<Character> arrList = new ArrayList<Character>();
for (int x=0; x < charArray.length; x++) {
String str = Character.toString(charArray[x]);
btn = new JButton(str);
btn.setFont(myFont);
pane.add(btn, "LR");
btn.addActionListener(new SwitchAction());
arrList.add(str.charAt(0));
}
// check the order...
System.out.print(arrList);
if (arrList.get(0) < arrList.get(1)
&& arrList.get(1) < arrList.get(2)
&& arrList.get(2) < arrList.get(3)
&& arrList.get(3) < arrList.get(4)) {
lbl.setText("SOLVED");
}
}
ActionListener to switch the captions, which I can't figure out...
public class SwitchAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String a = btn.getText();
System.out.println(evt.getActionCommand() + " pressed"); // debug
// something goes here...
}
}
You should have an array or ArrayList of JButton, ArrayList<JButton> and put your buttons into this list.
Your ActionListener will need a reference to the original class so it can get a hold of the ArrayList. It can then iterate through the array list find out which button was pressed, which is its neighbor, and do its swap. So pass that reference in via a constructor parameter, and then in the actionPerformed method, call a getList() or similar "getter" method to get the ArrayList and iterate through it.
i.e.,
public class MyListener implements ActionListener {
private OriginalGui gui;
public MyListener(OriginalGui gui) {
this.gui = gui;
}
public void actionPerformed(ActionEvent e) {
JButton pressedButton = (JButton) e.getSource();
ArrayList<JButton> buttonList = gui.getButtonList();
// ... iterate through list and find button.
}
}
Ok, so here is the problem: Every time I click OK it should return the selected index number, right? The code below is returning ONLY the first index regardless of what I select. I set "cMenu.selected(1)" and it returns index 1, again, regardless of what I select.
Using JPanel, JButton, Choice
String[] menu = {"item 1" , "item 2", "item3"};
cMenu = new Choice();
cMenu.setBounds(0, 0, 75, 25);
for (int i = 0; i < menu.length; i++)
cMenu.add(menu[i]);
}
panel.add(cMenu);
final int menuSelection = cMenu.getSelectedIndex();
//Below is, of course, debugging
//Before asking, the button works it does say 0 or Hello World or whatever I want
//when clicked
OK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(menuSelection);
}
});
You need to recalculate the value for menuSelection when the 'OK' button is clicked; you're setting it once during instantiation of the Choice as shown below:
final int menuSelection = cMenu.getSelectedIndex();
If you do something like this, you should be able to see your value:
OK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int currentSelection = cMenu.getSelectedIndex();
System.out.println(currentSelection);
}
});
This will mean cMenu should be final, which is probably OK because you don't need to ever update that reference.
"OK it should return the selected index number". No, it should not. you're calling getSelectedIndex() once. So your int has the same value forever. You have to call getSelectedIndex() in your listener to get the new value.