尝试在单击按钮时在 JPanel 中添加动态定位的图像

发布于 2024-12-05 13:28:12 字数 3149 浏览 1 评论 0原文

我正在尝试向现有 JPanel 添加/绘制单个 Graphics 对象。我正在生成 10 个随机大小并放置在面板中的初始 Graphics 对象,但希望一次添加一个额外的绘制对象,随机大小并像初始 10 个一样放置。

当前,AddNewDrawItem 类不会渲染新的 Graphics 对象。

感谢您的意见。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class Painter{

private DrawingPanel dp = new DrawingPanel();

    //constructor
    public Painter(){
        buildGUI();
    }

    private void buildGUI(){
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());
        frame.setTitle("Paint drawing demonstration");
        JPanel headerPanel = new JPanel();
        headerPanel.add(new JLabel("The drawing panel is below"));
        JButton addNew = new JButton("Add New Graphic");
        addNew.addActionListener(new addNewClickHandler());
        headerPanel.add(addNew);            
        frame.add(BorderLayout.NORTH,headerPanel);
        frame.add(BorderLayout.SOUTH,this.dp);  
        frame.pack();
        frame.setVisible(true);
    }

    class DrawingPanel extends JPanel {

        public void paintComponent(Graphics g) {
            super.paintComponent(g);       
            this.setBackground(Color.white);

            int x, posx, posy, width, height;

            for(x=0;x<=10;x++){
                //even number differentiation
                if(x % 2 == 0){
                    g.setColor(Color.red);
                }else{
                    g.setColor(Color.blue);
                }

                Random rand = new Random();
                posx = rand.nextInt(300);
                posy = rand.nextInt(300);
                width = rand.nextInt(40);
                height = rand.nextInt(40);

                //System.out.println("the ran x pos is: " + posx);
                g.fillRect(posx, posy, width, height);
            }//end for  
         }//end paintComponent  

        public Dimension getPreferredSize() {
           return new Dimension(400,400);
        }
    }// end DrawingPanel

    private class addNewClickHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            System.out.print("in addNew_click_handler click handler");//trace debug
            AddNewDrawItem newItem = new AddNewDrawItem();
            newItem.repaint();
            System.out.print("after repaint() in addNew_click_handler click  handler");//trace debug
            }
        }

    class AddNewDrawItem extends JPanel {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);       
            this.setBackground(Color.white);
            int posx, posy, width, height;

            Random rand = new Random();
            posx = rand.nextInt(300);
            posy = rand.nextInt(300);
            width = rand.nextInt(40);
            height = rand.nextInt(40);
            g.setColor(Color.cyan);
            g.fillRect(posx, posy, width, height);

        }//end paintComponent   
    }//end AddNewDrawItem 

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

    }//end class Painter

I am trying to add/draw a single Graphics object to an existing JPanel. I am generating 10 initial Graphics objects randomly sized and place in the panel, but would like to add additional drawn objects one a time, randomly sized and placed like the initial 10.

Currently, the AddNewDrawItem class is not rendering the new Graphics object.

Thank you for input.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class Painter{

private DrawingPanel dp = new DrawingPanel();

    //constructor
    public Painter(){
        buildGUI();
    }

    private void buildGUI(){
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());
        frame.setTitle("Paint drawing demonstration");
        JPanel headerPanel = new JPanel();
        headerPanel.add(new JLabel("The drawing panel is below"));
        JButton addNew = new JButton("Add New Graphic");
        addNew.addActionListener(new addNewClickHandler());
        headerPanel.add(addNew);            
        frame.add(BorderLayout.NORTH,headerPanel);
        frame.add(BorderLayout.SOUTH,this.dp);  
        frame.pack();
        frame.setVisible(true);
    }

    class DrawingPanel extends JPanel {

        public void paintComponent(Graphics g) {
            super.paintComponent(g);       
            this.setBackground(Color.white);

            int x, posx, posy, width, height;

            for(x=0;x<=10;x++){
                //even number differentiation
                if(x % 2 == 0){
                    g.setColor(Color.red);
                }else{
                    g.setColor(Color.blue);
                }

                Random rand = new Random();
                posx = rand.nextInt(300);
                posy = rand.nextInt(300);
                width = rand.nextInt(40);
                height = rand.nextInt(40);

                //System.out.println("the ran x pos is: " + posx);
                g.fillRect(posx, posy, width, height);
            }//end for  
         }//end paintComponent  

        public Dimension getPreferredSize() {
           return new Dimension(400,400);
        }
    }// end DrawingPanel

    private class addNewClickHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            System.out.print("in addNew_click_handler click handler");//trace debug
            AddNewDrawItem newItem = new AddNewDrawItem();
            newItem.repaint();
            System.out.print("after repaint() in addNew_click_handler click  handler");//trace debug
            }
        }

    class AddNewDrawItem extends JPanel {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);       
            this.setBackground(Color.white);
            int posx, posy, width, height;

            Random rand = new Random();
            posx = rand.nextInt(300);
            posy = rand.nextInt(300);
            width = rand.nextInt(40);
            height = rand.nextInt(40);
            g.setColor(Color.cyan);
            g.fillRect(posx, posy, width, height);

        }//end paintComponent   
    }//end AddNewDrawItem 

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

    }//end class Painter

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Hello爱情风 2024-12-12 13:28:12

您的代码存在一些问题,其中之一是您的 PaintComponent 方法中有程序逻辑:代码随机更改此方法中显示的值,这意味着您的显示在重新绘制时会发生变化,无论您是否愿意或不。要看到这一点,尝试调整 GUI 的大小,您会在绘制的红色和蓝色矩形中看到一些迷幻的变化。

现在就您当前的问题而言,它的解决方案与我上面描述的问题的解决方案类似。我建议......

  • 您创建一个 ArrayList
  • 在类的构造函数中创建随机矩形,以便它们仅创建一次,然后将它们放置在上面的 ArrayList 中。
  • 您可以在 JPanel 的 PaintComponent 方法中迭代此 ArrayList,边绘制边绘制它们。这样,paintComponent 除了绘制之外什么也不做,这就是它应该做的,
  • 您创建一个 MouseAdapter 派生的对象并将其作为 MouseListener 和 MouseMotionListener 添加到您的 DrawingPanel
  • ,您使用上面的侦听器创建一个新的 Rectangle2D 对象,并在完成后添加它到 ArrayList 并在 DrawingPanel 上调用 repaint
  • ,您通过按钮的操作侦听器激活鼠标适配器。

我就到此为止,但我想您已经明白了,如果您不明白,请提出您可能有的任何问题。

You've got some problems with your code, one of which is that you've got program logic in your paintComponent method: the code randomly changes values that are displayed within this method, meaning your display will change when it repaints, whether you want it to or not. To see that this is so, try to resize your GUI and you'll see some psychedelic changes in the drawn red and blue rectangles.

Now as to your current problem, the solution to it is similar to the solution to the problem I describe above. I suggest...

  • that you create an ArrayList<Rectangle2D>,
  • that you create your random rectangles in your class's constructor so that they're created only once, and then place them in the ArrayList above.
  • that you iterate through this ArrayList in your JPanel's paintComponent method, drawing them as you go. This way paintComponent does nothing but paint which is as it should be,
  • that you create a MouseAdapter-derived object and add it as a MouseListener and MouseMotionListener to your DrawingPanel
  • that you use the listener above to create a new Rectangle2D object and when done add it to the ArrayList and call repaint on the DrawingPanel
  • that you activate the mouse adapter via your button's action listener.

I'll stop there, but I think you get the idea, and if you don't, please ask any questions you may have.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文