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

此示例将 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);

  }

}


ABOUTYOU
浏览 30回答 1
1回答

慕容森

xy 分量没有首选大小。您可以在 JFrame 上调用pack ,它将组件调整为其首选大小。由于 xy 分量没有,因此它变得不可见。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java