I know how to add background image to JPanel (creating ImagePanel class that extends JPanel and overload it's paintComponent() method), BUT this trick with JTextField not working properly: Displays image, but not text. So, how to add background image to JTextField properly?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You need to add the text field to the label. Something like:
JTextField textField = new JTextField(10);
textField.setOpaque( false );
JLabel label = new JLabel( new ImageIcon(...) );
label.setLayout( new BorderLayout() );
label.add( textField );
回答2:
Found this online for you.
import java.awt.*;
import javax.swing.*;
class Testing extends JFrame
{
public Testing()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel(new BorderLayout());
JTextField tf = new JTextField(5);
JLabel label = new JLabel(new ImageIcon("Test.gif"));
label.setOpaque(true);
label.setBackground(tf.getBackground());
label.setPreferredSize(new Dimension(label.getPreferredSize().width,tf.getPreferredSize().height));
p.setBorder(tf.getBorder());
tf.setBorder(null);
p.add(label,BorderLayout.WEST);
p.add(tf,BorderLayout.CENTER);
JPanel p1 = new JPanel();
p1.add(p);
getContentPane().add(p1);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args){new Testing().setVisible(true);}
}