import java.awt.*; import javax.swing.*; import java.awt.event.*; public class FarbSlider implements java.awt.event.ActionListener { protected JFrame f; protected Scrollbar sRed, sGreen, sBlue; protected Label lRed, lGreen, lBlue; protected int r, g, b; public FarbSlider() { f = new JFrame("Farb-Slider"); // create window object final Container pane=f.getContentPane(); // needs to be final for use in inner classes pane.setLayout(new GridLayout(4, 2)); // set a grid layout pane.setBackground(Color.black); // default background r = g = b = 0; // for the default RGB values // set up red label lRed = new Label("Rot: 0"); lRed.setBackground(Color.red); // add red label pane.add(lRed); // set up slider for red value sRed = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256); // register event handler for changing red slider sRed.addAdjustmentListener( new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { r = e.getValue(); // get the slider value lRed.setText("Rot: " + r); // update label text pane.setBackground(new Color(r, g, b)); // update field color } } ); // add red slider pane.add(sRed); // the following repetition of code for the other sliders // can of course be avoided but the resulting code // is more complex (need to identify event source) lGreen = new Label("Gruen: 0"); lGreen.setBackground(Color.green); pane.add(lGreen); sGreen = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256); sGreen.addAdjustmentListener( new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { g = e.getValue(); lGreen.setText("Gruen: " + g); pane.setBackground(new Color(r, g, b)); } } ); pane.add(sGreen); lBlue = new Label("Rot: 0"); lBlue.setBackground(Color.blue); pane.add(lBlue); sBlue = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256); sBlue.addAdjustmentListener( new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { b = e.getValue(); lBlue.setText("Blau: " + b); pane.setBackground(new Color(r, g, b)); } } ); pane.add(sBlue); // define the quit button JButton q = new JButton("Quit"); q.addActionListener(this); // add the quit button pane.add(q) ; f.setSize(150, 100); f.setVisible(true); } // class defines reaction to button click itself (implements ActionListener) public void actionPerformed(java.awt.event.ActionEvent e) { System.out.println("Ciao!"); System.exit(0); } public static void main(String[] args) { FarbSlider sl=new FarbSlider(); // create object, will create a window in its constructor } }