问题描述
这是我在这里的第一篇文章,所以我很抱歉这不是正确的提问方式。我想要改善的建议。
提到这个问题,我看到了一个有关透明Jtextfield的youtube视频(https://www.youtube.com/watch?v=2Ruc5rkDg1E),但是相同的代码并没有提供相同的输出。
import javax.swing.*;
import java.awt.*;
public class TextField3 {
public TextField3() {
ImageIcon icon = new ImageIcon("pic1.jpg");
//JLabel l1 = new JLabel();
//l1.setBounds(0,900,500);
//l1.setIcon(icon);
Color back = new Color(0,80);
Color fore = new Color(255,255,255);
Font font = new Font("Times New Roman",Font.BOLD,24);
JFrame f1 = new JFrame("My First TextField");
f1.setBounds(150,50,500);
//f1.setVisible(true);
f1.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
f1.getContentPane().setLayout(null);
JLabel l1 = new JLabel();
l1.setBounds(0,500);
l1.setIcon(icon);
JTextField tf = new JTextField("TextField");
//tf.setopaque(false);
tf.setBounds(275,150,350,60);
tf.setVisible(true);
tf.setHorizontalAlignment(JTextField.CENTER);
tf.setBackground(back);
tf.setForeground(fore);
tf.setFont(font);
f1.add(l1);
f1.add(tf);
f1.setVisible(true);
}
public static void main(String[] args) {
TextField3 tf = new TextField3();
}
}
The output from the youtube video.
以上代码与视频代码不完全相同。实际上,视频中的代码生成了一个空白的JFrame,然后我将代码的JLabel部分移到了JFrame的部分下方,然后在第二张图像中生成了输出。
我搜索了此问题,发现将setopaque设置为false将解决此问题。但是当我尝试它时,JTextField完全消失了,只显示了背景图像。有人可以帮助解决这个问题吗?
解决方法
Swing旨在与布局管理器一起使用。您不应使用null布局,也不应使用setBounds()。
Swing是基于父子关系设计的。如果要使文本字段显示在标签顶部,请不要将两个组件都添加到框架中。相反,您需要这样的结构:
- frame
- background label
- text field
因此您的基本代码应类似于:
JTextField textField = new JTextField("text");
textField.setBackground(...);
JLabel background = new JLabel(...);
label.setlayout( new GridBagLayout() );
label.add(textField,new GridBagConstraints());
frame.add(label,BorderLayout.CENTER);
现在,您将在标签中心看到文本字段。
但是,由于Swing无法正确处理半透明性,因此文本字段的半透明背景仍然会出现问题。有关更多信息和解决方案,请查看:Why does the alpha in this timer draw on top of itself in this Java Swing Panel?
,您需要使用setOpaque(false)
方法来使JTextField透明。应该可以。