For loop to create button array not displaying properly in JPanel - java

So i'm creating an array of buttons that is supposed to display and 8,8 grid, instead it displays very small buttons spreading across the window (31 buttons in a row for two rows then two more buttons on the third). If I replace:
gamePanel1.add(buttons[a][b]);
with:
frame.add(buttons[a][b]);
... it display correctly but when initialising the array, I have to resize the window to see the buttons as it does not fit to contents.
Here is the code to create the buttons:
contentPane.setLayout(new BorderLayout());
JPanel gamePanel1 = new JPanel();
buttons = new JButton[boardsize][boardsize];
mineBoard = new int[9][9];
for (int a = 0; a < boardsize; a++)
for (int b = 0; b < boardsize; b++) {
buttons[a][b] = new JButton("");
buttons[a][b].setBounds(30+gridsize*a,30+gridsize*b,gridsize,gridsize);
gamePanel1.add(buttons[a][b]);
buttons[a][b].addMouseListener(new MouseListener(a,b));
setx(a);
sety(b);
settried(false);
setmine(false);
}
contentPane.add(gamePanel1, BorderLayout.CENTER);
Can anyone tell me how I might fix this or show me how with this code I may use a different layout - i tried grid layout for the buttons but could not get it working at all.

First create a Panel as:
JPanel panel=new JPanel();
Then set the layout as
panel.setLayout(new GridLayout(8,8));
Then using a for loop create and add the buttons and the buttons will be displayed in eight by eight grid. Thanks.

Related

Adding JButtons in for loop

JAVA Swing Problem
I want to create a list of JButtons based on a list of strings, which represents the button text.
In my first step, I collect my data for the button texts from an external text file. This data is stored in the data variable.
List<String> data = ReadFile("texts.txt")
Now I want to create the list of JButtons, named buttons. There I set their text and their Bounds. The Bounds are relative to the index, so the buttons are placed below each other. Finally, I add the button to the frame and to the buttons list.
List<JButton> buttons = new ArrayList<>();
for (int index = 0; index < data.size(); index++) {
JButton button = new JButton();
button.setText(data.get(index));
button.setBounds(0, index*50, 100, 50);
add(button);
buttons.add(button);
But when I execute this, the last Button ends big, the first ones also disappear when I don't hover over them, but that's based on the fact, that the last button ist placed above:
Picture of the executed script
The last button has the size of the frame, doesn't matter, if I resize the frame:
Picture of the resized screen
I hope someone can help me or tell me where I can find help. Thanks.
the last Button ends big, the first ones also disappear when I don't hover over them,
That is because by default the content pane of the JFrame uses a BorderLayout. When you add a component to the BorderLayout the button is added to the CENTER. However, only a single component can be added to the CENTER, so only the size/location of the last component added is managed by the BorderLayout.
Don't attempt to set the size/location of your components manually. It is the job of a layout manager to do this. In your case you can use a couple of panels with different layout so align your button in a column on the left. Something like:
JPanel buttonPanel = new JPanel( new GridLayout(0, 1) );
for (int index = 0; index < data.size(); index++) {
JButton button = new JButton();
button.setText(data.get(index));
button.setBounds(0, index*50, 100, 50);
//add(button);
buttonPanel.add( button );
buttons.add(button);
}
add(buttonPanel, BorderLayout.LINE_START);
Try the above code and you will notice that the buttons are all the same size, but the size keeps changing as the height of the frame changes.
So to prevent this resizing we need to allow the button to be displayed at their preferred height by using an additional layout manager:
//add(buttonPanel, BorderLayout.LINE_START);
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(buttonPanel, BorderLayout.PAGE_START);
add(wrapper, BorderLayout.LINE_START);
Read the Swing tutorial on Layout Manager for more information and examples.

Java Button Action Command

I'm creating a simple Minesweeper game in Java. Size 9x9.
I create an array of JPanels and an array of buttons; I add each button to its respective JPanel. then i add the JPanels to the JFrame.
How do i distinguish between each button on the action event?
Here's some of my code:
int gridx = 9;
int gridy = 9;
JButton[] buttons = new JButton[gridx*gridy];
JPanel[] jpanels = new JPanel[gridx*gridy];
public Minesweeper(){
super("Minesweeper");
setLayout(new GridLayout(9,9));
JPanel panel = new JPanel();
int i = 0;
for(i = 0; i<gridx*gridy; i++){
jpanels[i] = new JPanel();
buttons[i] = new JButton();
buttons[i].addActionListener(buttonEvent);
jpanels[i].setLayout(new GridLayout(1,1));
jpanels[i].add(buttons[i]);
add(jpanels[i]);
}
//buttons[67].setEnabled(false);
setSize(300,300);
setVisible(true);
}
The only way i can think about doing this is adding text to the button like so:
buttons[i] = new JButton(i);
Then calling getActionCommand() but i dont want text to show up on the button. Any other ideas?
You can use AbstractButton#setActionCommand.
In your loop:
buttons[i].setActionCommand(i+"");
Then you'll get i back when you use getActionCommand
Note I did mention in a comment on another answer that I would create a new class Mine which extends JButton which I believe to be a better and more complete solution. This however gets the job done rather quickly.

Need a layout? How it should be used?

So im writing a small test program for fun replicating a inventory from games like minecraft and runescape. Basically a frame with another one inside it, and pictures of your items in it, and a scroll bar to scroll down through all the stuff you have in your inventory. The "Stuff" i would have in my inventory would be buttons added later on with their own functionality, so you can scroll through vertically and see all the "stuff." Right now i have some test buttons being added to deomsntrate the error. Basically i want the buttons to be 100,100 and for them to be in a row of 4, and go onto the next column. I though GridLayout would be the best choice, but it seems to add more rows after being added into a scrollpane. Well heres the code skimmed down:
public class inventory extends JFrame{
public static void main(String[] args){
new inventory();
}
JPanel mainInv = new JPanel();
JScrollPane sp;
public inventory(){
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit tk = this.getToolkit();
setLocation(tk.getScreenSize().width/2-getWidth()/2, tk.getScreenSize().height/2-getHeight()/2);
setLayout(null);
mainInv.setSize(getWidth()-10, 1000);
mainInv.setBackground(Color.blue);
mainInv.setLayout(new GridLayout(8,4));
sp = new JScrollPane(mainInv, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
sp.setMaximumSize(new Dimension(400,400));
sp.setBounds(5, 5, 500-10, 500-130);
JButton[] testButs = new JButton[100];
for(int i = 0; i < 50; i++){
testButs[i] = new JButton("Test Button " + i);
testButs[i].setSize(100,100);
mainInv.add(testButs[i]);
}
add(sp);
setVisible(true);
}
}
With GridLayout the number of rows is the dominating factor.
If you have 8 rows and 4 columns that can only fit 48 buttons, if you try to add a 49th button it will create a 5th column not a 9th row.
You can solve your problem by setting up the GridLayout with more rows.

Second row of gridbaglayout scrolling out of container

I am trying to achieve a layout similar to that of a carousel. It needs to have images added horizontally with a checkbox field in the second row. I have a panel within a jscrollpane and individual images are added to the panel as labels. Please see screen shot.
screenshot
When I scroll the pane , the first row containing the images stays well within the panel..but if you notice the second row of checkboxes , it scrolls out of the panel. Here is the code ...
JLabel lab1=new JLabel();
for (int ii=0; ii<imageFiles.length; ii++) {
GridBagConstraints constraint = new GridBagConstraints();
lab1 = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
constraint.gridx = ii;
constraint.gridy =0;
jPanel9.add(lab1,constraint);
}
for (int ii=0; ii<imageFiles.length; ii++) {
GridBagConstraints constraint1 = new GridBagConstraints();
constraint1.anchor = GridBagConstraints.SOUTH;
chkbox = new Checkbox("asdasdada");
constraint1.gridx = ii;
constraint1.gridy =1;
jPanel9.add(chkbox, constraint1);
}
Not sure what is wrong..Any help is much appreciated..Thanks..
The problem is that you are mixing AWT components (heavyweight) with Swing components (lightweight). I have 2 recommendations:
Don't mix heavyweight and lightweight components
Try to use lightweight components as much as possible
So in your code, replace Checkbox by JCheckbox and it should work just fine.

JScrollPane not scrolling when a JPanel is added

I was hoping someone would be able to help. This seems like it should be a simple problem but for the life of me I can't work it out.
Problem: I am creating a JPanel that is made up of panels containing 5 labels each with ImageIcons. [sounds confusing]
I am then adding this panel to a JScrollPane. But when it is displayed the images are showing and correctly placed but I am unable to scroll down to see the panels that are off the screen.
here is a screenshot: http://img841.imageshack.us/img841/36/screenshot20120510at160.png
Here is the snippet of code I am using to populate the panels and add the JScrollPane.
private void setSeriesViewContainer(){
container = new BackgroundPanel(backGround, BackgroundPanel.TILED);
//container.setPreferredSize(new Dimension(650,500));
container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
FlowLayout flowLayout = new FlowLayout();
JPanel[] jp = new BackgroundPanel[10];
for (int i = 0; i < jp.length; i++) {
jp[i] = new BackgroundPanel(backGround, BackgroundPanel.TILED);
jp[i].setLayout(flowLayout);
for (int j = 0; j < 10; j++) {
jp[i].add(new JLabel(new ImageIcon(getClass().getResource("/placeHolder.png"))));
}
}
for (int i = 0; i < jp.length; i++) {
container.add(jp[i]);
}
public void init(){
seriesViewContainer = new javax.swing.JScrollPane(container);
seriesViewContainer.setBorder(null);
seriesViewContainer.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
seriesViewContainer.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
seriesViewContainer.setPreferredSize(new java.awt.Dimension(700, 300));}
I have searched around for the solution but have not come up with one as yet.
container.setPreferredSize(new Dimension(x,y)); the dimensions of container should be larger than the dimensions of the scrollpane.
from what I've read setPreferredSize() is not a good thing to use though. The problem is probably the LayoutManager for container or jp.
same problem here: Java Swing: JScrollPane not working
Have you tried to call revalidate() to the JScrollPane and/or container after each add ?

Categories