我有一个JTabbedPane,其中2个JPanels设置为GridLayout(13,11)。第一个JPanel有足够的单元格填充它离开空单元格。
第二个JPanel填充的单元格明显减少,这导致每个按钮被拉伸以填满整行。
有没有办法让GridLayout兑现空单元格,因此两个JPanels中的按钮大小相同?
答案 0 :(得分:7)
使用嵌套布局来获得所需的结果。有些布局尊重组件的首选尺寸,有些则不合适。 GridLayout
是其中之一。看一下this answer,了解哪一个人做了哪一个,哪个人不做。
例如,您可以将GridLayout
嵌套中的13个按钮嵌套在JPanel
FlowLayout
中
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEADING));
JPanel p2 = new JPanel(new GridLayout(13, 1));
for (int i = 0; i < 13; i++) {
p2.add(new JButton("Button " + i));
}
p1.add(p2);
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test6 {
public Test6() {
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEADING));
JPanel p2 = new JPanel(new GridLayout(13, 1));
for (int i = 0; i < 13; i++) {
p2.add(new JButton("Button " + i));
}
p1.add(p2);
JFrame frame = new JFrame("Test Card");
frame.add(p1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Test6 test = new Test6();
}
});
}
}
答案 1 :(得分:7)
有没有办法让GridLayout兑现空单元格,因此两个JPanels中的按钮大小相同?
使用GridLayout
肯定是可行的,只需使用没有文字的JLabel
“填充”空白方块。
E.G。这是两个网格布局,都填充到3行。
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.LineBorder;
class FillGridLayout {
public static final JComponent getPaddedGrid(
ArrayList<BufferedImage> images, int width, int height) {
JPanel p = new JPanel(new GridLayout(height, width, 2, 2));
p.setBorder(new LineBorder(Color.RED));
int count = 0;
for (BufferedImage bi : images) {
p.add(new JButton(new ImageIcon(bi)));
count++;
}
for (int ii=count; ii<width*height; ii++ ) {
// add invisible component
p.add(new JLabel());
}
return p;
}
public static void main(String[] args) {
final ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
int s = 16;
for (int ii = s/4; ii < s; ii+=s/4) {
images.add(new BufferedImage(ii, s, BufferedImage.TYPE_INT_RGB));
images.add(new BufferedImage(s, ii, BufferedImage.TYPE_INT_RGB));
}
Runnable r = new Runnable() {
@Override
public void run() {
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.add(getPaddedGrid(images, 3, 3), BorderLayout.LINE_START);
gui.add(getPaddedGrid(images, 4, 3), BorderLayout.LINE_END);
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
答案 2 :(得分:1)
将空的 JLabel 添加到空单元格
content.add(new JLabel(""));