我正在编写一个程序,允许多个用户共享屏幕截图。每次用户连接时,参与“房间”的每个人(一群能够互相接收屏幕快照的用户)都可以看到用户拍摄的屏幕快照。为了能够看到屏幕截图,框架需要自行拆分,以便为该用户的屏幕截图留出专用空间。
我决定使用GridLayout,因为它将组件拆分成相等大小的矩形,这正是我想要的。布局完全符合我的需要,除了一个问题。如果我的GridLayout配置为有两行和两列,那么即使只有一个组件,最底下的行仍会分成两列。这是预期的行为,但是有没有解决的办法,最好不要使用其他布局?我真的很喜欢GridLayout的简单性。我已经考虑过使用BorderLayout,但是它有局限性,因为我可以放置项目的空间一定。
图片的格式不受支持,因此我无法将其嵌入此问题。
这是框架看起来像已满的样子。我将实际的屏幕截图替换为按钮,因为我只是在测试。
http://cl.ly/0N311g3w061P1B0W1T3s/Screen%20shot%202012-05-13%20at%204.23.25%20PM.png
现在,这是我从最底部的行中删除按钮时的外观:
http://cl.ly/2j3Z0V1r3w1S3F160j05/Screen%20shot%202012-05-13%20at%204.23.41%20PM.png
这是我希望最底部的行显示的样子:
http://cl.ly/0J2R2y2L06151F0k0Y0i/Screen%20shot%202012-05-13%20at%204.24.11%20PM.png
如何使最底部的行看起来像这样?请记住,我仍然希望其他行具有两列,但我只希望最底部的一行具有一列。
谢谢!
最佳答案
据我所知,你做不到。 GridLayout是通过这种方式完成的。
但是GridBagLayout将为您的程序做得漂亮。
看一下这个小的演示,它按行和列排列按钮。
(单击按钮将其删除)。
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Test4 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
final JPanel root = new JPanel(new GridBagLayout());
frame.add(root);
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer t = new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final JButton b = new JButton("Hello" + root.getComponentCount());
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
root.remove(b);
updateConstraints(root);
}
});
root.add(b);
updateConstraints(root);
}
});
t.start();
}
});
}
protected static void updateConstraints(JPanel root) {
if (!(root.getLayout() instanceof GridBagLayout)) {
System.err.println("No a gridbaglayout");
return;
}
GridBagLayout layout = (GridBagLayout) root.getLayout();
int count = root.getComponentCount();
int col = (int) Math.round(Math.sqrt(count));
int row = (int) Math.ceil((double) count / col);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
int index = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
gbc.gridx = j;
gbc.gridy = i;
boolean last = index + 1 == count;
if (last) {
gbc.gridwidth = col - j;
}
Component c = root.getComponent(index);
layout.setConstraints(c, gbc);
if (last) {
break;
}
index++;
}
}
root.doLayout();
}
}