我不太擅长这个,希望能得到一些比我更了解这个问题的人的帮助。
我的应用程序中有一个带图像的背景JPanel。然后有一个小的JPanel,我正在尝试为其创建自定义绘画。我想要一个带有圆角和半透明背景的JPanel,所以我修改了paintComponent方法以填充半透明圆角矩形。但是当我在里面放置组件,比如JComboBox时,项目列表出现并且我点击其他地方关闭它时,JPanel会以原始方式进行绘制,使其四周变得半透明,但小矩形仍然使用原始的灰色背景颜色绘制。我看到这与在其父类上调用paintComponent或paintChildren有关,但我不知道如何组织这些方法或将它们放在哪里。我还遇到了透明颜色彼此重叠的问题。
以下是示例源代码:
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的JPanel并具有自定义paintComponent方法,则JComboBox(及其弹出菜单)会正确绘制。