Move icon from jbutton to jbutton - java

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...

Related

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.

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" )

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.

ActionListener on JButton creating "image" of a button in my frame?

I am creating a game of connect-4 using swing in java.
I have an array of 6 buttons which are used to input the move the player wants to make.
When I click a button, the ActionListener does what I want it to do, but also places an image of the most recently pressed button in the upper left of the screen. I say "image" of a button because it cannot be clicked. Here's my code:
public class ButtonPanel extends JPanel implements ActionListener{
ArrayList<JButton> buttonList;
public ButtonPanel(){
//set up the JPanel...
for (int i = 0; i < 7; i++){
buttonList.add(new JButton("" + i));
buttonList.get(i).addActionListener(this);
add(buttonList.get(i));
}
}
public void actionPerformed(ActionEvent e) {
for (JButton b : buttonList){
if(e.getSource() == b){
frame.playerMove = buttonList.indexOf(e.getSource());
return;
}
}
}
}
Here's what happens when I click the button 3
And when I click button 5
Does anybody know what's happening here, or how to fix it?
but also places an image of the most recently pressed button in the upper left of the screen. I say "image" of a button because it cannot be clicked.
Sounds to me like you are doing custom painting.
Make sure you are overriding paintComponent(), not paint();
Make sure the first statement in the paintComponent() method is super.paintComponent(...) so the background of your panel is cleared before the custom painting is done.
If this doesn't help, then post a proper SSCCE that demonstrates the problem.
In the future, make sure you post a SSCCE with all your questions.

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