Link zu www.kneller-gifs.de

GUI - Farbwechsel mit 2 Buttons

Dieses Beispiel zeigt, wie man zwei Buttons auf ihre Action (Klicks) abfragen kann.
Abhängig davon, welcher Button angeklickt wird, ändert sich die Hintergrundfarbe des Frames.

Hier der Quellcode zum oben beschiebenen Programm:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Farbwechsel extends JFrame implements ActionListener {

    JButton bRot;
    JButton bBlau;

    public Farbwechsel() {
        setSize(200, 100);
        setTitle("Farbwechsel");
        getContentPane().setBackground(Color.ORANGE);
        bRot = new JButton("Rot");
        bBlau = new JButton("Blau");
        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(bRot);
        getContentPane().add(bBlau);
        bRot.addActionListener(this);
        bBlau.addActionListener(this);
        bRot.setActionCommand("rot");
        bBlau.setActionCommand("blau");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("rot")) {
            getContentPane().setBackground(Color.red);
        } else {
            getContentPane().setBackground(Color.blue);
        }
        repaint();
    }
}

Testklasse zum Starten der Anwendung
public class Test {
    public static void main(String[] args) {
        Farbwechsel demo = new Farbwechsel();
    }
}