【问题标题】:Custom painting of JPanelJPanel的自定义绘画
【发布时间】:2011-04-13 15:59:18
【问题描述】:

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

所以这就是交易。在我的应用程序中有背景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(及其弹出菜单)可以正确绘制。

【问题讨论】:

标签: java paint


【解决方案1】:

试试这个:

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

【讨论】:

  • 天哪,我没有尝试这个,因为我认为 RoundedPanel 根本不会画画,但我没有看到 :-) 非常感谢先生!
猜你喜欢
  • 1970-01-01
  • 2012-12-08
  • 2011-08-05
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多