我正在使用Nimbus UI Defaults和JProgressBar组件。问题在于,当我想手动更改每个进度条的进度颜色时,我会通过设置JProgressBar.setUI()函数来使用BasicProgressBarUI。但这会带来更多麻烦,因为我只想更改进度条颜色,似乎我失去了jprogressbar的默认外观(边框、背景色消失)。
因此,我可以在代码初始化时设置Nimbus ProgressBar的UIDefaults,这样可以解决问题。
但我想动态地更改每个进度条的颜色。有没有其他方法可以更改JProgressBar的进度颜色?
因此,我可以在代码初始化时设置Nimbus ProgressBar的UIDefaults,这样可以解决问题。
但我想动态地更改每个进度条的颜色。有没有其他方法可以更改JProgressBar的进度颜色?
public class ProgressGenerator extends JFrame {
protected int minValue = 0;
protected int maxValue = 100;
protected int counter = 0;
protected JProgressBar progressBar;
public ProgressGenerator() {
super("JProgressBar Demo");
setSize(300, 100);
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
progressBar = new JProgressBar();
progressBar.setMinimum(minValue);
progressBar.setMaximum(maxValue);
progressBar.setStringPainted(true);
progressBar.setForeground(Color.GREEN);
JButton start = new JButton("Start");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread runner = new Thread() {
public void run() {
counter = minValue;
while (counter <= maxValue) {
Runnable runme = new Runnable() {
public void run() {
progressBar.setValue(counter);
}
};
SwingUtilities.invokeLater(runme);
counter++;
try {
Thread.sleep(100);
} catch (Exception ex) {
}
}
}
};
runner.start();
}
});
getContentPane().add(progressBar, BorderLayout.CENTER);
getContentPane().add(start, BorderLayout.WEST);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
}
public static void main(String[] args) {
new ProgressGenerator();
}
}
UIDefaults
和putClientProperty
来更改单个JProgressBar
的颜色。 - David KroukampPainter
。 - trashgod