Estou tentando definir os tamanhos dos meus JButtons em um JPanel com BoxLayout corretamente, mas o comportamento está além de estranho. Levará a altura de JButton.setPreferredSize, mas ignoram completamente a largura. Isso também só funciona quando todos os botões estão definidos para a mesma altura. Assim que um é menor, ele irá reverter todos eles para alguns tamanho mínimo aleatório (o que não é ainda a mesma para todos os botões)
Meu código é o seguinte:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 500);
JPanel rightPanel = new JPanel();
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
JButton bBookmarks = new JButton("Bookmarks");
bBookmarks.setPreferredSize(new Dimension(200, 100));
//more buttons with same size
leftPanel.add(bBookmarks);
//more buttons
JSplitPane mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
mainPanel.setDividerLocation(200);
frame.add(mainPanel);
frame.setResizable(false);
frame.setVisible(true);
Isso cria esta imagem.
O botão do meio é sempre mais amplo do que o resto também. Usando frame.pack () não faz nada exceto o redimensionamento do quadro porque o painel da direita está vazio.
O que estou fazendo errado?
Edit: deve ficar assim:
Dividir para conquistar: quebrar o projeto em pequeno, fácil de recipientes de layout. Neste caso, não coloque os botões diretamente na esquerda ( BoxLayout
container), mas em um aninhados JPanel
usando GridLayout
gerente.
Isso garante que todos os botões têm o mesmo tamanho:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
//add all buttons to a panel using a GridLayout which shows all components having the same size
JPanel buttons = new JPanel(new GridLayout(0,1));
JButton bBookmarks = new JButton("Bookmarks"); buttons.add(bBookmarks);
JButton bPlotter = new JButton("Plotter"); buttons.add(bPlotter);
JButton bShips = new JButton("Ships"); buttons.add(bShips);
//add buttons and text area to a panel using BoxLayout
JPanel leftPanel = new JPanel();
leftPanel.setPreferredSize(new Dimension(100,400));
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
leftPanel.add(buttons);
leftPanel.add(new TextArea(10,30));
JPanel rightPanel = new JPanel();
rightPanel.setPreferredSize(new Dimension(600,400));
rightPanel.add(new JLabel("right pane"));
JSplitPane mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true, leftPanel, rightPanel);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);