为什么我的paintComponent 不工作?

发布于 2024-12-17 10:02:02 字数 2791 浏览 2 评论 0原文

我想要对程序执行的操作是,当我单击图像时,矩形将与 JOptionPane 一起出现。然而,JOptionPane 是唯一弹出的东西。

我尝试更改方法并添加更多类,但没有任何效果>。<任何人都可以阐明我的问题吗?这是我的代码片段。

下面是我调用文件选择器的地方,它允许我选择我的照片。此外,还有很多其他东西,例如标签。

public Help(){

        fc.setDialogTitle("Choose an image file to begin:");
        int returnval = fc.showOpenDialog(null);
        if (returnval == JFileChooser.APPROVE_OPTION){ //when user selects a file, value returned will be JFileChooser.APPROVE_OPTION
            File file = fc.getSelectedFile(); //the File value of the selection is returned from a call on getSelectedFile
            try{
                image = ImageIO.read(file); //reads and loads File as image
            }
            catch (IOException e){}
                System.out.println("You chose to open this file: " + file.getName());
        }else
            System.out.println("No file selected.");

        icon = new ImageIcon(image);
        label = new JLabel(icon);
        tagName = new JLabel(input);

        label.addMouseListener(new ImagePanel());
        label.addMouseMotionListener(new ImagePanel());
        panel.add(tagName);
    }

最后是我的 ImagePanel 类,其中包含麻烦的 PaintComponent。另外,还有几个 mouseListener。

class ImagePanel extends JPanel implements MouseListener, MouseMotionListener{

        @Override
        public void mouseClicked(MouseEvent event) {
            // TODO Auto-generated method stub

                x = event.getX();
                y = event.getY();

                input = JOptionPane.showInputDialog("Enter tag name");
                tagName.setText("You have tagged: " + input);
                System.out.println(input);
        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mousePressed(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseReleased(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        public void paintComponent(Graphics g){
            super.paintComponent(g);

                if(image != null && isRectPresent){
                    g.setColor(Color.DARK_GRAY);
                    g.drawRect(x-50, y-50, 100, 100);
                }
        }   

        @Override
        public void mouseDragged(MouseEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            // TODO Auto-generated method stub
        }
    }

您可以编译代码并亲自查看。如果您知道该怎么做,请提醒我:) 非常感谢!

What I want to do with my program is when I click the image, the rectangle will come out, together with the JOptionPane. However, the JOptionPane is the only thing popping up.

I tried changing methods and adding more classes, nothing worked >.< Can anyone shed some light to my problem? Here's a snippet of my code.

Below is where I call the filechooser which allows me to select my photo. Also, a bunch of other stuff like labels are here.

public Help(){

        fc.setDialogTitle("Choose an image file to begin:");
        int returnval = fc.showOpenDialog(null);
        if (returnval == JFileChooser.APPROVE_OPTION){ //when user selects a file, value returned will be JFileChooser.APPROVE_OPTION
            File file = fc.getSelectedFile(); //the File value of the selection is returned from a call on getSelectedFile
            try{
                image = ImageIO.read(file); //reads and loads File as image
            }
            catch (IOException e){}
                System.out.println("You chose to open this file: " + file.getName());
        }else
            System.out.println("No file selected.");

        icon = new ImageIcon(image);
        label = new JLabel(icon);
        tagName = new JLabel(input);

        label.addMouseListener(new ImagePanel());
        label.addMouseMotionListener(new ImagePanel());
        panel.add(tagName);
    }

And finally, my ImagePanel class, which contains the troublesome paintComponent. Also, a couple of mouseListeners.

class ImagePanel extends JPanel implements MouseListener, MouseMotionListener{

        @Override
        public void mouseClicked(MouseEvent event) {
            // TODO Auto-generated method stub

                x = event.getX();
                y = event.getY();

                input = JOptionPane.showInputDialog("Enter tag name");
                tagName.setText("You have tagged: " + input);
                System.out.println(input);
        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mousePressed(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseReleased(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        public void paintComponent(Graphics g){
            super.paintComponent(g);

                if(image != null && isRectPresent){
                    g.setColor(Color.DARK_GRAY);
                    g.drawRect(x-50, y-50, 100, 100);
                }
        }   

        @Override
        public void mouseDragged(MouseEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            // TODO Auto-generated method stub
        }
    }

You can compile the code and see for yourself. Give me a heads up if you know what to do :) Thank you so much!

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

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

发布评论

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

评论(3

烟酒忠诚 2024-12-24 10:02:03

各种奇怪的东西:

label.addMouseListener(new ImagePanel());
label.addMouseMotionListener(new ImagePanel()); 

您不应该只是为了向组件添加侦听器而创建新的 JPanel。您已经拥有该面板的一个实例。

addMouseMotionListener(this);  

切勿将侦听器添加到绘画方法中的组件。您永远无法控制何时调用绘画方法,并且最终会多次添加相同的侦听器。

All kinds of weird stuff:

label.addMouseListener(new ImagePanel());
label.addMouseMotionListener(new ImagePanel()); 

You should not be creating a new JPanel just to add a listener to a component. You already have an instance of the panel.

addMouseMotionListener(this);  

Never add a listener to a component in a painting method. You can never control when the painting methods are invoked and you will end up with the same listener added multiple times.

落在眉间の轻吻 2024-12-24 10:02:03

一个注意事项:一个较小的示例早先已经得到了回答。

将鼠标事件 x 和 y 分配给 ImagePanel 中的自定义字段,并使用其他名称,例如:

int mx;
int my;

其他要实验的内容,省略了super.paintComponent。
此外,也许您想在 g 上使用更多方法:(

Graphics2D g2 = (Graphics2D)g;

分配给基类 x 和 y 从来都不是一个好主意;最好使用 setBounds 来进行诸如更改坐标之类的操作。)

One note: a smaller example would have been answered earlier.

Assign the mouse events x and y to self-defined fields in ImagePanel, with other names, like:

int mx;
int my;

The other things to experiment with, is leaving out super.paintComponent.
Furthermore maybe you want to use more methods on g:

Graphics2D g2 = (Graphics2D)g;

(Assigning to base classes x and y is never a good idea; better use setBounds for something like changing coordinates.)

回眸一笑 2024-12-24 10:02:03
  try{
       image = ImageIO.read(file); //reads and loads File as image
   }
   catch (IOException e){}

这里的代码说:“让我们尝试读取图像。如果失败(抛出异常),则忽略该问题并在没有图像的情况下继续。”。忽视问题总是不好的。我们至少可以打印问题并继续。

  try{
      image = ImageIO.read(file); //reads and loads File as image
  }
  catch (IOException e){
     e.printStackTrace();//print the exception
  }

或者打印问题并停止:

  try{
      image = ImageIO.read(file); //reads and loads File as image
  }
  catch (IOException e){
     e.printStackTrace();//print the exception
     System.exit(0);//stop executing
  }

实际问题很可能在这里:

if(image != null && isRectPresent){
   g.setColor(Color.DARK_GRAY);
   g.drawRect(x-50, y-50, 100, 100);
}

我认为问题是 if 条件为 false(没有图像(也许读取它时出现异常...? ) 和/或 isRectPresent 为 false) 因此它什么也不做!在 if 处包含一个断点,在调试模式下启动程序,并在程序到达此点时检查变量 imageisRectPresent。 (如果没有到达那里,您就知道遇到了不同的问题。)祝您好运!

  try{
       image = ImageIO.read(file); //reads and loads File as image
   }
   catch (IOException e){}

Here the code says: "let's try to read an image. If that fails (an exception is thrown) then ignore the problem and continue without the image.". Ignoring problems is always bad. We could at least print the problem and continue.

  try{
      image = ImageIO.read(file); //reads and loads File as image
  }
  catch (IOException e){
     e.printStackTrace();//print the exception
  }

Or print the problem and stop:

  try{
      image = ImageIO.read(file); //reads and loads File as image
  }
  catch (IOException e){
     e.printStackTrace();//print the exception
     System.exit(0);//stop executing
  }

The actual problem is most likely here:

if(image != null && isRectPresent){
   g.setColor(Color.DARK_GRAY);
   g.drawRect(x-50, y-50, 100, 100);
}

I think the problem is that the if condition is false (there is no image(perhaps there was an exception reading it...?) and/or isRectPresent is false) thus it does nothing! Include a break point at the if, launch your program in debug mode and inspect the variables image and isRectPresent when the program reaches this point. (If it doesn't get there, you know you got a different problem.) Good luck!

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