如何使文本字段和按钮居中?
编辑:使用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();
}
}
});
}
}
我希望它看起来像什么:
我尝试使用许多不同的布局样式,但我似乎无法使其正常工作......
答案 0 :(得分:3)
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
import javax.swing.border.*;
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(new FlowLayout(FlowLayout.CENTER));
private JButton logout = new JButton("Logout");
private static JFrame frame = new JFrame("RuneShadows");
public Game() {
panel.setLayout(new GridLayout(0,1,15,15));
panel.setBorder(new EmptyBorder(50,100,50,100));
panel.add(username);
panel.add(password);
panel.add(status);
JPanel logoutConstrain = new JPanel(new FlowLayout(FlowLayout.CENTER));
logoutConstrain.add(logout);
panel.add(logoutConstrain);
frame.setLayout(new GridBagLayout());
frame.add(panel);
//frame.setSize(806, 553); // forget this nonsense, instead..
frame.pack(); // best!
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();
}
});
}
}