How to place components beneath tabs in right orie

2019-07-06 00:39发布

So I just stumbled across placement of tabs in a JTabbedPane to the right and left (i.e. setTabPlacement(JTabbedPane.RIGHT)) which I love the look of. What I need is to utilize the space this leaves beneath the tabs. I currently have a column of JButtons, but they get pushed to the side, leaving a lot of blank space.

Any thoughts on how to do this? Some kind of custom overlay or something?

Here's a screenshot. In the code I basically have one horizontally aligned Box, with the JTabbedPane over a JTree, then the column of buttons after that.

boxOfEverything.add(tabbedPane);
boxOfEverything.add(boxColumnButtons);

Screenshot here.

1条回答
劳资没心,怎么记你
2楼-- · 2019-07-06 01:39

I made this community wiki because this answer is not mine. @cheesecamera seems to have posted the same question on another forum and got an answer there. I copied the answer so that people coming here looking for an answer can get an answer.

The idea is to use swing's glasspane.

import java.awt.*;
import javax.swing.*;

public class RightTabPaneButtonPanel {

  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

      @Override
      public void run() {
        new RightTabPaneButtonPanel().makeUI();
      }
    });
  }

  public void makeUI() {
    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.setTabPlacement(JTabbedPane.RIGHT);
    JPanel panel = new JPanel(new GridLayout(0, 1));

    for (int i = 0; i < 3; i++) {
      JPanel tab = new JPanel();
      tab.setName("tab" + (i + 1));
      tab.setPreferredSize(new Dimension(400, 400));
      tabbedPane.add(tab);

      JButton button = new JButton("B" + (i + 1));
      button.setMargin(new Insets(0, 0, 0, 0));
      panel.add(button);
    }

    JFrame frame = new JFrame();
    frame.add(tabbedPane);
    frame.pack();
    Rectangle tabBounds = tabbedPane.getBoundsAt(0);

    Container glassPane = (Container) frame.getGlassPane();
    glassPane.setVisible(true);
    glassPane.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    gbc.fill = GridBagConstraints.NONE;
    int margin = tabbedPane.getWidth() - (tabBounds.x + tabBounds.width);
    gbc.insets = new Insets(0, 0, 0, margin);
    gbc.anchor = GridBagConstraints.SOUTHEAST;

    panel.setPreferredSize(new Dimension((int) tabBounds.getWidth() - margin,
            panel.getPreferredSize().height));
    glassPane.add(panel, gbc);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}
查看更多
登录 后发表回答