我有一个带有两个Tap的JTabbedPane。在这里,我想尝试为活动标签赋予不同的颜色。为此,我使用setBackgroundAt,但这不会更改GUI。有人可以告诉我为什么会这样,或者我如何正确地做到这一点?
public JTabbedPane getTabbedPane() {
if (this.tabbedPane == null) {
this.tabbedPane = new JTabbedPane();
this.tabbedPane.addTab("Tab 1", new JPanel());
this.tabbedPane.addTab("Tab 2", new JPanel());
this.tabbedPane.addChangeListener(e -> {
for(int i = 0; i < tabbedPane.getTabCount(); i++){
tabbedPane.setBackgroundAt(i, Color.RED);
}
tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), Color.GREEN);
tabbedPane.repaint();
});
}
return this.tabbedPane;
}
结果看起来像这样:
JTabbedPane仅允许更改未选择的选项卡的背景。要更改所选选项卡的颜色,必须临时替换UIManager的“ TabbedPane.selected”属性。
示例:
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
/**
* <code>TabbedPaneDemo</code>.
*/
public class TabbedPaneDemo {
private JTabbedPane tabbedPane;
public static void main(String[] args) {
SwingUtilities.invokeLater(new TabbedPaneDemo()::startUp);
}
private void startUp() {
JFrame frm = new JFrame("Tab demo");
frm.add(getTabbedPane());
frm.setSize(500, 200);
frm.setLocationRelativeTo(null);
frm.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frm.setVisible(true);
}
private JTabbedPane getTabbedPane() {
if (this.tabbedPane == null) {
// UI hack - temporary replace selection color
Color old = UIManager.getColor("TabbedPane.selected");
UIManager.put("TabbedPane.selected", Color.GREEN);
this.tabbedPane = new JTabbedPane();
UIManager.put("TabbedPane.selected", old);
this.tabbedPane.addTab("Tab 1", new JPanel());
this.tabbedPane.addTab("Tab 2", new JPanel());
}
updateTabs();
return this.tabbedPane;
}
private void updateTabs() {
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
tabbedPane.setBackgroundAt(i, Color.RED);
}
}
}
此hack有一个缺点:您不能再更改选择背景。因此选项卡式窗格中的每个选定选项卡都将具有绿色背景。