MainClass(){
JFrame main = new JFrame("Login Form ");
main.setBounds(350,150,500,500);
main.setVisible(true);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
name = new JTextField(10);
pass = new JTextField(10);
main.setLayout(new GridLayout(0,1));
JPanel pane = new JPanel();
main.add(pane);
main.add(new JLabel("Username: "));
pane.add(name);
//main.add(pane);
pane.add(new JLabel("Password: "));
pane.add(pass);
submit = new JButton("Submit");
pane.add(submit);
submit.addActionListener(new Handler());
}
我想在标签username
和name
文本框后的单独行中分隔文本框。我需要将光标控制到一个新行。
答案 0 :(得分:7)
我想在单独的行中分隔文本框
import java.awt.*;
import javax.swing.*;
class MainClass {
JTextField name;
// This should be a JPasswordField!
JTextField pass;
JButton submit;
MainClass(){
JFrame main = new JFrame("Login Form ");
// Don't use this nonsense!
//main.setBounds(350,150,500,500);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
name = new JTextField(10);
pass = new JTextField(10);
main.setLayout(new GridLayout(0,1));
JPanel pane = new JPanel(new GridLayout(0,1));
main.add(pane);
pane.add(new JLabel("Username: "));
pane.add(name);
pane.add(new JLabel("Password: "));
pane.add(pass);
submit = new JButton("Submit");
pane.add(submit);
//submit.addActionListener(new Handler());
main.pack();
main.setVisible(true);
}
public static void main(String[] args) {
MainClass mc = new MainClass();
}
}
如果我正在构建一个登录屏幕,它可能会沿着这些行布置更多(标签右对齐并且按钮位于其自己的面板中 - 留给读者练习。)
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class MainClass {
JTextField name;
JPasswordField pass;
JButton submit;
MainClass(){
JFrame main = new JFrame("Login Form ");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
name = new JTextField(10);
pass = new JPasswordField(10);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
main.setContentPane(gui);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Username: "));
controls.add(name);
labels.add(new JLabel("Password: "));
controls.add(pass);
submit = new JButton("Submit");
gui.add(submit, BorderLayout.SOUTH);
main.pack();
main.setVisible(true);
}
public static void main(String[] args) {
MainClass mc = new MainClass();
}
}
答案 1 :(得分:1)
使用BoxLayout;创建一个JPanel,使用SetLayout将其设置为BoxLayout,并将BoxLayout设置为PAGE_AXIS。然后你添加的东西会一个接一个地垂直向下移动到'page'。有对齐选项,请参阅BoxLayout的API或布局管理器上的Oracle / Sun / Java教程。