gpt4 book ai didi

java - WindowsLookAndFeel 有关按钮颜色的意外行为

转载 作者:行者123 更新时间:2023-12-02 02:14:12 26 4
gpt4 key购买 nike

使用选择的WindowsLookAndFeel

UIManager.getSystemLookAndFeelClassName()

因为我正在 Windows 上工作,所以导致了意外的行为。按钮的背景颜色发生变化。有时他们在我当前的项目中没有,但我无法发现差异。

行为错误的按钮:

/image/d5OUk.png

具有默认 LookAndFeel 的按钮:

/image/AMoHv.png

我将给出一个产生意外行为的工作示例:

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);
}
}

最佳答案

经过几个小时的研究,我找到了解决方案。 Oracle 表示,即使我不明白为什么 LAF 必须如此不透明,但所显示的行为是想要的。解决方案是将以下几行添加到按钮的构造函数中:

setContentAreaFilled(false);
setOpaque(true);

第一行禁用绘制背景,第二行重新启用它,但错过了 LAF 更改外观的部分。

关于java - WindowsLookAndFeel 有关按钮颜色的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49521464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com