使JTextField背景透明

时间:2014-03-27 22:06:08

标签: java swing jtextfield

我正在尝试使JTextField的背景透明,这样它下面的JLabel仍然可见,但每当在JTextField中输入文本时,您都可以看到文本。这就是我现在基本上所拥有的。

下图中的JTextField背景设置为黑色。 enter image description here

理论上,如果JTextField的背景是透明的,它应该是这样的。 enter image description here

所以,我的问题是如何让JTextField的背景透明化?

3 个答案:

答案 0 :(得分:4)

此示例使用setOpaque(false)。标签文本始终可见。我用Java 1.7和1.8测试了它。因此,如果它对您不起作用,您还做了什么,以使您的框架初始化?

public class TextField extends javax.swing.JFrame {
    public TextField() {
        initComponents();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);

        jLabel1.setText("Test");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(60, 40, 70, 14);

        jTextField1.setText("jTextField1");
        jTextField1.setOpaque(false);
        getContentPane().add(jTextField1);
        jTextField1.setBounds(50, 30, 90, 40);

        pack();
    }// </editor-fold>                        

    public static void main(String args[]) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TextField().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

答案 1 :(得分:0)

将外观设置更改为金属或窗口 如果您已将其设置为透明,它将起作用 Nimbus laf在程序运行后立即显示textareas背景信息

答案 2 :(得分:0)

看起来 Nimbus 不支持 JTextField、JTextArea 等中的透明背景。这里不是使背景透明,而是使组件设置其背景颜色以匹配其父背景的代码:

private static final HierarchyListener _hl = new HierarchyListener() {

    @Override
    public void hierarchyChanged(HierarchyEvent e) {
        Component c = e.getComponent();
        for (Component p = c; p != null; p = p.getParent()) {
            if (p.isOpaque()) {
                int bk = p.getBackground().getRGB();
                c.setBackground(new Color(bk));
                break;
            }
        }

    }
};

public static void makeComponentCopyParentBackground(Component c) {
    c.removeHierarchyListener(_hl); // Guard against client calling multiple times.
    c.addHierarchyListener(_hl);
}