问题
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))));
}
I can add these code lines to each JTextField
, but I'm looking for an easier way to do this.
回答1:
To set the same border for all JTextField
s, use the UIManager class.
UIManager.getDefaults().put("TextField.border", BorderFactory.createTitledBorder("George"));
The above code will set the default border for every JTextField
to a titled border where the title is George.
UIManager
class manages what is known as look-and-feel. I suggest reading the javadoc for class UIManager
.
EDIT
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()
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 */ );
回答2:
You can use your own extension of JTextField like this:
public class OwnJTextField extends JTextField {
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))));
}
And everywhere where you need that use OwnJTextField instead JTextField.
来源:https://stackoverflow.com/questions/59133122/customize-jtextfield-in-java-swings-add-simple-compound-custom-borders-to-jtex