之前,我使用 servlet 创建了一个小型应用程序,其中第一页显示一个用户注册页面,该页面通过“提交”按钮捕获用户的名字和姓氏等基本信息。
假设在第一页中输入的用户名是“Scott”,那么一旦用户提交表单,我就会在第二页中创建一条欢迎消息“欢迎 Scott”。然后我提供了一个选项来查看之前通过连接数据库注册到应用程序的用户列表。
现在我想在 Swing 应用程序中实现相同的功能。我是 Swings 新手,所以我尝试从各种来源学习它,但我找不到可以在多个框架/面板之间导航的示例。
对于第一页,我创建了以下程序,显示文本字段和提交按钮:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class UserRegistration extends JFrame {
JButton button;
public UserRegistration() {
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
final JLabel label = new JLabel("Please enter details: ");
JLabel firstName = new JLabel("First Name");
JLabel lastName = new JLabel("Last Name");
final JTextField firstNameTxt = new JTextField(20);
final JTextField lastNameTxt = new JTextField(20);
button = new JButton("Submit");
JButton button1 = new JButton("Cancel");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
UserDetails user = new UserDetails();
user.showDetails();
user.setVisible(true);
}
});
add(label);
add(firstName);
add(firstNameTxt);
add(lastName);
add(lastNameTxt);
add(button);
add(button1);
setVisible(true);
}
public static void main(String args[]) {
new UserRegistration();
}
}
要从第一帧转到第二帧,我使用这些行:
dispose();
UserDetails user = new UserDetails();
user.showDetails();
user.setVisible(true);
现在,对于第二页,我无法找出如何获取用户输入的参数,这是我陷入困境的代码:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class UserDetails extends JFrame {
//private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public UserDetails() {
prepareGUI();
}
private void prepareGUI() {
//mainFrame = new JFrame("Java Swing Examples");
setSize(800, 800);
setLayout(new GridLayout(3, 5));
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
headerLabel = new JLabel("This is Header", JLabel.CENTER);
statusLabel = new JLabel("This is Status", JLabel.CENTER);
statusLabel.setSize(350, 100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
System.out.println(controlPanel);
add(headerLabel);
add(controlPanel);
add(statusLabel);
//setVisible(true);
}
public void showDetails() {
// Here I want display the welcome message and also to add all the registered user details.
}
}
请帮助我如何创建包含多个页面的应用程序?
最佳答案
Swing 提供了 CardLayout 类来提供您所需要的。它允许您加载两个或多个组件(JPanel)并允许共享相同的显示。可以像向导一样在卡片之间导航。请查看本教程:CardLayout
关于java - 如何创建具有多个页面的 Swing 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27687427/