Thursday, November 18, 2010
Assignment 17: Slider Demo
/*
//Graphics problem
*/
import java.awt.Graphics;
import java.awt.Dimension;
import javax.swing.JPanel;
public class OvalPanel extends JPanel
{
private int diameter = 10;//default diameter of 10
//draw an oval of the specified diameter
public void paintComponent( Graphics g )
{
super.paintComponent( g );
g.fillOval( 10, 10, diameter, diameter ); //draw circle
}
//validate and set diameter
public void setDiameter( int newDiameter )
{
//if diameter invalid, default to 10
diameter = ( newDiameter >= 0 ? newDiameter : 10 );
repaint(); //repaint panel
}
//use by layout manager to determine preffered size
public Dimension getPreferredSize()
{
return new Dimension( 200, 200 );
}
//used by layout manager to determine minimum size
public Dimension getMinimumSize()
{
return getPreferredSize();
}
}
-----------------------------------------------------------------
/*
//SliderFrame
*/
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class SliderFrame extends JFrame
{
private JSlider diameterJSlider; // slider to select diameter
private OvalPanel myPanel; // panel to draw circle
//no argument constructor
public SliderFrame()
{
super( "Slider Demo" );
myPanel = new OvalPanel(); //create panel to draw circle
myPanel.setBackground( Color.YELLOW ); //set bacground to yellow
//set up JSlider to control diameter value
diameterJSlider = new JSlider( SwingConstants.HORIZONTAL, 0 , 200, 10 );
diameterJSlider.setMajorTickSpacing(10); //create tick every 10
diameterJSlider.setPaintTicks( true ); //paint ticks on slider
//register JSlider event listener
diameterJSlider.addChangeListener(
new ChangeListener() //anonymous inner circle
{
//handle change in slider value
public void stateChanged( ChangeEvent e )
{
myPanel.setDiameter( diameterJSlider.getValue() );
}
}
);
add( diameterJSlider, BorderLayout.SOUTH ); //add slider to frame
add( myPanel, BorderLayout.CENTER ); //add panel to frame
}
}
---------------------------------------------------------------------
/*
//main method
*/
import javax.swing.JFrame;
public class SliderDemo
{
public static void main( String args[] )
{
SliderFrame sliderFrame = new SliderFrame();
sliderFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
sliderFrame.setSize( 220, 270 ); //set frame size
sliderFrame.setVisible( true ); //display frame
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment