Im adding buttons for a game but when removing the button in a loop it will only get rid of one button even though i added them in the same way
for(int i=0 - 1; i < 4 ; i++) {
panelButtonsub.remove(buttonBlankItems);
}
panelButtonsub.setLayout (new GridLayout (intLayout,intLayout));
revalidate();
repaint();
If you want to remove all the buttons in the panel you can use:
panel.removeAll();
If you want to remove the first 4 buttons in the panel you can use:
for (int i = 0; i < 4, i++)
panel.remove(0);
If you are trying to remove a certain type of component from the panel then you need to start at the end to remove the components:
int components = panel.getComponentCount();
for (int i = components - 1; i >= 0; i --)
{
Component c = panel.getComponent(i);
if (c instance of BlankButton)
panel.remove(i);
}
Where BlankButton is the component you created to represent the extra space by using panel.add( new BlankButton(...) ).
If you are trying to do something else then you need to clarify your question.
You must have distinct instances for each buttonBlankItems button. I guess that you are adding the same button 5 times and then you are trying to remove them.
Related
I have a problem with Java Swing, in particular with JLayeredPane.
I have a Deck manager which contains 4 JPanels in a JLayeredPane, but when i add an object to a Pane, then switch to another, the objects turns invisible at first, but when i pass with the mouse on, it returns visible even thoug i'm on a different Panel, here's the code:
deckSelector = new JLayeredPane();
Point origin = new Point(30, 0);
for (int i = 0; i < types.length; i++) {
Deck deck = new Deck(types[i], colors[i], origin);
deckSelector.add(deck, i);
decks[i] = deck;
}
to change
int j = 0;
boolean found = false;
for(int i=0; i<types.length; i++){
if(selectors[i].isSelected()){
deckSelector.setLayer(decks[i], 3);
found = true;
j=2;
} else
if(!selectors[i].isSelected()){
deckSelector.setLayer(decks[i], j);
if(found) j--;
else j++;
};
}
to add a card:
Card btnNewButton = new Card("Name Card");
add(btnNewButton);
I have a deck manager which is the main JLayerdPane, it has 4 decks overlayed, in which i can add cards, but when i switch from a deck to another, the card is still visible. Can anyone help me?
but when i pass with the mouse on
A mouseOver event is generate for the component. In the case of a JButton the border is changed, so the component needs to repaint itself. So that is why the component becomes visible.
The point of using a JLayeredPane is to see all the layers at the same time. Its just that some components will be stacked on top of others.
If you only want to see a single panel at a time, then you should be using a Card Layout. Then you can swap which panel is visible and any given time.
If you think you really need to use a JLayeredPane then try using setVisible(false) on the panel you don't want to see. This should prevent events from being passed to components on the panel in that layer.
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.
So... I'm making a Jeopardy game, and I'm experimenting with better ways of making and adding the buttons so that it looks better in the source code. So to start off, I have a CategoryClass that takes the parameters of a List of QuestionButtons (basically a JButton), the category name and so on. The only trouble I'm having is adding the buttons to a JPanel. Here's the code:
public void addCategoryButtons(JPanel pane) {
JLabel head = this.getCategoryHeading();
pane.add(head);
List<QuestionButton> buttons = this.getCategoryButtons();
for (int i = 0; i < buttons.size(); i++) {
pane.add(buttons.get(i).getButton());
}
}
And here's what I get. Note: the "Test" is the name of the category
As you can see, It shows the last Category I add instead of all of them. Any suggestions?
You need to set some layout manager, for example:
pane.setLayout(new GridLayout(buttons.size(), 1));
for (int i = 0; i < buttons.size(); i++)
{
pane.add(buttons.get(i).getButton());
}
You might want to use a Layout Manager for this task.
Im learning Java and Im creating a memory type game where you have to find two equal cards.
I have created a Window etc etc but my problem is adding multiple JButtons to it. (my cards are JButtons with icons). I have commented my code where my problem is.
//Get the images.
private File bildmapp = new File("bildmapp");
private File[] bilder = bildmapp.listFiles();
//My own class extending JButton
Kort[] k = new Kort[bilder.length];
for(int i = 0; i < bilder.length; i++){
k[i] = new Kort(new ImageIcon(bilder[i].getPath()));
}
//Later in my code:
int sum = rows * columns;
Kort[] temp = new Kort[sum];
//My function to randomize.
Verktyg.slumpOrdning(k);
//***********************//
//Trying to fill a array from K (which contains all cards) so my temp contains SUM cards and SUM/2 pairs
for(int i = 0; i < sum/2; i++){
temp[i] = k[i];
temp[i+sum/2] = k[i];
}
//Problem is that i only get SUM/2 (half of the cards) cards, not the 16 (8 pairs) i would like to add in this case
//SYNLIGT = VISIBLE.
for(int i = 0; i < sum; i++){
temp[i].setStatus(Kort.Status.SYNLIGT);
j.add(temp[i]);
}
Your code ends up adding each Kort object to the container twice, since the array temp contains two references to each Kort. When you add a Kort a second time, it moves to the second location. A Component can only appear in one place at a time.
You may not add the same widget twice. You need two separate buttons (but you may use the same icon on both).
You have to create sum JButton objects not sum/2; otherwise 2 buttons are the same and therefore only displayed once.
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.