使用
选择的WindowsLookAndFeelUIManager.getSystemLookAndFeelClassName()
因为我在Windows上工作会导致意外行为。按钮的背景颜色发生变化。有时他们不在我目前的项目中,但我无法发现差异。
行为错误的按钮:
具有默认LookAndFeel的按钮:
我将给出一个产生意外行为的工作示例:
import javax.swing.UIManager;
public class Context {
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
new VocableEditor();
}
}
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class VocableEditor extends JFrame implements WindowListener, ActionListener {
private static final long serialVersionUID = -6209345602005762300L;
private Button b_save, b_discard;
private GridBagLayout layout;
public VocableEditor() {
setTitle("vocableEditorTitle");
setSize(600, 400);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(this);
layout = new GridBagLayout();
setLayout(layout);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = 1;
c.gridheight = 1;
b_discard = new Button("discardAndLeave");
b_discard.addActionListener(this);
c.gridwidth = 1;
c.gridx = 2;
add(b_discard, c);
b_save = new Button("saveAndExit");
b_save.addActionListener(this);
c.gridx = 3;
add(b_save, c);
setVisible(true);
}
public void end(boolean save) {
System.out.println(save);
dispose();
}
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b_save) {
end(true);
} else if (e.getSource() == b_discard) {
end(false);
}
}
}
import java.awt.Color;
import javax.swing.JButton;
public class Button extends JButton {
private static final Color BACKGROUND_COLOR = new Color(60, 90, 180);
public Button(String name) {
super(name);
setBackground(BACKGROUND_COLOR);
setForeground(Color.WHITE);
}
}
答案 0 :(得分:2)
经过数小时的研究,我找到了解决方案。甲骨文表示,即使我无法理解为什么LAF必须是这样不透明的,所以显示出所显示的行为。解决方案是将以下行添加到按钮的构造函数中:
setContentAreaFilled(false);
setOpaque(true);
第一行禁用绘制背景,第二行重新启用它但是错过了LAF会改变外观的部分。