Java 在现有JFrame中重新绘制新JFrame?
我试图在用户在他们使用的同一窗口中执行某些操作后显示不同的JFrame,类似于登录功能。我还不知道该怎么做 我现在的解决方法是隐藏当前JFrame,然后打开一个新的JFrame,它模拟了类似的效果。但理想情况下,我希望它只在相同的现有窗口中显示下一个JFrameJava 在现有JFrame中重新绘制新JFrame?,java,swing,layout-manager,jdialog,cardlayout,Java,Swing,Layout Manager,Jdialog,Cardlayout,我试图在用户在他们使用的同一窗口中执行某些操作后显示不同的JFrame,类似于登录功能。我还不知道该怎么做 我现在的解决方法是隐藏当前JFrame,然后打开一个新的JFrame,它模拟了类似的效果。但理想情况下,我希望它只在相同的现有窗口中显示下一个JFrame import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swi
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 Login extends JFrame {
private static int x = 0;
static JTextField txtInput = new JTextField(10);
static JButton btnSwitch = new JButton("Log on");
public Login(){
setLayout(new FlowLayout());
//add button and register
add(new JLabel("Enter password:"));
add(txtInput);
add(btnSwitch);
}
public static void main(String[] args) {
final JFrame frame = new Login();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 150);
frame.setVisible(true);
btnSwitch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(txtInput.getText().equals("123")){
//frame = new GUIHelloWorld(); this doesn't work because "The final local variable frame cannot be assigned, since it is defined in an enclosing type"
//so I went with the below workaround
GUIHelloWorld frame = new GUIHelloWorld();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
});
}
}
一旦用户通过GUI的第一部分,我想向他们展示以下内容:
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GUIHelloWorld extends JFrame {
public GUIHelloWorld(){
setLayout(new GridLayout(0,1));
add(new JLabel("Hello World"));
add(new JLabel("Welcome to the 2nd part of the GUI"));
}
public static void main(String[] args) {
JFrame frame = new GUIHelloWorld();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
有人能告诉我如何在用户正在使用的现有窗口中显示新的JFrame吗
JFrame
扩展,尤其是在无法将帧添加到其他帧的情况下。相反,您可以根据JPanel
JFrame
的单个实例,将其布局管理器设置为使用CardLayout
在视图之间切换您也可以考虑使用登录窗口,但基本建议仍然存在;创建窗口,扩展组件…
谢谢!直到现在才知道这个布局管理器,看起来它正是我所需要的。还感谢您提出的关于不要扩展JFrame而不是JPanel的建议。@rawrrang很高兴它起了作用;)