Добавление ActionListeners к JButtons и JRadioButtons - PullRequest
0 голосов
/ 20 марта 2020

Я не знаю, как мне добавить ActionListeners, если я хочу нарисовать полигон в центре JPanel. JButtons normalP, randomP - мы можем изменить обычный многоугольник на случайный многоугольник JRadioButton draw - мы рисуем новый полигон Слайдер JSlider - меняем количество вершин

public class Wielokat extends JFrame implements ActionListener {
public Wielokat() throws HeadlessException {
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    this.setSize(800, 600);
    this.setTitle("Wielokąty");

    JPanel up = new JPanel();
    JPanel left = new JPanel();
    JPanel right = new JPanel();
    JPanel down = new JPanel();
    JPanel center = new JPanel();

    regularP = new JRadioButton("Wielokąt foremny");
    randomP = new JRadioButton("Dowolny wielkokąt");

    regularP.setActionCommand("1");
    randomP.setActionCommand("2");

    regularP.addActionListener(this);
    randomP.addActionListener(this);

    ButtonGroup group = new ButtonGroup();
    group.add(regularP);
    group.add(randomP);

    up.add(regularP);
    up.add(randomP);


    slider = new JSlider(JSlider.VERTICAL, 3, 100, 3);
    slider.setMajorTickSpacing(10);
    slider.setMinorTickSpacing(1);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    slider.setPreferredSize(new Dimension(80, 400));

    //wyświetlanie wrtości ze slidera
    value = new JTextField(String.format("%d", slider.getValue()));
    value.setHorizontalAlignment(SwingConstants.CENTER);
    slider.addChangeListener(new SliderChangeListener());

    left.setBorder(BorderFactory.createTitledBorder("Wierzchołki"));
    BoxLayout boxlayout1 = new BoxLayout(left, BoxLayout.Y_AXIS);
    left.setLayout(boxlayout1);
    value.setAlignmentX(Component.CENTER_ALIGNMENT);
    slider.setAlignmentX(Component.CENTER_ALIGNMENT);
    left.add(Box.createRigidArea(new Dimension(0, 10)));
    left.add(value);
    left.add(Box.createRigidArea(new Dimension(0, 10)));
    left.add(slider);
    left.add(Box.createRigidArea(new Dimension(0, 10)));

    right.setLayout(new GridLayout(3, 1, 0,50));
    p1 = new JPanel();
    p2 = new JPanel(new GridLayout(3, 1, 0,20));


    JLabel lineW = new JLabel("Grubość linii");
    String[] width = {"1pxl", "5pxl", "10pxl"};
    lineWidth = new JComboBox(width);


    lineColor = new JButton("Kolor linii");
    lineColor.addActionListener(e -> {
        newColor1 = JColorChooser.showDialog(null, "Choose Color", Color.black);
        //przypisanie koloru do linii
    });


    backgroundColor = new JButton("Kolor tła");
    backgroundColor.addActionListener(e -> {
        newColor2 = JColorChooser.showDialog(null, "Choose Color", Color.white);
        center.setBackground(newColor2);
    });

    BoxLayout boxlayout2 = new BoxLayout(p1, BoxLayout.Y_AXIS);
    p1.setLayout(boxlayout2);
    lineW.setAlignmentX(Component.CENTER_ALIGNMENT);
    lineWidth.setAlignmentX(Component.CENTER_ALIGNMENT);

    p1.add(Box.createRigidArea(new Dimension(0, 50)));
    p1.add(lineW);
    p1.add(lineWidth);
    p1.add(Box.createRigidArea(new Dimension(0, 50)));
    p2.add(lineColor);
    p2.add(backgroundColor);
    right.add(p1);
    right.add(p2);



//PROBLEM with this ActionListener
    draw = new JButton("Rysuj wielokąt");
    down.add(draw);
    draw.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int z = Integer.parseInt(e.getActionCommand());
            int n = slider.getValue();
            JPanel rys = new JPanel(){
                public void paintComponent(Graphics g){
                    super.paintComponent(g);
                    g.setColor(newColor1);
                    if (z == 1) {
                        g.drawPolygon(regular(n));
                    }
                    else if(z == 2){
                        g.drawPolygon(randomP(n));
                    }
                }
            };
            center.add(rys);
        }

    });


    this.add(up, BorderLayout.PAGE_START);
    this.add(left, BorderLayout.LINE_START);
    this.add(center, BorderLayout.CENTER);
    this.add(right, BorderLayout.LINE_END);
    this.add(down, BorderLayout.PAGE_END);

}

@Override
public void actionPerformed(ActionEvent e) {

}

//PROBLEM with randomP and regularP

public Polygon randomP(int n1){
    int n = n1;
    int[] xPoints = new int[n];
    int[] yPoints = new int[n];
    Random r = new Random();
    for (int i = 0; i < slider.getValue(); i++){
        xPoints[i] = r.nextInt(500);
        yPoints[i] = r.nextInt(500);
    }
    Polygon polygon = new Polygon( xPoints, yPoints, n);
    return polygon;
}

public Polygon regular(int n1){
    int n = n1;
    int R = 200;
    int[] xPoints = new int[n];
    int[] yPoints = new int[n];
    for (int i = 0; i < n; i++){
        xPoints[i] = (int)(R*cos((PI/2 + 2*PI*i)/n));
        yPoints[i] = (int)(R*sin((PI/2 + 2*PI*i)/n));
    }
    Polygon polygon = new Polygon( xPoints, yPoints, n);
    return polygon;
}



private class SliderChangeListener implements ChangeListener {
    @Override
    public void stateChanged(ChangeEvent e) {
        String valueS = String.format("%d", slider.getValue());
        value.setText(valueS);
    }
}


public static void main(String[] args){
    Wielokat w = new Wielokat();
    w.setVisible(true);
}

JSlider slider;
JTextField value;
JRadioButton regularP, randomP;
JPanel p1, p2;
JButton lineColor, backgroundColor, draw;
JComboBox lineWidth;
Color newColor1, newColor2;

}

Моя программа должна выглядеть примерно так: http://java.fizyka.pw.edu.pl/data/_uploaded/media/Lab4-przyklad.ogg Редактировать: Я изменил часть своего кода на что-то вроде этого:

    draw.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int n = slider.getValue();
            JPanel panel = new JPanel(){
                public void paintComponent(Graphics g){
                    super.paintComponent(g);
                    g.setColor(newColor1);
                    int n = slider.getValue();
                    if (regularP.isSelected()) {
                        int R = 200;
                        int[] xPoints = new int[n];
                        int[] yPoints = new int[n];
                        for (int i = 0; i < n; i++){
                            xPoints[i] = (int)(R*cos((PI/2 + 2*PI*i)/n));
                            yPoints[i] = (int)(R*sin((PI/2 + 2*PI*i)/n));
                        }
                        Polygon polygon = new Polygon( xPoints, yPoints, n);
                    }
                    else{
                        int[] xPoints = new int[n];
                        int[] yPoints = new int[n];
                        Random r = new Random();
                        for (int i = 0; i < slider.getValue(); i++){
                            xPoints[i] = r.nextInt(500);
                            yPoints[i] = r.nextInt(500);
                        }
                        Polygon polygon = new Polygon( xPoints, yPoints, n);
                        g.drawPolygon(polygon);
                    }
                }
            };
            panel.setSize(500, 500);
            center.add(panel);
        }

    });

Но он все равно не работает должным образом. Может быть, что-то не так с добавлением панели JPanel к панели "center"?

...