此示例將 JButton 和 JLabel 添加到 JFrame。還有一個(gè) JComponent 應(yīng)該顯示光標(biāo)的 XY 坐標(biāo)。我知道有一些示例展示了如何顯示 XY 坐標(biāo),但我很想知道為什么它在這種情況下失敗。查看輸出,似乎所有必需的偵聽(tīng)器都在觸發(fā),因?yàn)檩敵錾踔溜@示 PaintCompoent() 正在以預(yù)期的輸出執(zhí)行。不確定是否需要,但我確實(shí)嘗試了 setVisible(true) 和 setBounds()。是什么阻止了具有 XY 坐標(biāo)的 JComponent 出現(xiàn)。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貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
xy 分量沒(méi)有首選大小。您可以在 JFrame 上調(diào)用pack ,它將組件調(diào)整為其首選大小。由于 xy 分量沒(méi)有,因此它變得不可見(jiàn)。
添加回答
舉報(bào)
0/150
提交
取消