为什么看不到JComponent被添加到JFrame?

问题描述 投票:0回答:1

此示例将JButton和JLabel添加到JFrame。

还有一个JComponent应该显示光标的XY坐标。

我知道那里有显示如何显示XY坐标的示例,但很好奇为什么在这种情况下会失败。

查看输出,似乎所有必需的侦听器都在触发,因为输出甚至显示paintCompoent()已以预期的输出执行。

不确定是否需要,但是我确实尝试了setVisible(true)和setBounds()。

这是什么导致带有XY坐标的JComponent出现。

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class XYCoordinateTest extends JFrame 
{

  JLabel label = new JLabel("My Test Label");
  JButton b1 = new JButton("Press Me");
  XYMouseLabel xy = new XYMouseLabel();

  class XYMouseLabel extends JComponent
  {
       public int x;
       public int y;

       public XYMouseLabel() 
       {
         this.setBackground(Color.BLUE);
       }

       // use the xy coordinates to update the mouse cursor text/label
       protected void paintComponent(Graphics g)
       {
         super.paintComponent(g);
         String s = x + ", " + y;
         System.out.println("paintComponent() : " + s);
         g.setColor(Color.red);
         g.drawString(s, x, y);
       }
  } 

  public XYCoordinateTest () 
  {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(label);
    getContentPane().add(b1);
    xy.setBounds(0, 0,  300, 100);
    xy.setVisible(true);
    getContentPane().add(xy);

    addMouseMotionListener(new MouseMotionAdapter() {
        public void mouseMoved(MouseEvent me)
        {
         System.out.println("Panel Mouse Move x : " + me.getX() + "   Y : " + me.getY());
          xy.x = me.getX();
          xy.y = me.getY();
          xy.repaint();
        }
      });
    pack();
    setSize(300, 100);
  }

  public static void main(String[] args) {
    new XYCoordinateTest().setVisible(true);
  }
}
java paintcomponent jcomponent
1个回答
1
投票

xy组件没有首选大小。您在JFrame上调用pack,它将组件调整为首选大小。由于xy组件没有一个组件,因此它不可见。

© www.soinside.com 2019 - 2024. All rights reserved.