我有自定义的JTabbedPane,在将标签页设置为彼此相同的大小时遇到问题。
如您在图像中看到的,绿色标签被选中,而红色未选中,我希望红色标签(未选中)与绿色标签(已选中)具有相同的大小,这是我的代码>
这是代码。
import javax.swing.*;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
import java.awt.*;
public class UITest {
public static void main(String[] args){
JFrame jFrame = new JFrame();
JTabbedPane jTabbedPane = new JTabbedPane();
jTabbedPane.add(new JPanel(), "test");
jTabbedPane.add(new JPanel(), "test2");
jTabbedPane.setUI(new LynxTabbedPane());
jFrame.setContentPane(jTabbedPane);
jFrame.setSize(200,200);
jFrame.setVisible(true);
}
public static class LynxTabbedPane extends BasicTabbedPaneUI {
private Polygon shape;
@Override
protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
Graphics2D g2D = (Graphics2D) g;
int xp[] = new int[]{x, x, x + w, x + w, x};
int yp[] = new int[]{y, y + h, y + h, y, y};
shape = new Polygon(xp, yp, xp.length);
if (isSelected) {
g2D.setColor(Color.GREEN);
} else if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
g2D.setColor(Color.RED);
}
g2D.fill(shape);
}
}
}
答案 0 :(得分:0)
我通过在g2D.fill(shape);
内移动isSelected
来解决了该问题
@Override
protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
Graphics2D g2D = (Graphics2D) g;
int xp[] = new int[]{x, x, x + w, x + w, x};
int yp[] = new int[]{y, y + h, y + h, y, y};
shape = new Polygon(xp, yp, xp.length);
if (isSelected) {
g2D.fill(shape);
g2D.setColor(selectColor);
} else if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
g2D.setColor(deSelectColor);
}
}
只有在选择标签后,才会用形状填充它。
结果: