This example show how to place use a slider via swing.
------------------CODE ------------------------------------
import javax.swing.*;
import java.awt.*;
class DrawOval extends JPanel
{
private int d=10; //SET START SIZE OF CIRCLE
public void paintComponent(Graphics g)
{
super.paintComponent(g); //CALL JPANEL PAINT.COMPONENT METHOD
g.fillOval(10,10,d,d); // DRAW CIRCLE
}
// CREATE SETTER METHOD TO CHANGE VARIABLE AND REPAINT
public void setD(int newD)
{
d=(newD>=0 ? newD : 10);
repaint();
}
public Dimension getPreferredSize()
{
return new Dimension(200,200);
}
public Dimension getMinimumSize()
{
return getPreferredSize();
}
}
/////////////////////////////////////////////////////////////////////////////////
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
class TheWindow extends JFrame
{
private JSlider slider; // INSTANTIATE JSLIDER
private DrawOval myPanel; //// INSTANTIATE DRAWOVAL CLASS
public TheWindow()
{
super("The Slider Demo");
myPanel=new DrawOval();
myPanel.setBackground(Color.ORANGE);
slider=new JSlider(SwingConstants.HORIZONTAL,0,200,10);
slider.setMajorTickSpacing(10);
slider.setPaintTicks(true);
// ADD LISTERNER TO SLIDER
slider.addChangeListener
(
new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
myPanel.setD(slider.getValue()); //CALL SETTER METHOD
}
}
);
add(slider,BorderLayout.SOUTH); // ADD SLIDER + LAYOUT
add(myPanel,BorderLayout.CENTER); // ADD PANEL TO FRAME
}
}
////////////////////////////////////////////////////////////////////////////////////////
import javax.swing.*;
class start
{
public static void main(String args[])
{
TheWindow w = new TheWindow();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(300,380);
w.setVisible(true);
}
}
--------------------------------------------------------------
No comments:
Post a Comment