我必须创建两个JLabel,并且应该在JFrame中定位在中心和正下方。我正在使用摆动的gridbaglayout,但我无法弄清楚如何做到这一点。
terminalLabel = new JLabel("No reader connected!", SwingConstants.CENTER);
terminalLabel.setVerticalAlignment(SwingConstants.TOP);
cardlabel = new JLabel("No card presented", SwingConstants.CENTER);
cardlabel.setVerticalAlignment(SwingConstants.BOTTOM);
答案 0 :(得分:8)
使用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);
}
}
答案 1 :(得分:2)
使用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
放在中间位置,并放在彼此之下。您还可以在2个标签之间设置垂直间距。 #GridLayout(int, int, int, int)
答案 2 :(得分:1)
您应该为用于将标签添加到容器的GridBagCOnstraints指定正确的锚点(CENTER)。
答案 3 :(得分:1)
您必须使用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);