简体   繁体   中英

Reset/remove a border in Swing

Here's a very specific coding question:

I've recently been asked to maintain some old-ish Java Swing GUI code at work and ran into this problem:

I've attached my own subclass of InputVerifier called MyFilenameVerifier to a JTextField (but it may as well be any JComponent for these purposes). I've overridden the verify() method such that it calls super.verify(input) (where input is the JComponent parameter to verify()). If super.verify(input) comes back false, I do:

input.setBorder(BorderFactory.createLineBorder(Color.RED));

This is a convention used throughout the UI of this application that started long before me, so I don't have a lot of choice as far as using other ways to get the users attention (wish I did). This is just the way it works.

Problem is, once the user goes back and types something valid into the text field, I need a way to set it back to default border (instead of just saying set it to Color.GRAY or whatever, which is a different color from its original border). I need a way to say, "remove the extra decoration and go back to normal" or just set the border to its default, in other words.

在将边框设置为红色之前,您不能只调用input.getBorder()并将其缓存在某个位置吗?

Or without caching anything, you could tell the JComponent to update its UI back to the look and feel's defaults via component.updateUI. That should make the component reset its colors, borders, fonts, etc to match the original settings.

input.getBorder()

如果没有人看到过这个问题,那我真是太棒了,而我没有提出这个问题,我就没有打屁股吗?

Not sure how your system is build, but I think you can store the original border before changing it. So you can change it back later

// assuming the Border was not null before
if (!super.verify(input)) {
    original = input.getBorder();
    input.setBorder(...);
} else {
    if (original != null) {
        input.setBorder(original);
        original = null;  // not needed
    }
}

You need to preserve the existing border when you change it.

One way to do this is to use the methods putClientProperty() and getClientProperty(), which you'll find documented in the API.

Another possibility, if there are only a few input widgets you need this for is to subclass, eg JTextField, add setBorderOverride() and modify getBorder() to return "overriddingBorder" if it is not null.

Then you just use setBorderOverride(redBorder) to make it red and setBorderOverride(null) to clear it.

This of course depends on the painting to use getBorder(), which it may or may not do, and which may be implementation specific.

顺便说一句,您只需要对边框的一个静态引用-这是所有JTextField都使用的相同边框实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM