gpt4 book ai didi

java - JPanel的自定义绘画

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:40:21 26 4
gpt4 key购买 nike

我不是很擅长这个,我希望能从比我更了解这个问题的人那里得到一些帮助。

所以这是交易。在我的应用程序中,背景 JPanel 上绘制了图像。然后是一个小的 JPanel,我正在尝试为其创建自定义绘画。我想让 JPanel 具有圆角和半透明背景,所以我修改了 paintComponent 方法来填充半透明圆角矩形。但是,当我将组件放入 JComboBox 之类的内部时,会出现项目列表,然后我单击其他地方将其关闭 JPanel 以原始方式绘制自身,使其四周呈半透明状态,但小矩形绘制有原始灰色背景色。我看到它必须通过在其父对象或 paintChildren 上调用 paintComponent 来做一些事情,但我不知道如何组织这些方法或将它们放在哪里。我也有透明颜色相互重叠的问题。

这是一个示例源代码:

public class RoundedPanel extends JPanel {

private final int radius;


public RoundedPanel(int cornerRadius) {
radius=cornerRadius;
}

public void paintComponent(Graphics g) {
Color bg = getBackground();
g.setColor(new Color(bg.getRed(),bg.getGreen(),bg.getBlue(),40));
g.fillRoundRect(0,0, getWidth()-1, getHeight()-1, radius, radius);
g.setColor(new Color(0,0,0,70));
g.drawRoundRect(0,0, getWidth()-1, getHeight()-1, radius, radius);
}

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 300);
frame.setLocation(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel content = new JPanel();
JPanel wl = new JPanel();
JPanel el = new JPanel();
JPanel sl = new JPanel();
JPanel nl = new JPanel();
RoundedPanel rp = new RoundedPanel(50);
JComboBox combobox = new JComboBox();

frame.setContentPane(content);
content.setBackground(Color.red);
content.setLayout(new BorderLayout());
wl.add(new JButton("west"));
el.add(new JButton("east"));
sl.add(new JButton("south"));
nl.add(new JButton("north"));
content.add(wl,BorderLayout.WEST);
content.add(el,BorderLayout.EAST);
content.add(nl,BorderLayout.NORTH);
content.add(sl,BorderLayout.SOUTH);

content.add(rp,BorderLayout.CENTER);
rp.setBackground(Color.BLACK);

combobox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Třída 1.B", "Třída 1.C", "Třída 2.C" }));
rp.add(combobox);
frame.setVisible(true);
}
}

我希望有些人能帮助我 :-) 谢谢

编辑:我发现如果弹出菜单在包含 JComboBox 并具有自定义 paintComponent 方法的 JPanel 外部重叠,则 JComboBox(及其弹出菜单)可以正确绘制。

最佳答案

试试这个:

RoundedPanel rp = new RoundedPanel(50);
rp.setOpaque(false);

关于java - JPanel的自定义绘画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3734500/

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