import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.Color;
import java.util.Random;
public class JColorFrame extends JFrame{
private JPanel[]sides;
private JButton btn;
private Color[]colors;
private Random random;
public JColorFrame(){
super("Colors");
sides = new JPanel[]{
new JPanel(),
new JPanel(),
new JPanel(),
new JPanel()
};
btn = new JButton("Change");
colors = new Color[]{
Color.RED,
Color.BLUE,
Color.CYAN,
Color.PINK
};
random = new Random();
}
private void createGUI(){
String[]dirs={
BorderLayout.NORTH,
BorderLayout.SOUTH,
BorderLayout.EAST,
BorderLayout.WEST
};
getContentPane().add(btn);
for(int i = dirs.length-1; 0<= i; i --)
getContentPane().add(sides[i], dirs[i]);
}
private void bindEvents(){
btn.addActionListener((e)->{
SwingUtilities.invokeLater(()->changeColor());
});
}
private void changeColor(){
int i = random.nextInt(colors.length);
Color c = colors[i];
i = random.nextInt(sides.length);
sides[i].setBackground(c);
}
private void launchGUI(){
createGUI();
bindEvents();
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static void main(String[]args){
SwingUtilities.invokeLater(()->{
new JColorFrame().launchGUI();
});
}
}
Download
Comments
Post a Comment