为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我看不到 JComponent 添加到 JFrame 中?

为什么我看不到 JComponent 添加到 JFrame 中?

ABOUTYOU 2024-01-25 10:32:56
此示例将 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);  }}
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

xy 分量没有首选大小。您可以在 JFrame 上调用pack ,它将组件调整为其首选大小。由于 xy 分量没有,因此它变得不可见。



查看完整回答
反对 回复 2024-01-25
  • 1 回答
  • 0 关注
  • 25 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信