当值改变时,JPanel内部的JSlider移动

时间:2018-01-31 11:41:26

标签: java swing jslider

我在JFrame边框布局中有两个JPanel,在一个JPanel中我想绘制东西,而另一个我用来保存一些JComponents(现在只有JSlider)。问题是,当我用滑块更改值时,会发生非常奇怪的事情(滑块移动而不是什么)。这是全班:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main extends JPanel {

static final int WIDTH = 800, HEIGHT = 800;

static final int pointsMin = 10, pointsMax = 300;

static JSlider sliderPoints;

static ArrayList<Point> points = new ArrayList<Point>();

public static void main(String[] args)
{
    JFrame jf = new JFrame("Circle");
    Main panel = new Main();
    panel.setPreferredSize(new Dimension(800,650));
    JPanel panel2 = new JPanel(null);
    panel2.setPreferredSize(new Dimension(800,150));

    Container pane = jf.getContentPane();
    pane.add(panel2, BorderLayout.NORTH);
    pane.add(panel,BorderLayout.CENTER);

    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.pack();
    jf.setVisible(true);
    jf.requestFocus();

    sliderPoints = new JSlider(pointsMin, pointsMax, pointsMin);
    sliderPoints.setLocation(64,64);
    sliderPoints.setSize(128, 32);
    panel2.add(sliderPoints);
    sliderPoints.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            panel.recalculate();
        }

    });

    panel.recalculate();
}

private void recalculate()
{
    points.clear();
    float angle = (float) (6.2856f / sliderPoints.getValue());

    for(int i=0; i < sliderPoints.getValue(); i++)
    {
        int x = (int) (Math.cos(angle * i) * (100));
        int y = (int) (Math.sin(angle * i) * (100));
        points.add(new Point(x,y));
    }
    revalidate();
    repaint();
}

public void paint(Graphics g)
{
    g.setColor(Color.red);
    for (int i=0; i < points.size(); i++)
    {
        g.fillRect(400 + points.get(i).x - 1, HEIGHT/2 + points.get(i).y - 1, 3, 3);
    }

    g.dispose();
}
}

0 个答案:

没有答案