How to set image of a button randomly? - java

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.

Related

How to give each JButton in a 10 x 10 grid button layout a unique ID/name

I am trying to give each JButton from a 10 x 10 button layout (so 100 buttons) each unique name or ID or number so I can call them later. I made an ArrayList because that's what some other person did.
public ArrayList<JButton> myList;
//Some other code
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
button = new JButton();
button.addActionListener( al );
myList.add(button);
for(JButton button : myList)
button.setText("");
panel_1.add(button);
}
}
The program compiles but it doesn't run. It's showing error at
myList.add(button);
It's a null pointer exception apparently.
but I don't know why. Is it not adding the buttons to the ArrayList? Also how do I give each button a unique name or string?
The program compiles but it doesn't run. It's showing error at
The ArrayList is null because you didn't create an ArrayList object.
The code should be:
private ArrayList<JButton> myList = new ArrayList<JButton>();
Also how do I give each button a unique name or string?
There is no need to give the button a unique name. Its unique name is the "index" used to access the JButton in the ArrayList.
You probably don't even need the ArrayList.
Normally you add an ActionListener to the button. Then you can just use the getSource() method of the ActionEvent to get the reference to the button.

Minesweeper, how can i work on cells

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.

How to inactivate buttons that have not been pressed

I'm a very unexperienced programmer, so please bear with me for my lack of knowledge.
I have a program with 168 different buttons, which each count how many times they have been each pressed. After having either pressed or not pressed all of the buttons i need to inactivate and grey-out those which have not been pressed. So far I've used an 3D array to store how many times each button has been pressed, and have made a simple code:
if(a[0][0][0]<1)
{
ImageButton button_a1=(ImageButton) findViewById(R.id.button1a);
button_ca1.setEnabled(false);
button_ca1.setAlpha(6);
}
The only problem is that since each buttonID is different i have to do this 168 separated times. Is there any way to make this into a simple loop that doesn't take up over 1000 lines of code?
The program is written using Eclipse and is used for an Android app.
If all the buttons are in same layout, you can use getChildCount():
LinearLayout layout = setupLayout();
int count = layout.getChildCount();
View v = null;
for(int i=0; i<count; i++) {
v = layout.getChildAt(i);
if (v instanceof ImageButton) {
v.setEnabled(false);
v.setAlpha(6);
}
}
If not, simply create a Set, List or Array with all buttons and iterate over it:
List<ImageButton> buttons = new ArrayList<ImageButton>();
// be sure buttons is visible in the method
// when creating the buttons put them inside the list
Then in your method:
if(a[0][0][0]<1)
{
// disable all buttons
for(ImageButton button : buttons) {
button.setEnabled(false);
button.setAlpha(6);
}
}

GUI programming errors in CMD after compile

I'm trying to make a simple game which i made array of 9 buttons and for loops to display them and add then to ContentPane.
I'm trying to add images to the buttons in the for loops and I cannot get it to work./ any help?
String[] images = {"rainbow.jpg", "leprechaun.jpg", "potofgold.jpg"}; // IMAGES
// --- ICONS ---
Icon Icon1 = new ImageIcon("rainbow.jpg");
Icon Icon2 = new ImageIcon("leprechaun.jpg");
Icon Iconwin = new ImageIcon("potofgold2.jpg");
Icon blank = new ImageIcon("blank.jpg");
//creates array of buttons called tiles
JButton[] tile = new JButton[9];
They are the arrays and Icons.
for(int i = 0; i < tile.length; i++)
{
contentPane.add(tile[i]);
tile[i].setIcon(images[1]);
tile[i].addActionListener(this);
}
I'm trying to make it random image to the buttons. selects randomly I cannot get it to work I get error on tile[i].setIcon(images[1])
even when trying to just place it the 2nd image it give sme error
method setIcon in class AbstractButton cannot be applied to given types;
tile[i].setIcon(images[1]);
setIcon uses an Icon as its argument rather than a String
tile[i].setIcon(icon1);
Adding the buttons directly would be simpler
getContentPane().add(new ImageIcon(images[i]);

Initialize reference variables for many objects?

I'm having a little trouble building the grids for a Battleship game for my Java class. So far, I can easily make a for loop to add JPanel or JButton objects to the JFrame. However, my issue is that I'll need to use those Panels or Buttons again when playing the game (such as clicking on a button to see if your opponent put a ship on that square, et cetera). Is there a simple way in Java to initialize reference variables for a LOT of objects? Or will I have to declare all of them individually?
You could try a multi dimensional array of JPanels (or any other object). Create an array with the same size as your grid. The line below initializes an array with 5 rows and 5 columns.
JPanel[][] battleField = new JPanel[5][5];
Use nested for loops to create the panels in the array.
for (int rowIndex = 0; rowIndex < battleField.length; rowIndex++)
{
for (int cellIndex = 0; cellIndex < battleField[rowIndex]; cellIndex++)
{
battleField[rowIndex][cellIndex] = new JPanel();
}
}
If you want to reference the battleField array later on you would just make it into a instance variable.
For a battleship game, you most likely want to retrieve the location of a button after is has been clicked. You can create a hashtable using your buttons as keys and the point it is located at as a value.
HashMap<JButton, Point> buttonMap = new HashMap<JButton, Point>();
for (int x = 0; x < COLUMNS; x++)
{
for (int y = 0; y < ROWS; y++)
{
JButton btn = new JButton();
btn.addActionListener(this);
buttonMap.put(btn, new Point(x, y));
//then add the button to your container
}
}
The in your actionPerformed method you can convert the button to the point it is located at like this.
JButton btn = (JButton)actionEvent.getSource();
Point p = buttonMake.get(btn);
Of course you will need to properly handle error conditions such as source not being a button or the button not being in the map...
You can always extend JButton to keep track of the info you need. A simple example:
class MyButton extends JButton{
private MyGameInfo mygameInfo;
private int buttonId;
//More fields....
//Getters/Setters
}
Then instead of creating and adding JButton objects to your layout, create MyButton objects(which is also a JButton so your layout will not be effected) and use its extra functionality for your game logic.
For reference, here is a related matching game that uses a grid of buttons. This related answer demonstrates the application of the Model–View–Controller pattern to a simple game.

Categories

Resources