在回顾了许多以前的StackOverflow帖子之后,我仍然无法让JButton变成黑色,而不是默认的颜色。下面是我的按钮的样子:

这是我的密码:
public void setStartButton() {
JPanel panel = this.jPanel1;
panel.setLayout(null);
JButton button = new JButton("START");
// size and location of start button
int res = java.awt.Toolkit.getDefaultToolkit().getScreenResolution();
int length = (int) Math.floor(10.0*res/25.4); // side lengths of square button
int offset = length/2; // because button should be centered...but its x and y location are given by its upper left hand corner
button.setBounds(centerX-offset, centerY-offset, length, length);
// color of start button
button.setBackground(BLACK);
button.setOpaque(true);
button.setContentAreaFilled(false);
// font
button.setFont(new Font("Arial", Font.PLAIN, 8));
button.setVisible(true);
panel.add(button);
}顺便说一句,当我将setContentAreaFilled改为true时,没有什么不同。
我知道这个函数确实被调用了,因为我的按钮的位置和字体信息运行得很好。
任何帮助都将不胜感激!谢谢!
发布于 2017-04-09 22:11:38
JButton由一系列层组成,包括content、border和focus层。根据你想要做的事情,你可能需要把它们全部删除,例如.

public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
setStartButton();
}
public void setStartButton() {
JButton button = new JButton("START");
button.setMargin(new Insets(20, 20, 20, 20));
// color of start button
button.setOpaque(true);
button.setContentAreaFilled(true);
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setBackground(BLACK);
button.setForeground(WHITE);
// font
button.setFont(new Font("Arial", Font.PLAIN, 8));
add(button);
}
}我还强烈鼓励您考虑使用适当的布局管理器,并使用它的属性和JButton生成所需的填充,它们将与不同系统之间的字体度量一起工作,以便为按钮生成合适的大小。
https://stackoverflow.com/questions/43311214
复制相似问题