2011-10-12 37 views
1

在我的Java Swing应用程序,我想提出锁定图像一个JTextField不可编辑里面,出现这样的:如何在不可编辑的JTextField中显示图像?

Locked JTextField

我已经创建了一个JTextField,并插入一个JLabel它上面和定义JLabel的锁定图标。如果JTextField是可编辑的,那么JLabel就像上面的图片显示的那样显示正常,但是如果JTextField不可编辑,那么图像根本不会出现。

我该如何解决这个问题?

+0

为了更快提供更好的帮助,请发布[SSCCE](http://pscode.org/sscce.html)。 在代码中生成一个小图像。 –

回答

2

你可以尝试添加两个标签(图标)和文本字段中的面板。从文本框中删除边框,并在面板周围添加一个公共边框。将背景设置为与文本框的背景相同。

+0

谢谢大家的好解决方案。这对我来说是最简单的。最后的组件看起来非常好。谢谢StanislavL。 – Brad

0

写自己的类,它扩展JTextField和这个类,你必须与职位精心此改变paintComponent(Graphics g)

1)Icon

因为

2)把你Custom JTextField到resizibale Container内,如果Icon停留在右侧,如果尺寸正确调整为Custom JTextFieldIcon里面,

3)setEditable(true)setEditable(false)创建构造与Icon

1

为什么不使用jTextPane?

try { 
    // Get the text pane's document 
    JTextPane textPane = new JTextPane(); 
    StyledDocument doc = (StyledDocument)textPane.getDocument(); 

    // The image must first be wrapped in a style 
    Style style = doc.addStyle("StyleName", null); 
    StyleConstants.setIcon(style, new ImageIcon("imagefile")); 

    // Insert the image at the end of the text 
    doc.insertString(doc.getLength(), "ignored text", style); 
} catch (BadLocationException e) { 
} 
0

创建自定义Border让我们称之为IconBorder。查看MatteIcon的源代码,然后对其进行定制以仅绘制单个图像。然后,您可以使用以下代码将边框添加到文本字段:

Border border = new CompoundBorder(textField.getBorder(), new IconBorder(...)); 
textField.setBorder(border); 
相关问题