按下JButton时,JFrame不添加组件 [英] JFrame does not add component when JButton is pressed

查看:206
本文介绍了按下JButton时,JFrame不添加组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码基本上是关于一个框架,它有一个按钮。按下按钮可以绘制矩形,从鼠标按下和鼠标释放获取坐标。

My code is basically about having a frame and it has a button. You press the button you can draw rectangles, getting coordinates from the mouse press and the mouse release.

现在,如果你删除按钮代码完美,这里是代码。

Now, if you remove the button the code works perfectly, here is the code.

//测试文件

package ActionTest;    
import java.awt.*;
import javax.swing.*;    

public class MouseTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(new Runnable()
         {
            public void run()
            {
               JFrame frame = new MouseFrame();
               frame.setTitle("MouseTest");
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               frame.setVisible(true);
               frame.setSize(500,500);
            }
         });
   }
}

我的框架,调用鼠标组件

My frame, calls on the mouse component

package ActionTest;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class MouseFrame extends JFrame
{           
   public MouseFrame()
   {       
      add(new MouseComponent());                   
   }
}

组件类:处理鼠标点击并绘制矩形

The component class: handles mouse clicks and drawing the rectangle

package ActionTest;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class MouseComponent extends JComponent
{    
   Point first;
   Point second;
   private ArrayList<Rectangle2D> rectangles;

   public MouseComponent()
   {
      rectangles = new ArrayList<>();//contains rectangles
      addMouseListener(new MouseHandler());
   }
   //paint method of the component, simply re-paint the array
   public void paintComponent(Graphics g)
   {
      Graphics2D g2 = (Graphics2D) g;
      for (Rectangle2D r : rectangles)
         g2.draw(r);
   }


   /**
    * creates a rectangle and adds it to the rectangles ArrayList
    * then repaint the component
    * inside some operations to deal with rectangle drawing nothing to do with the issue
    * @param p1: first coordinates
    * @param p2: second coordinates
    */
   public void addRec(Point2D p1, Point2D p2)
   {
       double w, h, x, y;
       double x1 = p1.getX();
       double y1 = p1.getY();
       double x2 = p2.getX();
       double y2 = p2.getY();
       if(x1 <= x2){
           x = x1;
           w = x2-x1;        
       }
       else{
           x = x2;
           w = x1-x2;           
       }
       if (y1 <= y2){
           y = y1;
           h = y2-y1;           
       }
       else{
           y = y2;
           h = y1-y2;           
       }
      rectangles.add(new Rectangle2D.Double(x, y, w, h));
      repaint();
   }


   //records mouse click and mose release
   //you press the mouse that is the 1st coordinates
   //you release it that is the 2nd coordinates
   //pass both to the addRec method
   private class MouseHandler extends MouseAdapter
   {
      @Override
      public void mousePressed(MouseEvent event)
      {          
          first = event.getPoint();
      }
      @Override
      public void mouseReleased(MouseEvent event)
      {
          second = event.getPoint();          
          addRec(first, second);
      }
   }
}

完美无瑕。然而,回到原来的问题,如果我添加一个按钮,然后按下按钮继续并开始绘制矩形它不起作用。

It works perfectly. However, going back to the original problem, if I add a button, and then when the button pressed go ahead and begin drawing rectangles it doesn't work.

这是修改后的框架类

package ActionTest;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class MouseFrame extends JFrame
{    
   private JPanel buttonPanel;
   public MouseFrame()
   {       

       JFrame frame = this;
       buttonPanel = new JPanel();
       JButton rec = new JButton("Rectangle");
       rec.addActionListener(new ActionListener(){        
           public void actionPerformed(ActionEvent event)
           {         
               System.out.println("pressed");                   
               frame.add(new MouseComponent());                
           }});
       buttonPanel.add(rec);
       add(buttonPanel);            
   }
}

提前致谢。

推荐答案

frame.add(new MouseComponent());   

新创建的组件的大小为(0,0),因此无需绘制任何内容。因此,在将组件添加到可见GUI时需要调用布局管理器。

The size of a newly created component is (0, 0) so there is nothing to paint. So you need to invoke the layout manager when you add a component to a visible GUI.

frame.add(new MouseComponent());   
frame.revalidate();
frame.repaint();

请注意,这仅适用于布局管理器允许您向框架添加多个组件的情况。框架的默认布局管理器是BorderLayout,只有一个组件可以添加到BorderLayout的CENTER。

Note this will only work if the layout manager allows you to add multiple components to the frame. The default layout manager for a frame is the BorderLayout and only a single components can be added to the CENTER of the BorderLayout.

所以也许您需要使用以下命令添加按钮:

So maybe you need to add the button using:

frame.add(button, BorderLayout.PAGE_START);

阅读如何使用布局管理器获取更多信息和工作示例。

Read the section from the Swing tutorial on How to Use Layout Managers for more information and working examples.

此外,每次进行自定义绘制时,都需要覆盖自定义组件的 getPreferredSize()方法,以便布局管理器完成其工作。

Also, any time you do custom painting you need to override the getPreferredSize() method of the custom component so the layout managers can do their job.

这篇关于按下JButton时,JFrame不添加组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆