在Java Swings中自定义JTextField-向JTextField添加简单/复合/自定义边框 [英] Customize JTextField in Java Swings - add simple/compound/custom borders to JTextField
问题描述
我有一个具有很多形式的Netbeans Java项目.这些形式有许多JTextField
.我想用自定义边框自定义那些文本字段.
I have a Netbeans java project with a lot of forms. There are many JTextField
s 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.
推荐答案
To set the same border for all JTextField
s, 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屋!