我一直在尝试更改JTabbedPane中选项卡的背景颜色。
我在Java文档和论坛上在线阅读了这些文章,它们必须不透明设置为false并使用tabpane.setBackgroundAt(index, color)
来更改背景。我似乎无法使它正常工作。我的选项卡包含一个JPanel(将opaque设置为false),该面板具有JLabel(将是文件名)和JButton(用于关闭选项卡的X)。标签,按钮和面板都设置为不透明false,但是无论我尝试设置背景颜色如何,它都保持默认颜色。
这是我正在使用的选项卡窗格的代码:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class TextEdit extends JTabbedPane {
public TextEdit() {
// On startup, display a blank tabbed pane
AddTab("Untitled");
}
protected void AddTab(String fileName) {
/* This will be the panel that displays the
* textarea
*/
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0,1));
/* Textarea where the user will be able
* to type content into
*/
JTextArea ta = new JTextArea();
ta.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
/* Scrollpane that allows us to scroll
* if content in the text area gets too
* large
*
*/
JScrollPane sp = new JScrollPane(ta);
/* Line numbering
* In the future I will turn this on and off
* based on user preferences. This line will
* work to disable line numbering:
* sp.setRowHeaderView(null);
*/
TextLineNumber tln = new TextLineNumber(ta);
sp.setRowHeaderView(tln);
/*
* Add scrollpane to the panel
*/
panel.add(sp);
/* Now we configure the tab panel
* that displays the filename with an 'X'
* that will enable us to close the file (pane)
*/
JPanel tabPanel = new JPanel();
tabPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 2));
tabPanel.setOpaque(false);
// Label for the filename
JLabel label = new JLabel(fileName);
label.setBorder(new EmptyBorder(0,0,0,0));
// Button for the close button
JButton button = new JButton("X");
button.setBorder(new EmptyBorder(0,0,0,0));
button.setBorderPainted(false);
button.setOpaque(false);
button.setContentAreaFilled(false);
// On hover, change the color that way we know it's a button
button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent e) {
button.setForeground(Color.RED);
}
public void mouseExited(java.awt.event.MouseEvent e) {
button.setForeground(Color.BLACK);
}
});
tabPanel.add(label);
tabPanel.add(button);
panel.setPreferredSize(new Dimension(1000, 500));
this.addTab(fileName, panel);
int index = this.getSelectedIndex();
this.setTabComponentAt(index, tabPanel);
this.setBackgroundAt(index, Color.GREEN);
}
}
有什么建议吗?我知道索引是正确的,因为它在我setTabComponentAt(index,tabPanel)
时有效。我认为可能是其他原因导致了错误,但事实并非如此。
更新: 因此,我创建了第二个选项卡,并注意到只要选项卡未处于活动状态,背景颜色的确会发生变化。我只是看不到一个选项卡。有没有办法更改活动标签的颜色?我的目标是使活动标签与非活动标签具有不同的颜色。