1
votes

I have custom JTabbedPane, I am having issue with making the tabs the same size as each other.

enter image description here

as you can see in the image, The green tab is selected, while the Red is unselected, I would like the Red Tab (Unselected) to be the same size as the Green Tab (Selected) here is my code

here is the code.

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);
        }
    }
}
1
@AndrewThompson Sorry, I am still getting used to asking questions, Can you tell me what part of my example was incorrect? :D - SamHoque
I have edited my question, Is that good? - SamHoque
Yeah I have no clue what you mean, You are not telling me the exact issue with my question. - SamHoque
Yes, Now it makes sense to me. - SamHoque
Edited my question, You can now just copy and paste it - SamHoque

1 Answers

0
votes

I have fixed the issue by moving g2D.fill(shape); inside 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);
    }
}

This will only fill it with the shape if the tab is selected.

Result:

enter image description here