问题
I have a JTabbed pane, which has a varying number of tabs. When the number of tabs is greater than 4, I get extra spacing/padding at the bottom of each tab panel. The picture below shows this (on the left you see the extra spacing, on the right you see no extra spacing).
Here is the exact code I used to get those pictures:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class DialogTest {
public static void main(String[] args) {
new DialogTest();
}
public DialogTest() {
JDialog dialog = new MyDialog();
dialog.pack();
dialog.setVisible(true);
}
class MyDialog extends JDialog {
public MyDialog() {
super(null, ModalityType.APPLICATION_MODAL);
final JTabbedPane tabs = new JTabbedPane();
final int numTabs = Integer.parseInt(JOptionPane.showInputDialog("Number of tabs:"));
setPreferredSize(new Dimension(400, 200));
for (int i = 1; i <= numTabs; i++) {
tabs.addTab("Tab"+i, new MyPanel(i));
}
setLayout(new BorderLayout());
add(tabs, BorderLayout.NORTH);
}
}
class MyPanel extends JPanel {
public MyPanel(int text) {
final JLabel label = new JLabel("THIS IS A PANEL" + text);
label.setFont(label.getFont().deriveFont(18f));
label.setBackground(Color.cyan);
label.setOpaque(true);
add(label);
setBackground(Color.red);
}
}
}
I've tried numerous things including many different layout managers. I can't for the life of me get rid of that extra spacing. Any help would be great.
回答1:
final JTabbedPane tabs = new JTabbedPane();
tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); // ADD THIS!
The reason the other example behaves as it does is that the pane wraps the tabs to the next line & presumes that once we have gone beyond as many tabs as it might naturally display in a single line, it must increase the preferred size to include that extra line of tabs.
来源:https://stackoverflow.com/questions/19143362/jtabbedpane-why-is-there-extra-padding-only-when-i-have-multiple-tabs-code-and