【发布时间】:2016-04-28 12:46:05
【问题描述】:
我在具有图形的 JPanel 中有一个 JButton,但该按钮不会显示,因为它位于图形下方的图层中。 我已经读过这个:Put JLabel in front of Graphics 2D Rectangle in JPanel
但答案告诉我不要使用 NullLayoutManager。 有什么方法可以使用 NullLayoutManager,因为我需要在我的 JPanel 中专门定位我的 JButton? 如果这不可能,还有其他方法可以将 JComponent 定位在位置 x、y 吗?我也用谷歌搜索过,NullLayoutManager 是万维网给我的。
代码:
JPanel p = new JPanel(){
@Override
public void paintComponent(Graphics gr){
Graphics2D g = (Graphics2D) gr;
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 800);
g.setFont(titlefont);
g.setColor(Color.WHITE);
g.drawString("dont steal my game idea plz", 25, 100);
g.drawImage(bi, 138, 70, null);
repaint();
}
};
p.setLayout(null);
JButton b = new JButton("PLAY");
b.setLocation(100, 200);
b.setFont(ufont);
f.add(p);
p.add(b);
【问题讨论】:
-
每次我在paintComponent 内部看到
repaint()并使用null布局我都会有点恶心,就像黑板上的钉子一样——你为什么要这样做?谁在教你和许多其他新手这些坏习惯?请阅读教程以了解如何正确执行此操作。并阅读本网站上 Swing 专家对类似问题的回答,以了解如何正确地做事。这一切都被问过很多次了。 -
“但按钮不会显示在图形下方的图层中” - 不,不是,
paintComponent在paintChildren之前被调用,它会绘制组件。您通过不调用super.paintComponent“可能”来打破油漆链的事实与它有关 -
But the answers tell me not to use the NullLayoutManager- 那你为什么不试着听听答案???为什么你认为我们会因为你再次问同样的问题而改变答案???because I need to specifically position my JButton in my JPanel?- 所以使用布局管理器来定位按钮。顺便说一句,您也没有理由绘制文本。您只需使用 JLabel。因此,布局管理器将能够轻松处理标签和按钮。
标签: java swing graphics paintcomponent