This question already has answers here:
How to set Action Listener to 3 buttons
(3 answers)
Closed 6 years ago.
As part of an exercise, I would like to design a program that displays a 9x9 grid of JButtons. When I click on a button, I would like that button to change in some way, like say originally it displays an 'o', but when you click on it, it displays an 'x', or maybe it changes colors, etc., while the other buttons remain unchanged.
However, I am not sure how to do this. I have created a 2D array of JButtons, and placed each on in a 9x9 GridLayout panel. I also set an ActionListener for each one. The problem is, I do not know how to change the color or text of only one button. Here is the short version of my program only displaying the relevant parts.
private JButton[][] t = new JButton[9][9]; //Declared much earlier in the program, right after the class declaration.
public void buildTile()
{
panelc.setLayout(new GridLayout(9, 9));
for(int r = 0; r < 9; r++)
{
for(int c = 0; c < 9; c++)
{
t[r][c] = new JButton("O");
t[r][c].setBackground(Color.BLACK);
t[r][c].setForeground(Color.WHITE);
t[r][c].addActionListener(new TileListener());
panelc.add(t[r][c]);
}
}
}
private class TileListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//Some code to change a specific button
}
}
How may I specify which button to perform some sort of aesthetic change to?
In the actionlistener e.getSource() will return the button you clicked
Related
I'am trying to do memory game. I have 12 buttons and 6 images.
I want to randomly set the image to the button. One image to 2 buttons.
ImageIcon[] icons = {icon1,icon2,icon3,icon4,icon5,icon6};
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16;
I know this Random r = new Random(); but no idea how can I use it here.
Edit:
U used this
for (int i = 0; i < buttons.length; i++)
buttons[i].setIcon( iconList.get(i) );
How can I set something like visible(false) of this icon?
Don't have 12 different variable names for your buttons. Instead create an Array to hold your 12 buttons.
Use an ArrayList to contain 12 Icons (two of each image).
Then you can use the shuffle(...) method of the ArrayList to randomly sort the icons.
Then you create a loop to assign each Icon to a button. Something like:
for (int i = 0; i < buttons.length; i++)
buttons[i].setIcon( iconList.get(i) );
Edit:
The above suggestion was to assign the Icons to the button when the button was created.
If you have a game where you have an empty Icon and then you display the Icon when the button is clicked then you need a different approach.
In your ActionListener code you will need to search the button array to see which button was clicked. Once you get the index of this button, then you get the matching Icon:
JButton button = (JButton)event.getSource();
for (int i = buttons.length; i < buttons.length;i++)
{
if (button = buttons[i];
{
button.setIcon( iconList.get(i) );
break;
}
}
The same ActionListener can be used for all buttons since the logic is generic.
I would like to create a minesweeper game. Firstly, this will work on buttons. I think I will work on two dimensional array, and there will be like boolean array that will present where are bombs, for example if booleanArray[0][4] is true, there is a bomb.
Now, how can I implement this in my buttons? I can set Names on these buttons, and then if I click some button, then I will get the name from this div. For example when i click first button, i will get "00" name, then i will get first letter "0" and second letter "0" and parse it to int. And this will be the indexes from my previous booleanArray, in this case it will be booleanArray[0][0].
So, can I do this another, better way, instead of that?
This is the way I will be creating the buttons:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
JButton button = new JButton("");
button.setPreferredSize(new Dimension(50, 50));
button.setName(Integer.toString(i) + Integer.toString(j));
}
}
EDIT
I will have a two dimensional Array, that will reflect my buttons:
and now, how can I check if I hit the bomb after I click for example in the first button?
Just hold a two dimensional array of buttons,
JButton[][] myButtons = new JButton[10][10];
which you use to draw them and they all call the same method with their value
for (int x=0; x<10; x++){
for (int y=0; y<10; y++){
myButtons[x][y] = new JButton("0");
//add to page, or do it elsewhere
myButtons[x][y].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed(x,y);
}
});
}
}
Then a call to yout method selectionButtonPressed() will tell you what button has been pressed, you can take action and even make changes to the button with myButtons[x][y].whatever()
That is one way but you should create the String of the name by using something like:
button.setName(i + ":" j);
This will make it easier to parse out the two values as you can just use the String.split(...) method.
Another option might be to create a HashTable with the JButton as the key and then use a Point object (representing the row/column) as the value Object of the HashTable. Then you just use the get(...) method of the HashMap to retrieve the Point for the clicked button.
Another option is to extend JButton and add two parameters (row, column) when creating the button. Then you also add getRow() and getColumn() methods.
Either of this approaches will keep the logic simple and you only need to create a single ActionListener to be used by all the buttons.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am quite new to Java. I decided to code tic-tac-toe as practice (from scratch).
Anyway, I am trying to have the 'JLabel label' change when I click; going from 1, then 2, etc. Eventually, it will change to something other than numbers. But, for now, it works for a test.
The 'System.out.println("Number of clicks: " + mouseIn);' works fine, and produces the output I want. A picture of the console and JFrame/JPanel/JLabel can be seen here:
(The little 1 in the JFrame is the JLabel. I want to match what is output in the console.
I have googled, and searched, and tried everything I know (which ain't much!) and I can't get the dang thing to work...I'm just asking for some guidance. Main method just includes building of JFrame/Panel.
Code below:
From the main class, called (namone.java [named it this for my own reasons]):
public void run(JPanel p) //Takes panel from main method {
for(int i = 0; i < ticList.length; i++){
ticList[i] = new JButton(buttonText); //For every position in
//ticList[], create a JButton object
p.add(ticList[i]);
ticList[i].setPreferredSize(new Dimension(140,140));
ticList[i].addMouseListener(mouse); //Load mouseListner
}
//Set mouseIn to click value in MouseEvents Class
int mouseIn = mouse.getClicks();
//Set text value to text value in MouseEvents class
text = mouse.getText();
//Output...
System.out.println("Number of clicks: " + mouseIn); //For testing
String mouse = Integer.toString(mouseIn); //Convert mouseIn value (from MouseEvents.java) to mouse
JLabel label = new JLabel(); //New JLabel
p.add(label); //Add label to screen
label.setText(mouse); //Set the text of the label to value of mouse
System.out.println(mouse); //For testing
//So I can see if it's working (clicks wise)
}
And then the code from my MouseEvents.java class:
public class MouseEvents extends namone implements MouseListener {
int clicks = 1;
String text = "first"; //For testing purposes
public namone game = new namone();
public int getClicks(){
return clicks;
}
public String getText(){
return text;
}
public int intToString(){
Integer.toString(clicks);
return clicks;
}
#Override
public void mouseClicked(MouseEvent e) {
clicks++;
intToString();
JPanel p = new JPanel();
text = "" + clicks;
game.run(p);
}
As I said. I am very new to Java and I'm trying to learn how to develop applications with it. I'm sure it's caused by my own ignorance.
Thanks.
Assuming that mouse is of type MouseEvents that you write, one possibility is that you need to pass mouse.getText() to your call to label.setText(.).
Regardless, the way you set up your game is a bit strange to me. What is the reason to create a brand new JPanel every time someone clicks? Why not maintain the original JPanel and update it instead. I personally would attach a custom ActionListener to each JButton that runs some code everytime the button is clicked. If this ActionListener is an inner class, it can also view variables in the scope that the JButton is defined.
I am working on a lab, it's a connect four game. I'm having trouble specifically with basic concepts like how classes communicate with each other, how to use private instance variables, how to use an ArrayList, how to compare JLabels or set them as something comparable...
To give a brief breakdown I have four classes GUI, Game, Player, Name
I can create the GUI by using two four loops, the game is a grid with 7 columns of 6 pieces. The pieces are images,
JLabel Piece = new JLabel("images/blank.png");
for example to denote an empty spot.
The GUI is based on a JFrame, single content pane and four panels, one for a header which indicates who is playing and who won, another for the 7 buttons accompanying the 7 rows, the grid itself of the possible places to be played and then a button panel which gives you the option to replay.
I'm lacking in a lot of concepts. For instance, the replay button shouldn't appear until the game has ended.
I don't understand how to use an ArrayList. I tried to use
ArrayList<ArrayList<JLabel>> myList = new ArrayList<ArrayList<JLabel>>();
So when I create the GUI by running two for loops like so
For ( c = 0 ; c<8 ; c++) {
ArrayList<JLabel> column = new ArrayList<JLabel>();
For ( r = 0 ; r<7 ; r++) {
ArrayList<JLabel> row = new ArrayList<JLabel>();
JLabel empty = new JLabel("images/blank.png");
row.add(empty);
}
column.add(row);
}
Even this small step I've already got confused.
I know the two for loops above are not correct specifically the ArrayList.
I don't know how to create the arraylist and then use them.
using something like
column.get().get();
myList.get().get();
to get a specific piece.
I don't know how to pass that to an argument so that for example if I push on button 7 for column 7, and no pieces have been played yet, I can start from the lowest area column 7 row 6 and update that to a played piece, red or yellow for the appropriate player.
This is vague and I doubt I'll get anywhere but I am desperate for help. There isn't much time available from the TA's / Teacher and I believe I am lacking significantly to be able to finish this project.
I understand how it works/what I have to do in words but in terms of applying Java code...
I'd appreciate any help.
OK first off you should use an array of Enums. ArrayLists are intended for lots of items and that can have rapidly changing numbers. Arrays are intended to house data in a grid of some sorts. Since you are using a static board, use arrays! They are also much less memory-intensive. Example:
//Note you should use [column][row] as that is common practice.
States[][] grid = new States[7][6];
//And initialize it:
for(int i = 0; i < grid.length; i++)
for(int o = 0; o < grid[i].length; o++)
grid[i][o] = EMPTY_JLABEL;
Then declare an enum (this is a new class) (NOTE: replace FULL_PLAYER_ONE_JLABEL and FULL_PLAYER_TWO_JLABEL with the JLabels that have the image for each.):
public enum States {
FULL_PLAYER_ONE(FULL_PLAYER_ONE_JLABEL), FULL_PLAYER_TWO(FULL_PLAYER_TWO_JLABEL), EMPTY(EMPTY_JLABEL);
//The image of the appropriate state.
private JLabel label;
//Enum constructors must be private
private States(JLabel label) {
this.label = label;
}
public JLabel getLabel() {
return label;
}
}
In your GUI, have a JButton that is only added to the frame when the game is over. Also add a button to indicate when each column has been clicked by the player.
JButton button = new JButton();
//Initialize JButton and add to frame...
//Anytime before the frame is set to visible:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/* Perform tests for for what should happen.
For example test whose turn it is then call a method to add a piece to that column. Then call a checker to see if someone has won. If so, display the replay button, otherwise do nothing (allow other player to move).
*/
}
}
I am coding an image puzzle game and one part of the code is to compare the pieces the user has selected to the pieces of the correct image.
Each image piece is already added to a JButton as an ImageIcon.
An identifier is required to differentiate each image piece apart and also for comparision.
I am setting a setName() for each JButton created as the identifier.
The comparison starts when the user releases the mouse after he drags the puzzle pieces from the original 3x3 grid where the shuffled pieces are to the other 3x grid for matching.
I have problems removing the error from the comparison if statement.
I got the comparison idea from this SO thread - link
private JButton[] button = new JButton[9];
private JButton[] waa = new JButton[9];
private String id;
private int cc;
private String id2;
private int cc2;
// setName for each of the 9 buttons in the original 3x3 grid being created
// which stores the shuffled puzzle pieces
for(int a=0; a<9; a++){
button[a] = new JButton(new ImageIcon());
id += Integer.toString(++cc);
button[a].setName(id);
}
// setName for each of the 9 buttons in the other 3x3 grid
// where the images will be dragged to by the user
for(int b=0; b<9; b++){
waa[b] = new JButton();
id2 += Integer.toString(++cc2);
waa[b].setName(id2);
}
// check if puzzle pieces are matched in the correct place
// compare name of original 'button' array button with the name of 'waa' array buttons
button[a].addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent m){
if(m.getbutton().getName().equals (waa.getName())){
}
else{
JOptionPane.showMessageDialog(null,"Wrong! Try Again.");
}
}
}
In your mouseReleased event m.getButton() is returning the mouse button that was clicked. You'll want to do something more like this that will get you closer:
if (m.getComponent().getName().equals(waa.getName())) {
m.getComponent() returns the Component object (your JButton) that the event was fired from. From there you can do the comparison with the getName approach you are using.
There's an additional issue in that your waa variable is an array. I'm not sure how you want to compare them, whether running through the arrays and making sure the index and names match, but that's an additional issue you need to look into.
JButton uses an ActionListener to trigger notifications back to your program to indicate when it's been triggered. This allows the button to respond to different types of event, including the mouse, keyboard and program triggers.
As apart of the action API, you can supply an action command for each button. See JButton#setActionCommand
Basically you would integrate it in a simular way to your mouse listener...
public void actio Performed(ActionEvent evt) {
if (command.equals(evt.getActionCommand()) {...}
}
Depending on your requirements, it might even be easier to use the Action API
The problem you are actually having is waa is an array, therefore, it doesn't have a getName method. I'm also unclear as to why you have two arrays of buttons?