用户输入会导致frame.getContentPane.removeAll()停止工作 [英] User input causes frame.getContentPane.removeAll() to stop working
问题描述
在JFrame中,我正在用另一个JPanel替换Jpanel。
Within a JFrame , i am replacing a Jpanel with another JPanel .
package testing;
import java.io.*;
import java.util.*;
import java.security.*;
import javax.xml.bind.DatatypeConverter;
import java.lang.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Testing extends JPanel {
JLabel jl;
ImageIcon icon;
Point pointer;
public static void main(String[] args) {
JFrame jf = new JFrame();
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
JLabel jl1 = new JLabel("Hey1");
JLabel jl2 = new JLabel("Hey2");
jp1.add(jl1);
jp2.add(jl2);
jf.add(jp1);
jf.setVisible(true);
jf.pack();
Scanner myScanner= new Scanner(System.in);
int x = myScanner.nextInt(); // the line causes the code to not work ,
// what is happening
jf.getContentPane().removeAll();
jf.add(jp2);
}
}
奇怪的部分是代码停止工作的时候我试图读取用户输入
The weird part is that the code stops working the moment i try to read user input
int x = myScanner.nextInt();
int x = myScanner.nextInt();
代码: jf.getContentPane()。removeAll();
停止工作,我不能删除目前的JPanel并添加了新的JPanel
The code : jf.getContentPane().removeAll();
stops working and i cant remove the current JPanel and add in the new JPanel
我需要在JPanel替换之前阅读用户输入,我如何解决这个问题?
i need to read in the user input before the JPanel is replaced , how do i resolve this issue??
注意:即使我输入内容,jf.getContentPane()。removeAll()仍然无效
推荐答案
使用 validate()
布局容器的子组件。另外 pack()
窗口
之前
setVisible()
。
Use validate()
to layout the container's subcomponents. Also pack()
the Window
before
setVisible()
.
或者,使用 CardLayout
更改视图和 JTextField
来收集用户输入。
Alternatively, use CardLayout
to change the view and JTextField
to collect user input.
如测试:
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Testing extends JPanel {
JLabel jl;
ImageIcon icon;
Point pointer;
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
JLabel jl1 = new JLabel("Hey1");
JLabel jl2 = new JLabel("Hey2");
jp1.add(jl1);
jp2.add(jl2);
jf.add(jp1);
jf.pack();
jf.setVisible(true);
Scanner myScanner = new Scanner(System.in);
int x = myScanner.nextInt(); // the line causes the code to not work ,
jf.getContentPane().removeAll();
jf.add(jp2);
jf.validate();
}
}
这篇关于用户输入会导致frame.getContentPane.removeAll()停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!