Wednesday, March 18, 2009

COLOR CYCLE

/*

Exercise 2
Program Name:Color Cycle
Programmer name: Danver G. Palmiano
Date Started: March 18,2009, 8:15pm
Date Ended: March 18, 2009,9:15pm
Aim: When you enter the button then the color of the background will change depends on the color that are required or stated on the button.
*/


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ButtonDemo extends JPanel implements ActionListener {

private static boolean USE_CROSS_PLATFORM_UI = false;

int buttonLabelIndex = 0;
String buttonLabels[] = { "Green", "blue", "Gray", "Red" };
Color buttonColors[] = { Color.GREEN, Color.BLUE, Color.GRAY, Color.RED,};

JButton button;

public ButtonDemo() {
super(new BorderLayout());

button = new JButton(buttonLabels[buttonLabelIndex]);
// In the default UI look and feel you cannot easily alter the background color
// for buttons since it is designed to match the OS X UI.
if(USE_CROSS_PLATFORM_UI) {
button.setBackground(buttonColors[buttonLabelIndex]);
} else {
button.setForeground(buttonColors[buttonLabelIndex]);
}

button.addActionListener(this);


this.add(button, BorderLayout.CENTER);

this.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}

public void actionPerformed(ActionEvent e) {
buttonLabelIndex = ++buttonLabelIndex < buttonLabels.length?buttonLabelIndex:0;

button.setText(buttonLabels[buttonLabelIndex]);
this.setBackground(buttonColors[buttonLabelIndex]);
button.setBackground(buttonColors[buttonLabelIndex]);

}


private static void run() {
if(USE_CROSS_PLATFORM_UI) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
}

JFrame frame = new JFrame("Button Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JComponent contentPane = new ButtonDemo();
contentPane.setOpaque(true);

frame.setContentPane(contentPane);
frame.pack();

frame.setVisible(true);
}

public static void main(String[] args) {
run();
}

}

No comments:

Post a Comment