Search code examples
javaswingjtextfield

Making a JTextField background transparent


I'm trying to make the background for a JTextField transparent, that way so the JLabel underneath it is still visible, but whenever entering text into the JTextField you can see the text. Here's what I have now basically.

The JTextField background is set to black in the below picture. enter image description here

In theory, if the JTextField's background was transparent it should look like this. enter image description here

So, my question is how would I make the JTextField's background transparent?


Solution

  • This example does simple use setOpaque(false). The labels text is always visible. I tested it with Java 1.7 and 1.8. So if it does not work for you, what else did you do, to initalize your frame?

    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                   
    }