我必须创建两个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);
最佳答案
使用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);
}
}