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.
Related
I'm working on a personal project where I'm trying to create Simon game in Java. It is essentially a memory game where the user has to repeat the sequence the computer generates. So, I created a basic CLI version of the game and now I'm looking to give it a GUI. I haven't worked with Java Swing before so I'm having some trouble replicating the same behavior in GUI form.
The structure of the CLI version looked something like this:
public static void main(String[] args) {
GameContext simon = new GameContext();
simon.start();
while (!simon.getRoundEndState()) {
simon.playSequence();
simon.pickColour();
}
}
Here's what the playSequence() method looks like. It essentially generates a number between 0 and 3 and keeps adding one number to the array each round if the player gets the previous one right.
public void playSequence() {
int rand = getRandomNumber(4);
computerSequence.add(rand);
for(int i:computerSequence) {
System.out.println(i);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
gameContext.setState(gameContext.getHumanPlayingState());
}
pickColour() method that asks the user for the pattern and checks if the pattern matches the one generated by the computer.
public void pickColour() {
boolean roundWon = true;
for(int i=0; i<gameContext.getSequence().size();i++){
Scanner input = new Scanner(System.in);
Integer userInput = input.nextInt();
if(userInput == gameContext.getSequence().get(i)) {
continue;
}
else {
System.out.println("Input mismatched the sequence");
roundWon = false;
break;
}
}
if (roundWon == true) {
score++;
gameContext.setState(gameContext.getComputerPlayingState());
} else {
gameContext.setRoundEndState(true);
System.out.println("Your score is: " + score);
gameContext.setState(gameContext.getInLobbyState());
}
}
Please note that I'm using the state pattern here and hence the change in states. I got the first part working where I need to light up the colors after the computer generates the the sequence. So now, playSequence() looks something like this:
public void playSequence() {
int rand = getRandomNumber(4);
computerSequence.add(rand);
gameContext.setState(gameContext.getHumanPlayingState());
}
And I added a mouse listener to the start button which looks something like this:
btnStart.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me) {
simon = new GameContext();
simon.start();
while (!simon.getRoundEndState()) {
simon.playSequence();
for(int i : simon.getSequence()) {
lightPanels(i);
Timer timer = new Timer(1000, e -> {
darkenPanels(i);
});
timer.setRepeats(false);
timer.start();
}
simon.pickColour();
}
}
});
I have 4 JPanels that now act as the input buttons. How do I change simon.pickColour() so that instead the asking the user for the correct sequence like it did in the CLI version, it would register the clicks made in the JPanels as the input.
It essentially generates a number between 0 and 3 and keeps adding one number to the array each round if the player gets the previous one right.
and
I have 4 JPanels that now act as the input buttons.
Why have 4 panels. Just have one panel that contains 4 buttons. You would then add an ActionListener to the button (not a MouseListner) to handle the clicking of the button.
The buttons would be created with code like:
for (int i = 1; i <= 4; i++)
{
JButton button = new JButton("" + i);
button.addActionListener(...);
panel.add( button );
}
The ActionListener code would then get the text of the button and add the text to an ArrayList to track the order the the buttons that have been clicked.
A working example of this approach of sharing an ActionListener for all the buttons can be found here: https://stackoverflow.com/a/33739732/131872. Note the "action command" will default from the text that is set on the button.
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()
}
});
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 am writing a Blackjack program using JFrame and trying to keep it as simple as possible. My JButton, jbHit works with a single click, however it overwrites the playersHand and playerSide slot with every click. I would like it to work with multiple clicks (3 clicks - since that is the max number of cards you can get after the first two are dealt) options It should count them so to speak so that the array index can record the card image. Here is my ActionListener code that I have so far. I am afraid I am stuck. Should I use some sort of for loop with an int i++?
//Hit Button ActionListener
jbHit.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if ( playerValue < 21 ) {
//Draw a card
Card c = deck.drawCard();
playersHand.add(c);
playerSide[2].setIcon( new ImageIcon( c.getFilename() ) );
}
//If playerValue > 21, bust
else if ( playerValue > 21 ) {
//Toggle Buttons
jbDeal.setEnabled(true);
jbHit.setEnabled(false);
jbStand.setEnabled(false);
jbDoubleDown.setEnabled(false);
message = "You bust.";
}
}
});
You could create an array of "action commands" and every time you click the button, the action command changes to the next. If you reach the end, set the index back to zero. Perhaps something like this:
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Action");
String[] commands = {"command1", "command2", "command3"};
button.setActionCommand(commands[0]);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton)e.getSource();
String cmd = btn.getActionCommand();
System.out.println("Command: " + cmd);
if(cmd.equals("command1"))
{
btn.setActionCommand(commands[1]);
System.out.println("Command 1 was pressed");
}
else if(cmd.equals("command2"))
{
btn.setActionCommand(commands[2]);
System.out.println("Command 2 was pressed");
}
else if(cmd.equals("command3"))
{
btn.setActionCommand(commands[0]);
System.out.println("Command 3 was pressed");
}
else
System.out.println("Something went wrong!");
}
});
panel.add(button);
frame.add(panel);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
If you are using Java 7 or later, you can replace the if/else with a Switch statement.
I believe you're looking for a logical flag based on an integer, for example:
if(cardsDealt < 3) {
// DoThings();
} else {
return;
}
Which would require you to do
cardsDealt++;
at the bottom of your button click handle.
If this is not what you're asking, please re-explain the question.
It sounds like you might be a little confused about how jbHit will be called. Realize that it will be called one complete time every time the mouse is clicked. It's not like it inherently knows that it is on the second or third click. Add a class member like int clickCount; that you increment at the appropriate point inside of jbHit. Then you can alter your method's response depending on the value of clickCount.
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.
}
}