【发布时间】:2014-11-10 22:14:56
【问题描述】:
我有一个 GUI,主面板有透明背景,所以 可以通过它们看到背景图像。问题是,点击一个 此面板之一上的按钮,在 Mac OS 上,按钮具有圆形边框,它们的背景变成不透明的颜色。我怎样才能避免这种情况?
这是一张图片:
【问题讨论】:
标签: java swing jpanel jbutton transparency
我有一个 GUI,主面板有透明背景,所以 可以通过它们看到背景图像。问题是,点击一个 此面板之一上的按钮,在 Mac OS 上,按钮具有圆形边框,它们的背景变成不透明的颜色。我怎样才能避免这种情况?
这是一张图片:
【问题讨论】:
标签: java swing jpanel jbutton transparency
只需使用setOpaque(false) 使按钮透明即可。永远不要使用 alpha 颜色作为背景颜色,Swing 只处理不透明或不透明的组件,它不知道如何处理基于 alpha 的颜色。
如果您使用基于 alpha 的背景颜色,Swing 不知道 1- 它假设在绘制组件之前正确准备 Graphics 上下文以及 2- 组件下面的组件也需要在组件更改。
随着 UI 复杂性的增加和变化开始发生(UI 已更新),使用 alpha 背景颜色会产生随机且令人讨厌的绘画伪影
请参阅Painting in AWT and Swing 和Performing Custom Painting 了解更多详情
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage background;
public TestPane() {
JButton btn = new JButton("I'm a transparent button");
btn.setOpaque(false);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(btn, gbc);
add(new JButton("I'm not a transparent button"), gbc);
try {
background = ImageIO.read(new File("C:\\hold\\thumbnails\\issue522.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
return background == null ? new Dimension(200, 200) : new Dimension(background.getWidth(), background.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g2d.drawImage(background, x, y, this);
g2d.dispose();
}
}
}
}
如果要绘制半透明背景,则需要重写组件paintComponent 方法并自己绘制,确保组件先标记为透明(不是不透明)
【讨论】: