简体   繁体   English

事件发生时绘制新的图形组件(即圆圈)

[英]Draw new graphics components (ie circles) when event happens

Im working on a very simple program. 我正在开发一个非常简单的程序。 What I want to do is have a new circle added when firstButton is pressed (program is currently as it is after making sure I had events working right). 我想做的是,在按下firstButton时添加了一个新的圆圈(程序在确保事件正常运行之后是当前状态)。

I know I need a paintComponent method somewhere, and possibly need to use repaint but not certain how to put these in. 我知道我需要在某个地方使用paintComponent方法,并且可能需要使用repaint但不确定如何将它们放入。

Help would be appreciated, thanks: 感谢您的帮助,谢谢:

public class aGameForBella extends JPanel {

    private int count1 = 0, count2 = 0, count3 = 0;
    JButton firstButton, secondButton, thirdButton;
    JLabel firstLabel, secondLabel, thirdLabel;
    JPanel optionPanel;

    //constructor method
    public aGameForBella() {
        //create components
        optionPanel = new JPanel();
        firstButton = new JButton("Button option number one");
        firstLabel = new JLabel("You pushed the first button: " + count1
                + " times");
        secondButton = new JButton("Button option number two");
        secondLabel = new JLabel("You pushed the second button: " + count2
                + " times");
        thirdButton = new JButton("Button option number three");
        thirdLabel = new JLabel("You pushed the third button: " + count3
                + " times");
        //add listeners
        firstButton.addActionListener(new ButtonListener());
        secondButton.addActionListener(new ButtonListener());
        thirdButton.addActionListener(new ButtonListener());

        //add panels
        add(optionPanel);

        //add components to panels
        optionPanel.add(firstButton);
        optionPanel.add(firstLabel);
        optionPanel.add(secondButton);
        optionPanel.add(secondLabel);
        optionPanel.add(thirdButton);
        optionPanel.add(thirdLabel);

        //set size of things
        optionPanel.setPreferredSize(new Dimension(200, 200));
        setPreferredSize(new Dimension(250, 500));
        setBackground(Color.cyan);

    }

    //inner class
    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            if (event.getSource() == firstButton) {
                count1++;
                firstLabel.setText("You pushed the first button: " + count1
                        + " times");
            } else if (event.getSource() == secondButton) {
                count2++;
                secondLabel.setText("And you pushed the second button: "
                        + count2 + " times");
            } else if (event.getSource() == thirdButton) {
                count3++;
                thirdLabel.setText("And the last button: " + count3 + " times");

            }

        }
    }
}

Depending on your needs will depend on your overall approach. 根据您的需求将取决于您的整体方法。

For example, if you want to maintain what you are drawing, you need to generate a list containing all the values you need in order to reproduce the output when the component is repainted. 例如,如果您要维护所绘制的内容,则需要生成一个包含所有所需值的列表,以便在重新绘制组件时重现输出。

The following example basically contains a list of objects based on Shape and repaints them each time the component is painted. 下面的示例基本上包含一个基于Shape的对象列表,并在每次绘制组件时重新绘制它们。

在此处输入图片说明

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DrawCircles {

    public static void main(String[] args) {
        new DrawCircles();
    }

    public DrawCircles() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final CirclePane circlePane = new CirclePane();
                JButton btn = new JButton("Click");
                btn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        circlePane.addCircle();
                    }

                });

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(circlePane);
                frame.add(btn, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class CirclePane extends JPanel {

        private List<Shape> circles;

        public CirclePane() {
            circles = new ArrayList<>(25);
        }

        public void addCircle() {
            int width = getWidth() - 1;
            int height = getHeight() - 1;
            int radius = (int) Math.round(Math.random() * (Math.min(width, height) / 4f));
            int x = (int) Math.round(Math.random() * getWidth());
            int y = (int) Math.round(Math.random() * getHeight());
            if (x + radius > width) {
                x = width - radius;
            }
            if (y + radius > height) {
                y = height - radius;
            }
            circles.add(new Ellipse2D.Float(x, y, radius, radius));
            repaint();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            int width = getWidth() - 1;
            int height = getHeight() - 1;
            for (Shape shape : circles) {
                g2d.draw(shape);
            }
            g2d.dispose();
        }

    }

}

Custom Painting Approaches shows the two standard ways of doing custom painting. “定制绘画方法”显示了两种执行定制绘画的标准方法。 The first is to draw from a List and the second is to draw on a BufferedImage. 第一个是从List绘制,第二个是在BufferedImage上绘制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM