有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在区域JPanel中创建半透明JPanel

我想制作一个半透明的JPanel,我可以为它选择x坐标、y坐标、宽度和高度。我已经找到了一些材料,使半透明的JPanel填充其父容器,但我不需要这种效果。我需要一个半透明的JPanel,它的位置可以在父容器中指定,这样只有这个区域是半透明的,而父容器中的其他区域是不透明的。我试过这个代码,但不正确。合成的面积比我想要的面积小。怎么了,或者我怎样才能得到这种效果

public class TranslucentJPanel extends JPanel {

    private float transparency;

    public TranslucentJPanel(){
    }



    /**set the transparency
     * 
     * @param transparency:the transparency you want to set
     * 
     * @return void
     */
    public void setTransparent(float transparency) {
        this.transparency = transparency;
    }

    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);

        Graphics2D graphics2d = (Graphics2D) g.create();
        graphics2d.setComposite(AlphaComposite.SrcOver.derive(transparency));

        graphics2d.fill(getBounds());
        graphics2d.dispose();
    }
}

共 (1) 个答案

  1. # 1 楼答案

    所以,我马上想到两件事

    首先,不要使用getBounds,因为Grapghics上下文已经被转换为组件x/y位置,所以你要加倍。相反,只需使用0x0并提供widthheight,类似于

    graphics2d.fillRect(0, 0, getWidth(), getHeight());
    

    另外,请记住,大多数Swing组件在默认情况下都是不透明的,这包括JListJScrollPaneJViewport,如果希望它们完全透明,则需要将它们设置为透明

    此外,JList使用的“默认”渲染器也会将其自身渲染为不透明,因此如果希望项目透明,则需要能够提供自己的渲染器

    Translucent

    import java.awt.AlphaComposite;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridBagLayout;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.imageio.ImageIO;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.border.EmptyBorder;
    
    public class Test {
    
        public static void main(String[] args) {
            new Test();
        }
    
        public Test() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }
    
                    DefaultListModel<String> model = new DefaultListModel<>();
                    model.addElement("Bananas");
                    model.addElement("Apples");
                    model.addElement("Pears");
                    model.addElement("Grapes");
                    model.addElement("Tim Tams");
    
                    JList list = new JList(model);
                    list.setCellRenderer(new DefaultListCellRenderer() {
    
                        @Override
                        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                            setOpaque(isSelected);
                            return this;
                        }
    
                    });
                    list.setOpaque(false);
                    JScrollPane sp = new JScrollPane(list);
                    sp.setOpaque(false);
                    sp.getViewport().setOpaque(false);
    
                    TranslucentPane tp = new TranslucentPane();
                    tp.setLayout(new GridBagLayout());
                    tp.setLayout(new BorderLayout());
                    tp.add(sp);
    
                    JFrame frame = new JFrame("Testing");
                    frame.setContentPane(new BackgroundPane());
                    frame.setLayout(new GridBagLayout());
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(tp);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TranslucentPane extends JPanel {
    
            private float alpha = 0.75f;
    
            public TranslucentPane() {
                setOpaque(false);
                setBorder(new EmptyBorder(5, 5, 5, 5));
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setComposite(AlphaComposite.SrcOver.derive(alpha));
    
                g2d.setColor(getBackground());
                g2d.fillRect(0, 0, getWidth(), getHeight());
                g2d.dispose();
            }
    
        }
    
        public class BackgroundPane extends JPanel {
    
            private BufferedImage background;
    
            public BackgroundPane() {
                try {
                    background = ImageIO.read(new File("C:\\Users\\shane\\Dropbox\\MegaTokyo\\thumnails\\megatokyo_omnibus_1_3_cover_by_fredrin-d4oupef.jpg"));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(background.getWidth(), background.getHeight());
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                int x = (getWidth() - background.getWidth()) / 2;
                int y = (getHeight() - background.getHeight()) / 2;
                g.drawImage(background, x, y, this);
            }
    
        }
    
    }