如何在不可编辑的 JTextField 中显示图像?
在我的 Java Swing 应用程序中,我想在不可编辑的 JTextField 中放置一个锁定图像,如下所示:
我创建了一个 JTextField,并在其上方插入了一个 JLabel,并为 JLabel 定义了锁定图标。如果 JTextField 是可编辑的,那么 JLabel 将显示正常,如上图所示,但如果 JTextField 不可编辑,则根本不会显示图像。
我该如何解决这个问题?
In my Java Swing application i want to put a lock image inside a JTextField that is not editable, to appear like this :
I have created a JTextField, and inserted a JLabel above it and defined the lock icon for the JLabel. If the JTextField is editable then the JLabel appears fine as the image above shows, but if the JTextField is not editable then the image does not appear at all.
How can i fix that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以尝试在面板中添加标签(用于图标)和文本字段。从文本字段中删除边框并在面板周围添加公共边框。将背景设置为与文本字段的背景相同。
You can try to add both label (for icon) and the textfield in a panel. Remove border from the textfield and add a common border around the panel. Set background to be the same as the textfield's background.
为什么不使用 jTextPane ?
Why dont you use a jTextPane ?
编写自己的扩展
JTextField
的类,并且在该类中,您必须覆盖paintComponent(Graphics g)
1) 仔细使用
Icon
的位置,因为
2)将您的
Custom JTextField
放入 resizibaleContainer
,尝试Icon
是否保持在右侧静止状态,以及调整大小对于Custom JTextField< 是否正常工作/代码> 与里面的
Icon
,3) 使用
Icon
为setEditable(true)
和setEditable(false)
创建构造函数write own Class that extends
JTextField
and inside this class you have to overidepaintComponent(Graphics g)
1) carefully with positions for
Icon
because
2) put your
Custom JTextField
to the resizibaleContainer
, try ifIcon
stay still on right side, if resize works correctly forCustom JTextField
withIcon
inside,3) create constructor for
setEditable(true)
andsetEditable(false)
withIcon
创建一个自定义
Border
让我们将其命名为 IconBorder。查看 MatteIcon 的源代码,然后将其自定义为仅绘制单个图像。然后,您可以使用如下代码将边框添加到文本字段:Create a custom
Border
lets call it IconBorder. Take a look at the source code for MatteIcon and then customize it to only paint a single image. Then you would add the Border to the text field with code like:您使用的是 Java 7 吗?然后使用 JLayeredPane。
Are you using Java 7? Then use a JLayeredPane.