import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Random extends JApplet
{
private SmallButtonPanel panel1;
private BigButtonPanel panel2;
private SliderPanel panel3;
private DrawPanel panel4;
private int panelchoice = 0, y = 0;
public void init ( )
{
setBackground ( Color.black );
Container contentPane = getContentPane();
contentPane.setLayout ( new GridLayout ( 2, 2, 5, 5 ) );
panel1 = new SmallButtonPanel ( );
contentPane.add ( panel1 );
panel2 = new BigButtonPanel ( );
contentPane.add ( panel2 );
panel3 = new SliderPanel ( );
contentPane.add ( panel3 );
panel4 = new DrawPanel ( );
contentPane.add ( panel4 );
}
public Insets getInsets ( )
{
return new Insets ( 5, 5, 5, 5 );
}
class SmallButtonPanel extends JPanel implements ActionListener
{
public SmallButtonPanel ( )
{
setBackground ( Color.blue );
JButton small = new JButton ( " Random Rectangle " );
small.addActionListener ( this );
this.add ( small );
}
public void actionPerformed ( ActionEvent evt )
{
String command = evt.getActionCommand();
if ( command.equals ( " Random Rectangle " ) )
{
panelchoice = 1;
panel4.repaint ( );
}
}
}
class BigButtonPanel extends JPanel implements ActionListener
{
public BigButtonPanel ( )
{
setLayout(new BorderLayout());
setBackground ( Color.cyan );
JButton big = new JButton ( " Random Line " );
big.addActionListener ( this );
this.add ( big, BorderLayout.CENTER );
}
public void actionPerformed ( ActionEvent evt )
{
String command = evt.getActionCommand();
if ( command.equals ( " Random Line " ) )
{
panelchoice = 2;
panel4.repaint ( );
}
}
}
class SliderPanel extends JPanel implements ChangeListener
{
JSlider slide;
public SliderPanel ( )
{
setLayout(new BorderLayout());
setBackground ( Color.magenta );
slide = new JSlider ( 0, 225, 100 );
slide.setOrientation ( JSlider.VERTICAL );
slide.addChangeListener ( this );
this.add ( slide, BorderLayout.EAST );
}
public void stateChanged ( ChangeEvent e )
{
if ( e.getSource() == slide )
{
panelchoice = 3;
y = slide.getValue ( );
panel4.repaint ( );
}
}
}
class DrawPanel extends JPanel
{
private int x, otherx, othery;
public DrawPanel ( )
{
setBackground ( Color.yellow );
}
public void paintComponent ( Graphics g )
{
super.paintComponent ( g );
if ( panelchoice == 1 )
{
x = (int)(Math.random ( ) * ( getWidth ( ) - 20 ) );
y = (int)(Math.random ( ) * ( getHeight ( ) - 20 ) );
g.setColor ( Color.green );
g.fillRect ( x, y, 20, 20 );
}
else if ( panelchoice == 2 )
{
x = (int)(Math.random ( ) * getWidth ( ) );
y = (int)(Math.random ( ) * getHeight ( ) );
otherx = (int)(Math.random ( ) * getWidth ( ) );
othery = (int)(Math.random ( ) * getHeight ( ) );
g.setColor ( Color.blue );
g.drawLine ( x, y, otherx, othery );
}
else if ( panelchoice == 3 )
{
x = getWidth ( ) / 2;
g.setColor ( Color.black );
g.fillOval ( x, 225 - y, 20, 20 );
}
}
}
}
Back to Lesson 30 Examples
Back to Java Main Page