【发布时间】:2012-04-30 06:53:53
【问题描述】:
您好,我无法在我的 JFrame 中引用 JPanel 的来源。我的 JPanel 在构造函数中是这样设置的,我想在 JPanel 的左边缘添加一条线。
table = new JPanel();
table.setBackground(Color.green);
table.setBounds(10,10, 600, 600);
table.setSize(width.getValue(), height.getValue());
add(table);
那么paint方法...
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawLine(table.getX(), table.getY(), table.getX(), (table.getY() + table.getHeight()));
g2d.drawLine(100, 100, (int)Math.round(cueBall.getPositionX()), (int)Math.round(cueBall.getPositionY()));
}
paint 方法中的最后一个命令与我的问题无关... 该代码似乎将原点设为 (10, 10),但将其应用于整个 JFrame 而不是 contentPane。我不完全理解 contentPane 但我认为 add() 添加到内容窗格中,从那时起您只引用 contentPane 中的坐标...我只是不明白为什么 setBounds() 在我的位置添加了 JPanel想要它是 (10,10) 仅与 contentPane 相关,但是当我paint() 时,它似乎获得了与 contentPane 相关的坐标,但参考 JFrame 绘制了这些坐标。我意识到我可以添加一个值来下移这条线,但我怀疑这是一个糟糕的解决方案。
我是否需要添加一个带有它自己的 paint() 方法的 contentPane 或类似的东西?
【问题讨论】:
标签: java swing jframe jpanel contentpane