Ecco un esempio minimale di uso di GridBagLayout per realizzare un classico "modulo" di inserimento dati.
codice:import java.awt.*; import javax.swing.*; public class TestFrame extends JFrame { private Container contentPane; private GridBagLayout gridbag; public TestFrame() { super("Test"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); contentPane = getContentPane(); gridbag = new GridBagLayout(); contentPane.setLayout(gridbag); setupRiga(0, new JLabel("Nome"), new JTextField(20)); setupRiga(1, new JLabel("Cognome"), new JTextField(25)); setupRiga(2, new JLabel("Sesso"), new JComboBox(new String[] { "", "Maschio", "Femmina" })); setupRiga(3, new JLabel("Citta`"), new JTextField(30)); pack(); } private void setupRiga(int r, Component leftComp, Component rightComp) { GridBagConstraints c = new GridBagConstraints(); c.gridy = r; c.anchor = GridBagConstraints.WEST; c.insets = new Insets(r == 0 ? 10 : 0, 10, 10, 0); c.gridx = 0; contentPane.add(leftComp, c); c.insets = new Insets(r == 0 ? 10 : 0, 10, 10, 10); c.gridx = 1; contentPane.add(rightComp, c); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TestFrame().setVisible(true); } }); } }

Rispondi quotando