就像标题所说的那样,我试图在JFrame的每个角上放置4个不同的JLabel。我希望他们永远呆在那里,即使我尝试调整JFrame的大小
我已经尝试过使用布局管理器,但是我做对了。
ImageIcon icon;
JLabel labelNW = new JLabel();
JLabel labelNE = new JLabel();
JLabel labelSW = new JLabel();
JLabel labelSE = new JLabel();
URL buttonURL = InputOutputTest.class.getResource("images/square_dot.gif");
if(buttonURL != null){
icon = new ImageIcon(buttonURL);
labelNW.setIcon(icon);
labelNE.setIcon(icon);
labelSW.setIcon(icon);
labelSE.setIcon(icon);
}
window.add(labelNW, BorderLayout.NORTH);
//window.add(labelNE, BorderLayout.EAST);
//window.add(labelSW, BorderLayout.WEST);
window.add(labelSE, BorderLayout.SOUTH);
该代码负责左侧的北部和南部。我可能正在解决这个错误。
我也尝试了GridLayout(2,2),但是它们不在角落,右侧有很大的空隙。
最佳答案
您将需要使用各自的布局来嵌套JPanels。实际上,您可以通过嵌套全部使用BorderLayout的JPanels来做到这一点。
要检查GridBagLayout是否可以一击就完成....挂起...
是的GridBagLayout也这样做:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class GridBagExample {
public static void main(String[] args) {
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(
0, 0, 0, 0), 0, 0);
mainPanel.add(new JLabel("Left Upper"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHEAST;
mainPanel.add(new JLabel("Right Upper"), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.SOUTHWEST;
mainPanel.add(new JLabel("Left Lower"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.SOUTHEAST;
mainPanel.add(new JLabel("Right Lower"), gbc);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
编辑
现在以BorderLayout为例:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class BorderLayoutExample {
public static void main(String[] args) {
JPanel northPanel = new JPanel(new BorderLayout());
northPanel.add(new JLabel("North East"), BorderLayout.EAST);
northPanel.add(new JLabel("North West"), BorderLayout.WEST);
JPanel southPanel = new JPanel(new BorderLayout());
southPanel.add(new JLabel("South East"), BorderLayout.EAST);
southPanel.add(new JLabel("South West"), BorderLayout.WEST);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(northPanel, BorderLayout.NORTH);
mainPanel.add(southPanel, BorderLayout.SOUTH);
JFrame frame = new JFrame("BorderLayout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}