问题是,JFrame 的默认Layout 管理器是BorderLayout,这意味着您的ShowImage 窗格正在填充框架的整个区域(黑色)。我敢打赌,如果您将ShowPane 的背景更改为红色。它会显示为完全填充为红色
现在您可以查看 A Visual Guide to Layout Managers 或更改 ShowPane 的工作方式
更新
抱歉,我不熟悉 Java 7 中的新 Transparency API(仍在使用 Java 6 hack ;))
您能帮我验证一下这就是您正在寻找的那种效果吗?读取的正方形将是图像(黑色背景是框架-nb,我只捕获了框架)
更新
首先您需要阅读Window.isOpaque 和Window.setBackground 以了解此解决方案的工作原理。
接下来,不要使用Window.setOpacity,它不会达到你想要的效果。主要原因是 opacity 值应用于父级及其子级(最初是通过我)。
那么,框架代码:
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make sure where in the top left corner, please lookup how
// to find the screen insets ;)
setLocation(0, 0);
setSize(dim);
// Set undecorated
setUndecorated(true);
// Apply a transparent color to the background
// This is ALL important, without this, it won't work!
setBackground(new Color(0, 255, 0, 0));
// This is where we get sneaky, basically where going to
// supply our own content pane that does some special painting
// for us
setContentPane(new ContentPane());
getContentPane().setBackground(Color.BLACK);
setLayout(new BorderLayout());
// Add out image pane...
ShowImage panel = new ShowImage();
add(panel);
setVisible(true);
ContentPane。基本上,我们需要“欺骗”绘制引擎,让其思考透明(不透明)的位置,然后绘制我们自己的不透明度
public class ContentPane extends JPanel {
public ContentPane() {
setOpaque(false);
}
@Override
protected void paintComponent(Graphics g) {
// Allow super to paint
super.paintComponent(g);
// Apply our own painting effect
Graphics2D g2d = (Graphics2D) g.create();
// 50% transparent Alpha
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2d.setColor(getBackground());
g2d.fill(getBounds());
g2d.dispose();
}
}
我很抱歉我之前的回答,但我希望这可以弥补它;)
使用按钮更新
我就是这样修改的
ShowImage panel = new ShowImage();
panel.setBackground(Color.RED);
setContentPane(new ContentPane());
getContentPane().setBackground(Color.BLACK);
setLayout(new BorderLayout());
add(panel);
JPanel pnlButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
pnlButtons.setOpaque(false);
pnlButtons.add(new JButton("<<"));
pnlButtons.add(new JButton("<"));
pnlButtons.add(new JButton(">"));
pnlButtons.add(new JButton(">>"));
// Okay, in theory, getContentPane() is required, but better safe the sorry
getContentPane().add(pnlButtons, BorderLayout.SOUTH);
setVisible(true);