以下是在特定面板3上创建9个网格布局按钮的代码。我想要的是使每个按钮的背景为黑色,上面有灰色文本。有人可以帮忙吗?
for(int i=1;i<=9;i++)
{
p3.add(new JButton(""+i));
}
以下是在特定面板3上创建9个网格布局按钮的代码。我想要的是使每个按钮的背景为黑色,上面有灰色文本。有人可以帮忙吗?
for(int i=1;i<=9;i++)
{
p3.add(new JButton(""+i));
}
请查看JButton文档。 特别注意继承自JComponent
的setBackground
和setForeground
方法。
for(int i=1;i<=9;i++)
{
JButton btn = new JButton(String.valueOf(i));
btn.setBackground(Color.BLACK);
btn.setForeground(Color.GRAY);
p3.add(btn);
}
setOpaque(true)
,否则根本不会绘制黑色背景。 - JasonsetBorderPainted(false)
可以解决上述问题。 - Homaei简单的写法:
btn.setBackground(Color.red);
使用RGB值:
btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));
for(int i=1;i<=9;i++) {
p3.add(new JButton(""+i) {{
// initialize the JButton directly
setBackground(Color.BLACK);
setForeground(Color.GRAY);
}});
}
您可能需要使用setOpaque方法来确保通过向该方法传递true显示颜色。
我尝试了之前的解决方案,但仍然无法改变颜色。偶然发现另一篇文章并解决了我的问题。按钮由不同的层组成。移除所有层可以解决问题:
btn.setOpaque(true);
btn.setContentAreaFilled(true);
btn.setBorderPainted(false);
btn.setFocusPainted(false);
btn.setBackground(Color.GRAY); // for the background
btn.setForeground(Color.white); // for the text