How to add background image to JTextField?

僤鯓⒐⒋嵵緔 提交于 2019-12-12 18:18:41

问题


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);}  
} 


来源:https://stackoverflow.com/questions/21126994/how-to-add-background-image-to-jtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!