Codice: Seleziona tutto
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridBagLayoutDemo {
public static void addComponentsToPane(Container pane) {
JButton button;
JButton button2;
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
pane.setLayout(layout);
button = new JButton("1");
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 2;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.VERTICAL;
layout.setConstraints(button, c);
pane.add(button);
JLabel label = new JLabel("2");
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(label, c);
pane.add(label);
JLabel label2 = new JLabel("3");
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 2;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(label2, c);
pane.add(label2);
button2 = new JButton("4");
c.gridx = 4;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 2;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.VERTICAL;
layout.setConstraints(button2, c);
pane.add(button2);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 10));
JPanel p = new JPanel();
Dimension d = new Dimension(frame.getSize().width, 30);
p.setPreferredSize(d);
JPanel p2 = new JPanel();
p2.setPreferredSize(d);
addComponentsToPane(p);
addComponentsToPane(p2);
frame.add(p);
frame.add(p2);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}Tuttavia, se non imposto manualmente la dimensione del panel ho che le label occupano il minimo spazio possibile ed impostando una dimensione per le label non capisco la logica con cui vengano incrementate le dimensioni delle componenti nella griglia. Ad esempio, se imposto la label più larga del frame questa spesso continua a mostrarmi tutto il suo contenuto.
C'è un modo per decidere a priori le dimensioni di righe e colonne e poi operare di conseguenza?
