import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.GridLayout; public class GridEksempel { public static void main(String[] args) { /* Setter opp vinduet */ try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { System.exit(1); } JFrame vindu = new JFrame("Mitt Program"); vindu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); vindu.add(panel); /* Lager ActionListener til knappene, slik at de skriver ut nr naar man trykker */ // (Trenger ikke aa gjoere dette, kan ogsaa ha knapper som ikke gjoer noe) class KnappListener implements ActionListener { int nr; public KnappListener(int nr) { this.nr = nr; } @Override public void actionPerformed(ActionEvent e) { System.out.println(nr); } } /* Lager rutenettet */ int rader = 3; int kol = 4; panel.setLayout(new GridLayout(rader, kol)); int teller = 1; // For hver kolonne i hver rad, sett en knapp der for (int r = 0; r < rader; r++ ) { for (int k = 0; k < kol; k++) { JButton nrKnapp = new JButton("" + teller); nrKnapp.addActionListener(new KnappListener(teller)); teller++; panel.add(nrKnapp); } } /* Pakker sammen og viser GUI-vinduet */ vindu.pack(); vindu.setVisible(true); } }