所以我一直在研究一个java程序,我试图让JLabel居中在窗口中间,但是我做的标签只是在顶部中心。我希望有人可以帮助找到一种方法让文本居中在窗口中间。这是我的代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class Lottery extends JPanel implements ActionListener {
private static final long serialVersionUID = 5815877011755522230L;
private JLabel label;
public static void main(String[] args) {
make();
}
public Lottery() {
label = new JLabel("Hello There");
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
add(label);
}
public static void make(){
JFrame frame = new JFrame("Lottery");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Lottery hi = new Lottery();
frame.setContentPane(hi);
frame.setSize(600, 600);
frame.setVisible(true);
}
}
有人可以帮我解决这个问题。
答案 0 :(得分:2)
替换add(标签);用:
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
并且不要忘记导入java.awt.BorderLayout;
您的代码会对齐标签中的文字,但标签本身并不在您的面板中居中。无论如何,你必须修改布局。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
public class Lottery extends JPanel {
private static final long serialVersionUID = 5815877011755522230L;
private JLabel label;
public static void main(String[] args) {
make();
}
public Lottery() {
label = new JLabel("Hello There");
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
//add(label);
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
}
public static void make(){
JFrame frame = new JFrame("Lottery");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Lottery hi = new Lottery();
frame.setContentPane(hi);
frame.setSize(600, 600);
frame.setVisible(true);
}
}