我正在使用JProgressBar
組件以及Nimbus UI默認值。問題是,當我想手動更改每個進度條的Bar顏色時,我通過設置JProgressBar.setUI()
函數使用BasicProgressBarUI
。這使得更麻煩,因爲我想只改變條的顏色,似乎我鬆開jprogressbar的默認外觀(Border,backgroundcolor消失)。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();
}
}
爲更好地幫助更快張貼[SSCCE(http://sscce.org/),短,可運行,編譯,否則要搜索,谷歌可以返回 – mKorbel
參見[這] (http://stackoverflow.com/questions/7174420/change-colors-for-jprogressbar-with-nimbus)類似的問題/答案,它顯示瞭如何使用'UIDefaults'和'putClientProperty'來改變一個'JProgressBar'顏色 –
目前的問題是當我使用setForeground(Color.GREEN)更改條形顏色時;它會更改SelectionBackground顏色。看來,setBackgroundColor(Color.RED);命令不會執行任何操作。 – mbasol