【发布时间】:2014-01-16 13:38:42
【问题描述】:
如何使我的文本字段和按钮居中?
编辑:用 SSCE 更新了我的帖子。希望这会有所帮助。
顺便说一句,我希望左图看起来像右图。
package pkg;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
public class Game {
private static JPanel panel = new JPanel();
public static JTextField username = new JTextField(20);
public static JPasswordField password = new JPasswordField(20);
JButton login = new JButton("Login");
JLabel status = new JLabel();
private static JPanel game = new JPanel();
private JButton logout = new JButton("Logout");
private static JFrame frame = new JFrame("RuneShadows");
public Game() {
panel.add(username);
panel.add(password);
panel.add(login);
panel.add(status);
game.add(logout);
frame.add(panel);
frame.setSize(806, 553);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new Game();
}
public void loadGame() {
frame.remove(panel);
frame.revalidate();
frame.add(game);
frame.revalidate();
logout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(game);
frame.revalidate();
frame.add(panel);
frame.revalidate();
try {
Client.socketOut.writeUTF("logout");
Client.socketOut.writeUTF(Client.username);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
}
我想要的样子:
我尝试了许多不同的布局样式,但我似乎无法让它工作......
【问题讨论】:
-
如需尽快获得更好的帮助,请发帖 SSCCE。另见this answer..
-
在你的图片中你有 2 个,你想要的那个是左边还是右边?
-
我希望左图看起来像右图。
-
不要使用 frame.remove() 和 frame.add() 替换框架上的整个面板。相反,您应该使用
CardLayout。本教程为此提供了一个示例。
标签: java swing layout components