0

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);
}
}
Drew Wood
  • 91
  • 1
  • 10

1 Answers1

0

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.

yitzih
  • 3,018
  • 3
  • 27
  • 44
  • well the suggestion to be like, create the GridLayout dynamically based on the button count. – ray Apr 13 '14 at 08:12
  • So i added : mainInv.setLayout(new GridLayout((int)(Math.ceil(buttonCount/4)),4)); Thats fixed the problem with the more than 4 columns, but now the buttons aren't being resized to be 100,100. – Drew Wood Apr 13 '14 at 13:15
  • *"but now the buttons aren't being resized to be 100,100"* It would be better **not** to try and set a size to the buttons. See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) - But as I said earlier, this work a lot better for the typical user as a `JList` (in a scroll pane, obviously). – Andrew Thompson Apr 14 '14 at 02:22