英文:
Java Create a program with multiple GUI frames
问题
在Java中,您可以创建一个单独的类来处理所有的GUI框架,而不必为每个框架创建一个新的类。您可以使用Swing或JavaFX库来实现这一点。以下是一个简单的示例代码,演示如何在同一个类中创建多个GUI框架:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyProgram extends JFrame {
private JTextField nameField;
private JTextField firstNumberField;
private JTextField secondNumberField;
public MyProgram() {
// 设置窗口标题
super("My Program");
// 设置窗口大小
setSize(400, 200);
// 创建组件
nameField = new JTextField(20);
firstNumberField = new JTextField(10);
secondNumberField = new JTextField(10);
JButton nextButton = new JButton("Next");
// 设置布局
setLayout(new GridLayout(4, 2));
// 添加组件到窗口
add(new JLabel("Please give me your name:"));
add(nameField);
add(new JLabel("Please put the first number:"));
add(firstNumberField);
add(new JLabel("Please put the second number:"));
add(secondNumberField);
add(new JLabel()); // 空白标签用于布局
add(nextButton);
// 添加下一步按钮的点击事件
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 在这里处理下一步的操作
}
});
// 设置窗口关闭操作
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyProgram program = new MyProgram();
program.setVisible(true);
}
});
}
}
这个示例演示了如何在同一个类中创建多个GUI框架,每个框架之间可以共享数据和逻辑。您可以在actionPerformed
方法中处理下一步的操作。
英文:
Alright so im making a program in Java that asks the user for multiple details in continuous frames in GUI, My main question would be is there a way to put all frames in one class, and not have to create a class for each frame.
So here is what im doing:
1st frame:
Please give me your name: [User puts name here] //Then click ok
2 frame:
Please put the first numer: [user puts first number]
Please put second number: [user puts second number]
//then click next
and so on
I cant figure out a way to do this without creating a new class for each frame.
Is there a way to put all frames in the same class. Thanks in advance
答案1
得分: 2
在这种情况下,听起来你实际上不需要多个帧;而是需要一个帧,其内容会更改。你可以使用多个JPanels来表示不同的页面,并在它们之间切换。
但是,你不应该将整个对话框混合到单个类中;而是应该练习关注点分离,将代码划分为合理的部分,并可能使用设计模式如MVC。
英文:
In this case, it sounds like you do not actually need multiple frames; rather you need one frame, and its content changes. You could use several JPanels for the individual pages, and switch between them.
That said, you should not mash the entire dialog into a single class; rather you should practice separation of concerns, cut code into reasonable chunks, and possibly use design patterns like MVC.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论