在Java Swings中自定义JTextField-向JTextField添加简单/复合/自定义边框 [英] Customize JTextField in Java Swings - add simple/compound/custom borders to JTextField

查看:241
本文介绍了在Java Swings中自定义JTextField-向JTextField添加简单/复合/自定义边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有很多形式的Netbeans Java项目.这些形式有许多JTextField.我想用自定义边框自定义那些文本字段.

I have a Netbeans java project with a lot of forms. There are many JTextFields in those forms. I would like to customize those text fields with a custom border.

 private void tfUserNameFocusGained(java.awt.event.FocusEvent evt) {                                       
        tfUserName.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 255)), javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 255))), javax.swing.BorderFactory.createMatteBorder(0, 4, 2, 0, new java.awt.Color(255, 255, 255))));
 }

private void tfUserNameFocusLost(java.awt.event.FocusEvent evt) {                                     
        tfUserName.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)), javax.swing.BorderFactory.createMatteBorder(0, 4, 2, 0, new java.awt.Color(255, 255, 255))));
}

我可以将这些代码行添加到每个JTextField中,但是我正在寻找一种更简单的方法来实现此目的.

I can add these code lines to each JTextField, but I'm looking for an easier way to do this.

推荐答案

要为所有JTextField设置相同的边框,请使用

To set the same border for all JTextFields, use the UIManager class.

UIManager.getDefaults().put("TextField.border", BorderFactory.createTitledBorder("George"));

上面的代码会将每个JTextField的默认边框设置为标题为 George 的标题边框.

The above code will set the default border for every JTextField to a titled border where the title is George.

UIManager类管理所谓的外观.我建议阅读类UIManager javadoc .

UIManager class manages what is known as look-and-feel. I suggest reading the javadoc for class UIManager.

要在JTextField获得焦点或失去焦点时更改边框,请使用方法focusGained()和方法focusLost()FocusEvent参数.该参数包含事件的来源".

For changing the border when a JTextField gains or loses focus, use the FocusEvent parameter of the method focusGained() and method focusLost(). The parameter contains the "source" of the event.

evt.getSource()

您知道来源是JTextField,因此只需将其投射并设置边框即可.

You know that the source is a JTextField so just cast it and set the border.

JTextField textField = (JTextField) evt.getSource();
textField.setBorder( /* whatever border you need */ );

这篇关于在Java Swings中自定义JTextField-向JTextField添加简单/复合/自定义边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆