gpt4 book ai didi

java - 如何使 java JPanel 和 graphics2d 透明?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:59:06 25 4
gpt4 key购买 nike

好吧,标题是不言自明的。我想使用 java 分层构建两个面板。我希望顶层包含一个包含 graphics2d 对象的 JPanel。我希望 JPanel 和 graphics2d 都具有透明背景(我仍然希望 graphics2d 绘制的内容可见)。有谁知道如何做到这一点?

最佳答案

在 JPanel 上调用 setOpaque(false) - 这不会绘制 JPanel 的背景。

取决于您覆盖什么方法来获取 Graphics2D(JPanel 不包含像组件一样的 Graphics2D 对象 - Graphics2D 对象用于绘制 JPanel)- 如果它是 paintComponent () 你应该 read the JavaDocs for JComponent - 并首先调用 super.paintComponent(g) 以确保不透明性 - 然后进行其余的绘画。

工作示例:

package com.stackoverflow.opaque;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class OpaqueExample extends JFrame {

private JLayeredPane layers;
private JPanel up, down;
private JButton toggleOpaque;

public OpaqueExample() {
layers = new JLayeredPane();

down = new JPanel();
down.setBackground(Color.GREEN);
down.setBounds(100, 100, 200, 200);
layers.add(down, new Integer(1));

up = new JPanel() {
public void paintComponent(Graphics og) {
super.paintComponent(og);

Graphics2D g = (Graphics2D)og;
GradientPaint gradient = new GradientPaint(0, 0, Color.BLUE, 10, 0,
Color.WHITE, true );

Polygon poly = new Polygon();
poly.addPoint(10, 10);
poly.addPoint(100, 50);
poly.addPoint(190, 10);
poly.addPoint(150, 100);
poly.addPoint(190, 190);
poly.addPoint(100, 150);
poly.addPoint(10, 190);
poly.addPoint(50, 100);
poly.addPoint(10, 10);

g.setPaint(gradient);
g.fill(poly);

g.setPaint(Color.BLACK);
g.draw(poly);
}
};
up.setBackground(Color.RED);
up.setBounds(150, 150, 200, 200);
layers.add(up, new Integer(2));

getContentPane().add(layers, BorderLayout.CENTER);

JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
toggleOpaque = new JButton("Toggle Opaque");
toggleOpaque.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
up.setOpaque(!up.isOpaque());
layers.repaint();
}
});
buttonPanel.add(toggleOpaque);

getContentPane().add(buttonPanel, BorderLayout.EAST);
}

public static void main(String[] args) {
JFrame f = new OpaqueExample();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 500);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

关于java - 如何使 java JPanel 和 graphics2d 透明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1386178/

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