我的要求是動態更改 JTabbedPane 的選項卡 colos。就像單擊按鈕時更改選項卡和選定選項卡顏色一樣。出于同樣的原因,我不能使用 UIManager。但是標簽顏色一旦設定和更改標簽就無法正常作業。還選擇的選項卡始終顯示默認顏色,而不是我設定的顏色。
下面是代碼:
import javax.swing.*;
import java.awt.*;
public class TestJTP extends JFrame {
JTabbedPane tabbedPane;
public TestJTP() {
init();
}
private void init() {
tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab-1", null);
tabbedPane.addTab("Tab-2", null);
tabbedPane.addTab("Tab-3", null);
tabbedPane.addTab("Tab-4", null);
tabbedPane.addTab("Tab-5", null);
JPanel panel = new JPanel();
JButton b1 = new JButton("Orange,blue");
b1.addActionListener(e -> {
tabbedPane.setBackground(null);
tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), null);
tabbedPane.setBackground(Color.orange);
tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), Color.blue);
});
JButton b2 = new JButton("Red,cyan");
b2.addActionListener(e -> {
tabbedPane.setBackground(null);
tabbedPane.setBackground(Color.red);
tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), null);
tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), Color.cyan);
});
JButton b3 = new JButton("Green,magenta");
b3.addActionListener(e -> {
tabbedPane.setBackground(null);
tabbedPane.setBackground(Color.green);
tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), null);
tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), Color.magenta);
});
panel.add(b1);
panel.add(b2);
panel.add(b3);
getContentPane().add(panel, BorderLayout.NORTH);
getContentPane().add(tabbedPane, BorderLayout.CENTER);
pack();
setVisible(true);
setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public static void main(String[] args) {
new TestJTP();
}
}
uj5u.com熱心網友回復:
如果我明白你在問什么試試:
//tabbedPane.setBackground(null);
tabbedPane.setBackground(Color.red);
//tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), null);
//tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), Color.cyan);
UIManager.put("TabbedPane.selected", Color.CYAN);
SwingUtilities.updateComponentTreeUI(tabbedPane);
這應該重置所有選項卡的默認“選項卡選擇顏色”和“選項卡顏色”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/323057.html
上一篇:在JPanel中并排創建兩個按鈕
