Draw lines in jpanel using jslider value
-
15-10-2022 - |
Question
I want to divide a jpanel equally by drawing lines, so when i drag the jslider to 2 then i want my jpanel to be divided by 2 , and so on.Like the page [http://illuminations.nctm.org/Activity.aspx?id=3510][1] Below is my code
MyDrawPanel panel;
JFrame frame;
int x = 0;
int counter = 0;
int stepping = 0;
JSlider hslider;
public static void main(String[] args){
DividePanel div = new DividePanel();
div.go();
}
public void go(){
frame = new JFrame("My Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
hslider = new JSlider(JSlider.HORIZONTAL,1,4,4);
//hslider.setValue(1);
hslider.setMajorTickSpacing(1);
hslider.setPaintLabels(true);
hslider.setPaintTicks(true);
hslider.addChangeListener(new HsliderListener());
panel = new MyDrawPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.BLUE,2,false));
frame.getContentPane().add(BorderLayout.SOUTH,hslider);
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.setSize(400, 400);
frame.setVisible(true);
}
public class MyDrawPanel extends JPanel{
public MyDrawPanel(){
setPreferredSize(new Dimension(400,400));
}
@Override
public void paintComponent(Graphics g){
//g.setColor(Color.WHITE);
//g.fillRect(0, 0, this.getWidth(), this.getHeight());
for(int i=1; i<counter; i+=100){
stepping=400/counter;
g.setColor(Color.BLUE);
g.drawLine(0, x+stepping, this.getWidth(), i+stepping);
}
}
}
public class HsliderListener implements ChangeListener{
@Override
public void stateChanged(ChangeEvent e) {
counter = hslider.getValue();
panel.repaint();
}
}
If anyone can help i would be thankful. Sorry for the bad english. Thanks in advance.
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow