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



此示例向JFrame添加了一个JButton和一个JLabel。

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

我知道有一些样本显示了如何显示XY坐标,但我很想知道为什么它在这种情况下失败了。

从输出来看,似乎所有需要的侦听器都在启动,因为输出甚至显示了paintComponent((正在使用预期输出执行。

不确定是否需要,但我确实尝试了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);
}
}

xy组件没有首选的大小。您在JFrame上调用pack,它将组件的大小调整为它们喜欢的大小。由于xy组件没有,因此它变得不可见。

最新更新