3

因此,我偶然发现了 JTabbedPane 中的选项卡在左右(即setTabPlacement(JTabbedPane.RIGHT))中的位置,这是我喜欢的外观。我需要的是利用标签下方留下的空间。我目前有一列 JButton,但它们被推到一边,留下了很多空白。

关于如何做到这一点的任何想法?某种自定义叠加层之类的?

这是一个截图。在代码中,我基本上有一个水平对齐的 Box,JTabbedPane 在 JTree 上,然后是按钮列。

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

截图在这里

4

1 回答 1

1

我制作了这个社区维基,因为这个答案不是我的。@cheesecamera 似乎在另一个论坛上发布了相同的问题并在那里得到了答案。我复制了答案,以便来这里寻找答案的人可以得到答案。

这个想法是使用swing的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);
  }
}
于 2011-04-07T17:49:52.080 回答