Hello,
I need to re size the square whenever I move the slider; how can I accomplish that? Your time and effort are appreciated.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
public class SquareSliderTest{
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
SliderFrame frame = new SliderFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class SliderFrame extends JFrame
{
public SliderFrame()
{
setTitle("Square Slider");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
SquareComponent component = new SquareComponent();
add(component);
sliderPanel = new JPanel();
sliderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
listener = new ChangeListener()
{
public void stateChanged(ChangeEvent event)
{
// update text field when the slider value changes
JSlider source = (JSlider) event.getSource();
textField.setText("" + source.getValue());
}
};
// add the snap to tick slider
JSlider slider = new JSlider();
slider = new JSlider();
slider.setPaintTicks(true);
slider.setSnapToTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(2);
addSlider(slider, "Slide to size the square");
//Set the location of the slider
add(sliderPanel, BorderLayout.SOUTH);
//display the slider on top
textField = new JTextField();
add(textField, BorderLayout.NORTH);
}
private void addSlider(JSlider s, String description)
{
s.addChangeListener(listener);
JPanel panel = new JPanel();
panel.add(s);
panel.add(new JLabel(description));
sliderPanel.add(panel);
}
private JTextField textField;
private JPanel sliderPanel;
private ChangeListener listener;
public static final int DEFAULT_WIDTH = 350;
public static final int DEFAULT_HEIGHT = 400;
}
class SquareComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
double leftX = 125;
double topY = 125;
double width = 10;
double height = 10;
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
g2.draw(rect);
}
}