我必须创建两个jlabel,并且它们应该在JFrame中位于彼此的中间和正下方。我一直在使用griddbaglayout从swing,但我不知道如何做到这一点。
terminalLabel = new JLabel("No reader connected!", SwingConstants.CENTER);
terminalLabel.setVerticalAlignment(SwingConstants.TOP);
cardlabel = new JLabel("No card presented", SwingConstants.CENTER);
cardlabel.setVerticalAlignment(SwingConstants.BOTTOM);
使用BoxLayout。在下面的代码中,Box类是一个便利类,它创建了一个使用BoxLayout的JPanel:
import java.awt.*;
import javax.swing.*;
public class BoxExample extends JFrame
{
public BoxExample()
{
Box box = Box.createVerticalBox();
add( box );
JLabel above = new JLabel("Above");
above.setAlignmentX(JLabel.CENTER_ALIGNMENT);
box.add( above );
JLabel below = new JLabel("Below");
below.setAlignmentX(JLabel.CENTER_ALIGNMENT);
box.add( below );
}
public static void main(String[] args)
{
BoxExample frame = new BoxExample();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
使用FlowLayout和GridLayout
enclosingPanel = new JPanel();
enclosingPanel.setLayout( new FlowLayout( FlowLayout.CENTER) );
labelPanel = new JPanel();
labelPanel.setLayout( new GridLayout( 2 , 1 ) ); // 2 rows 1 column
enclosingPanel.add( labelPanel );
frame.add( enclosingPanel ); // frame = new JFrame();
setPreferredSize( new Dimension( 200 , 200) );
// do other things
使用这种方法,您可以将2个JLabels
放置在彼此的中心和下方。您也可以设置两个标签之间的垂直间距。#GridLayout(int, int, int, int)
您应该为用于向容器添加标签的GridBagCOnstraints指定适当的锚点(CENTER)
您必须使用GridBagConstraints
。在添加第二个标签的同时改变约束的gridY
值,它将被放置在第一个标签的下面。
试试这个:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.anchor = GridBagConstraints.CENTER;
JLabel terminalLabel = new JLabel("No reader connected!");
frame.add(terminalLabel,constraints);
constraints.gridy = 1;
JLabel cardlabel = new JLabel("No card presented");
frame.add(cardlabel,constraints);
frame.setVisible(true);
还可以阅读这个:如何使用GridBagLayout