Вопрос

I have tons of jbuttons, jtextfields, jlabels, jmenus, gui items and it is extremely time consuming to set the background color and foreground color one at a time.

I want to be able to color the fonts(foreground) and backgrounds all the jmenus, jmenuitems,jtextfields,jbuttons, etc quickly/concisely in my project instead of having to set them one at a time.

Is there any technique to do this more concisely instead of doing it one at a time?

Это было полезно?

Решение

1) most eficient way would be to use Custom Look and Feel, part of them have got a nice Themes

2) set value to the UIDefault, Listing UIDefault Properties

EDIT:

best of all UIManager Defaults by @camickr

Другие советы

You can combine Swing with CSS or use a Swing Look & Feel in order to create a standard look for your components. The Java site says:

Before we get into a CSS implementation, let's consider the alternative: a custom look and feel. Swing Look and Feels (L&Fs) are sets of classes that implement the actual drawing of components at a very low level (think lines and bitmaps). They can be swapped out for new ones at runtime, often to implement the look of a native platform; i.e., the JDK for OSX has a set of classes that make Swing apps look like native Aqua apps, with candy buttons and blue tint. Custom L&Fs are powerful, but not trivial or quick to build. You will usually have to touch 20 or so classes and implement a whole bunch of special drawing code.

So CSS is easier to use. The same article goes on to give a tutorial about how to implement the CSS with Swing. They provide a nice walkthrough of creating the right rules and then going on to implement them in CSS. However, this is not simply "copy and paste" code.

If you'd just like to use a package (without having to code it yourself) the answers to the question Can I use CSS for Java Swing? suggest Flying Saucer and Jaxx.

They're all JComponents so you can make an ArrayList of everything:

//Adding everything to the ArrayList
ArrayList<JComponent> myComponents = new ArrayList<JComponents>();

JButton b1 = new JButton("Button 1");
myComponents.add(b1);

JMenuItem item = new JMenuItem("Menu Item 1");
myComponents.add(item);

//Coloring the foreground/background
for(JComponent j : myComponents) {
    j.setForeground(new Color("BLUE"));
    j.setBackground(new Color("RED"));
}

If you use a Look and Feel that honors the UI constants in javax.swing.UIManager then you can just set them. There are values for e.g. panel background. If not or if you can't control the look enough by this you can write you own UI delegate that draws a specific component (e.g. javax.swing.plaf.ButtonUI for JButtons). If even this is not enough you can write your own Look And Feel. If you just extend the Metal LnF it is not that hard, you would write own UI delegates and set properties, like above, but centralized.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top