Reputation: 5427
This code is just a silly example which I need to understand to solve a much bigger problem about another project I am working on: as you can see, in the for cycle, 23 buttons are supposed to be added to JPanel. As they cannot be shown all together I decided to add a JScrollPane but a strange thing happens: only 19 are shown and I do not understand why. The size matrix has 1 column for 23 rows so it is correct. Do you know why this happens? Thanks
package proveGUI;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import layout.TableLayout;
public class Main {
public static void main(String argv[]) {
JFrame jframe = new JFrame("Protocollo UTL");
//jframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
jframe.setSize(1200, 450);
JPanel body = new JPanel();
double[][] size = {
{0.05},
{0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05}
};
body.setLayout(new TableLayout(size));
for(int i=0; i<22; i++) {
body.add(new JButton(String.valueOf(i)), "0,"+String.valueOf(i));
}
JScrollPane scrollPane = new JScrollPane(body,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jframe.add(scrollPane);
jframe.setVisible(true);
}
}
Upvotes: 4
Views: 174
Reputation:
The problem stems from you using size values between 0.00 and 1.00. These are interpreted as relative sizes/percentages, in this case 5%. That's why it's showing 20 rows only (0 to 19 inclusive). Try using "50.0" instead and the problem goes away. Or use TableLayout.PREFERRED
.
Upvotes: 2
Reputation: 7202
I don't know much about TableLayout
because I've didn't ever use it. If it is your first experience with Swing, try the common Swing Layouts.
For your case, you can simple try
body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS)); // instead of TableLayout
When U'll understand how layouts work in Swing, use GridBagLayout
, because it is the most adjustable layout.
Upvotes: 2