Layout2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.Random;
/**
More crunchy layout goodness.
*/
class Layout2 extends JFrame
{
public static void main(String argv[])
{
Layout2 f = new Layout2();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.show();
}
public Layout2()
{
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension ss = kit.getScreenSize();
setSize(2*ss.width/3,ss.height/2);
setLocation(ss.width/4,ss.height/4);
setTitle("CISC370-011 -- Another layout demo");
Random rand = new Random();
Container cp = getContentPane();
// Six panels in a 3x2 arrangement, each with five buttons.
cp.setLayout(new GridLayout(2,3,6,6));
for (int i=0; i<6; i++) {
JPanel p = new JPanel();
if (i % 3 == 0)
p.setLayout(new FlowLayout(FlowLayout.LEFT));
else if (i % 3 == 1)
p.setLayout(new FlowLayout(FlowLayout.CENTER));
else
p.setLayout(new FlowLayout(FlowLayout.RIGHT));
Border b = BorderFactory.createEtchedBorder();
p.setBorder(b);
cp.add(p);
for (int k=0; k<5; k++)
randomButton(rand,p);
}
}
/**
Add a button to a panel that turns the panel's background
a random color.
*/
void randomButton(Random rand,final JPanel panel)
{
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
final Color c = new Color(r,g,b);
String label = Integer.toString(r*256*256 + g*256 + b,16);
JButton jb = new JButton("#"+label.toUpperCase());
Font f = new Font("Monospaced",Font.BOLD,12);
jb.setFont(f);
panel.add(jb);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{ panel.setBackground(c); }
});
}
}