简体   繁体   中英

Transparent JTextField .setOpaque(false) doesn't work

JTextField textbox1;
textbox1 = new JTextField();
textbox1.setBounds((549+x),(61+y),295,17);
textbox1.setOpaque(false);
Main.panel.add(textbox1);

I need a Textbox on top of an image to show the image underneath but still be able to be typed in. I've tried using the textbox1.setOpaque(false) method but it didn't change anything and didn't throw and error. Sorry if i didn't format the code properly I tried but I just don't use this site very often.

set only the background of the text box to transparent

   setBackground(new Color(0,0,0,0)); 

Use

    setOpaque(false);

Only when your text field has child components inside the textfield you want to make visible but not the textfield itself to avoid artifacts

The following example has a text field over a red circle.

import javax.swing.*;
import java.awt.*;


public class JunkStop{

    public static void main(String[] args){
        JFrame frame = new JFrame("wakka");
        JPanel layout = new JPanel(null);   
        JPanel background = new JPanel(){
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                g.setColor(Color.RED);
                g.fillOval(100, 100, 200, 200);
            }

        };
        
        background.setOpaque(false);
        JTextField field = new JTextField("testing");
        field.setBackground( new Color(0, 0, 0, 0) );
        layout.add(field);
        layout.add(background);
        
        field.setSize(new Dimension(200, 20));
        field.setBounds(100, 150, 200, 20);
        
        background.setBounds(0, 0, 400, 400);

        frame.setContentPane(layout);
        frame.setVisible(true);
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM