如何使jPanel半透明?

5

我想添加一个半透明的jPanel。但是放置在jPanel内部的其他组件,如按钮和标签,应以100%的不透明度显示。我正在使用NetBeans设计GUI。通常,我从调色板中拖放Swing组件来设计GUI(我不编写它们)。我在属性窗口中看不到任何属性可以实现此目的。请帮助我。由于我对Java很陌生,请给我详细的答案。谢谢。


5
这个那样吗? - trashgod
2个回答

7
您可以使用JPanel.setBackground(Color bg);使面板半透明。重要的是颜色的属性。您可以构造具有alpha值的颜色来设置颜色的透明度。

panel.setBackground(new Color(213, 134, 145, 123));

最后一个参数实际上是alpha值,您可以调整它以看到效果。

以下是代码:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class PanelTest {
    public static void main(String[] args) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                PanelTest test = new PanelTest();
                test.createUI();
            }
        };
        SwingUtilities.invokeLater(runnable);
    }

    public void createUI(){
        JFrame frame = new JFrame("Panel Test");

        JPanel panel = new JPanel();

        panel.setBackground(new Color(213, 134, 145, 123));
        JButton button = new JButton("I am a button");

        JLabel label = new JLabel("I am a label");
        label.setFont(new Font("Arial", Font.BOLD, 15));

        JTextField textField = new JTextField();

        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.add(button);
        panel.add(Box.createVerticalStrut(20));
        panel.add(label);
        panel.add(Box.createVerticalStrut(20));
        panel.add(textField);

        panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));

        BottomPanel buttomPanel = new BottomPanel();
        buttomPanel.add(panel);
        frame.add(buttomPanel,BorderLayout.CENTER);

        frame.setResizable(false);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    @SuppressWarnings("serial")
    class BottomPanel extends JPanel{
        @Override
        protected void paintComponent(Graphics g) {
            for (int y = 0; y < 200; y = y + 20) {
                g.drawString("I am the string on the bottom", 5, y);
            }
        }
    }
}

这是效果图,希望能对您有所帮助。enter image description here

2
您可以像往常一样使用拖放功能创建jPanel,然后使用以下代码更改面板的颜色并将其设置为透明或半透明:
panel.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.5f));

您可以通过更改Color构造函数的前三个参数来更改颜色,这些参数代表RGB值,并且您可以通过更改第四个参数来更改透明度,该参数是颜色的alpha值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接