简体   繁体   中英

Java: How do you style Swing components?

I'm writing my first Java project.

I was wondering if it's possible to style the Swing components (set a background color, remove the borders from the buttons, etc.)

If it's as simple as just changing the font, the background, the borders etc. Swing can do all these by default. Ie for a JButton:

JButton aButton ...
aButton.setBackground(new Color(...));  
aButton.setForeground(new Color(...));  
aButton.setFont(new Font(...));  
aButton.setBorder(null);  

Have a look at most of these methods at the JComponent . Or, for more component-specific methods, at the component's javadoc.

I would recommend you to read some basics in The Java Tutorial or the JComponent API or even a book such as Filthy Rich Clients or Java HowTo Program .

A custom Look and Feel would be a little too much. I suggest to first see if the above solutions don't fit your needs and then go for that.

It's certainly possible to do significant customisations because that is what the different look and feel options do.

You could look at the pluggable look and feel architecture , though this may be way overkill for what you want.

Alternatively you could perhaps subclass the existing components and use/override their existing methods, if it is only minor tweaks you need.

There are a few open soruce projects that allow you to style Swing components with CSS-like format.

You should take a look at the Java CSS project. It was introduced in this blog post .

For an application wide change, creating (or extending) your own pluggable look and feel is probably the correct solution. For special effects, you should also take a look at the painters framework . Note that they are part of swingx, not core Swing.

If you want to style your components heavily, getting a 3rd party Look-And-Feel and using that may be your best choice. My personal favorite is Substance which even has an API for creating completely custom LAFs on top of Substance.

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