views:

598

answers:

3

Is there anyway to remove a border in a JTextField?

txt = new JTextField();
txt.setBorder(null);   // <-- this has no effect.

I would really want it to look like a JLabel - but I still need it to be a JTextField because I want people to be able highlight it.

+1  A: 

Try setting it to BorderFactory.createEmptyBorder() instead of null. Sometimes this "does the trick" because setting it to null actually has a different meaning.

If that does not work, it is possible that the look and feel you are using is overriding something. Are you using the default or something custom?

Uri
Sometimes this does the trick ???if that's your attitude to programming I would not want to get near my team. shall I add revalidate and repaint as well ?
Markus V.
@Markus, in my experience with Swing, problems with it are often not limited to one issue, but rather have to be peeled like an onion. without seeing your entire code, I don't know if this would completely solve the problem. If I was dealing with the bug, this would be the first thing I would try. If it didn't work, I'd try to investigate whether the look-and-feel (if you're using something fancy) is interfering.
Uri
+2  A: 
JTextField textField = new JTextField();
textField.setBorder(javax.swing.BorderFactory.createEmptyBorder());

http://java.sun.com/javase/6/docs/api/javax/swing/BorderFactory.html

When setting the border to 'null', you're actually telling the look & feel to use the native border style (of the operating system) if there is one.

Björn
+1 for mentioning the reason WHY null does not work as expected
Nils Schmidt
should be -1. because it does not work. the solution that works is the one suggested that says:override setBorder to do nothing
Markus V.
This may or may not work depending upon context, for non-obvious reasons. http://stackoverflow.com/questions/2281539/setborder-on-jtextfield-does-not-work-or-does-it However, it is good information and I don't see any reason for downvoting it.
Tom Hawtin - tackline
As Tom says, this may work upon context. Given the context from OP, this would work splendidly. Thanks Tom, btw. :)
Björn
+2  A: 

From an answer to your previous question you know that some PL&Fs may clobber the border.

The obvious solution is to therefore override the setBorder method that the PL&F is calling, and discard the change.

JTextField text = new JTextField() {
    @Override public void setBorder(Border border) {
        // No!
    }
};
Tom Hawtin - tackline
+1. It's not elegant, but probably the best that can be done considering the limitations of Swing.
finnw