我有一个GUI程序,其中包含JLabels
和JButtons
,基本上我想要一个帮助我按如下方式显示它们的布局:
Label1 Button1
Label2 Button2
Label3 Button3
.....
是否有布局可以让我达到上述效果?
我看过this example,但是太复杂了,想知道我是否可以使用任何自动化的东西?
答案 0 :(得分:3)
这是我推荐的少数事项之一(实用方法和GroupLayout
this answer中所见。
答案 1 :(得分:2)
您可以使用GridLayout。文档here。
答案 2 :(得分:2)
这只是为了简单和您的问题。 GUI实际上取决于您想要做什么,而且实际上很难实现自动化...而且我不认为您只需要GUI上的这6个元素,但理论上这样做会:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUITest {
private Box labelbox = new Box(BoxLayout.Y_AXIS);
//Y_AXIS means they are placed vertically in the box
private Box buttonbox = new Box(BoxLayout.Y_AXIS);
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
public void makeGUI1() {
for (int i = 1; i <= 3; i++) {
//if you want to save the references, you should make
//an ArrayList<JLabel> and add each of them to it
JLabel label = new JLabel("Label " + i);
labelbox.add(Box.createVerticalStrut(5));
//these are for giving the labels some extra space
//between them vertically to be in line with the buttons
labelbox.add(label);
labelbox.add(Box.createVerticalStrut(10)); //these are too
}
for (int i = 1; i <= 3; i++) {
//if you want to save the references, you should make
//an ArrayList<JButton> and add each of them to it
JButton button = new JButton("Button " + i);
buttonbox.add(button);
}
panel.add(labelbox, BorderLayout.EAST);
//you can find picture of each constant:
//http://download.java.net/jdk7/archive/b123/docs/api/java/awt/BorderLayout.html
panel.add(buttonbox, BorderLayout.WEST);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
GUITest guitest = new GUITest();
guitest.makeGUI1();
}
});
}
}
答案 3 :(得分:-1)
您还可以使用obj.setBounds(LeftSpaceParameter,TopSpaceParameter),您可以使用它将gui元素或对象放置在您选择的任何位置。您需要将默认布局设置为null 而gridLayout则更容易。 。