我有一个JButton,想把它的背景设置成一个颜色。
JButton button = new JButton();
button.setVisible(true);
button.setPreferredSize(new Dimension(student_scroll.getWidth(), 50));
button.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1));
button.setBackground(Color.BLACK);
button.setForeground(Color.WHITE);
button.setOpaque(true);
我在Mac上使用这个,显示效果很好。但是,在Windows上尝试时,前景色为白色(应该是这样的),但背景为空白。
建议添加button.setContentAreaFilled(false);
,我已经添加了,但没有效果。大多数人建议添加button.setOpaque(true);
,我也已经添加了。
还需要做什么才能使其显示黑色背景?
编辑
如要求所述,以下是SSCCE:
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MainSwing extends JFrame {
private static final long serialVersionUID = -8231889836024827530L;
public static void main(String[] args) {
try {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Test");
UIManager.put("ScrollBarUI", "main.CustomScrollBarUI");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(ClassNotFoundException e) {
System.out.println("ClassNotFoundException: " + e.getMessage());
}
catch(InstantiationException e) {
System.out.println("InstantiationException: " + e.getMessage());
}
catch(IllegalAccessException e) {
System.out.println("IllegalAccessException: " + e.getMessage());
}
catch(UnsupportedLookAndFeelException e) {
System.out.println("UnsupportedLookAndFeelException: " + e.getMessage());
}
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFrame frame = new JFrame() {
Container c = getContentPane();
JButton button = new JButton("Hello");
{
button.setText("Hello");
button.setVisible(true);
button.setPreferredSize(new Dimension(100, 50));
button.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1));
button.setBackground(Color.BLACK);
button.setForeground(Color.WHITE);
button.setOpaque(true);
c.add(button);
}
};
frame.setSize(500, 500);
frame.setBackground(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
似乎问题与这行代码有关:UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
,因为当我将其移除时,按钮就变成了黑色。
setContentAreaFilled(false)
和setBorderPainted(false)
。"填充"效果由外观委托提供,我不知道任何方法可以影响它使用的颜色。 - MadProgrammerbutton.setVisible(true);
。只需将其添加到顶级窗口(框架、窗口、对话框等)中的容器中,该容器在添加组件后进行打包,然后设置可见性。如果按钮没有文本,则可以使用(可能是透明的)图像轻松设置大小。如果按钮有文本,则最好从字体大小和文本内容以及包含它的按钮的边距和边框来确定大小。在任何情况下,我们都不需要设置首选大小。 - Andrew Thompson