如何将组件放置在向右定向的 JTabbedPane 中的选项卡下方
所以我只是偶然发现在 JTabbedPane 中左右放置了标签(即 setTabPlacement(JTabbedPane.RIGHT)
),我喜欢它的外观.我需要的是利用这在选项卡下方留下的空间.我目前有一列 JButton,但它们被推到一边,留下了很多空白.
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?
这是屏幕截图.在代码中,我基本上有一个水平对齐的 Box,JTabbedPane 在 JTree 上,然后是按钮列.
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);
此处截图.
我做了这个 社区维基 因为这个答案不是我的.@cheesecamera 似乎在另一个 forum 并在那里得到了答案.我复制了答案,以便来这里寻找答案的人可以得到答案.
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.
这个想法是使用swing的glasspane
.
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);
}
}