【发布时间】:2021-10-09 19:11:55
【问题描述】:
我的要求是动态更改 JTabbedPane 的标签页。就像单击按钮时更改选项卡和选定选项卡颜色一样。出于同样的原因,我不能使用 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();
}
}
【问题讨论】:
标签: java swing tabs selected jtabbedpane