【问题标题】:JTabbedPane Tab unselected does not fill JPanel while selected does未选择的 JTabbedPane 选项卡不会填充 JPanel,而选择确实
【发布时间】:2018-11-17 00:00:27
【问题描述】:

我有自定义 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);
        }
    }
}

【问题讨论】:

  • @AndrewThompson 对不起,我仍然习惯于提问,你能告诉我我的例子的哪一部分不正确吗? :D
  • 我已经编辑了我的问题,这样好吗?
  • 是的,我不知道你的意思,你没有告诉我我的问题的确切问题。
  • 是的,现在对我来说很有意义。
  • 编辑了我的问题,你现在可以复制粘贴了

标签: java swing jtabbedpane


【解决方案1】:

我已通过将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);
    }
}

如果选项卡被选中,这只会用形状填充它。

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    相关资源
    最近更新 更多