import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.util.Random; import java.util.Scanner; class EndreFarge { public static void main (String[] arg) { JFrame vindu = new JFrame("Endre farge p? en knapp"); vindu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(5,5)); vindu.add(panel); // Lager sjakkmoenster. Anenhver er hvit og svart for (int i = 0; i < 25; i++) { if (i % 2 == 0) panel.add(new MinKnapp(Color.WHITE)); else panel.add(new MinKnapp(Color.BLACK)); } vindu.pack(); vindu.setVisible(true); } } class MinKnapp extends JButton{ boolean farget = false; Color start; Random r = new Random(); public MinKnapp(Color start){ this.start = start; initGUI(); } class EndreKnappTekst implements ActionListener{ @Override public void actionPerformed(ActionEvent e){ farget = !farget; if(farget){ // Setter fargen til aa vaere en tilfeldig farge Color c = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256),r.nextInt(256)); setBackground(c); } else{ setBackground(start); } } } public void initGUI(){ setBackground(start); // For aa faa farge paa mac: setOpaque(true); // Gjoer knappen gjennomsiktig setBorderPainted(false); // Fjerner kantene slik at knappen er usynlig addActionListener(new EndreKnappTekst()); } }