public class E4 extends JFrame{
private JDialog jd;
private JButton jb;
private JLabel jl;
public E4(){
JFrame jf=new JFrame("事件");
jb=new JButton("开始");
jl=new JLabel("结果");
jd=new JDialog(this,"对话框",true);
jd.setBounds(200,200,200,200);
JTextField jta=new JTextField("");
String s=jta.getText();
jl.setText(s);
jb.addActionListener(new MyListener());
jf.setLayout(new FlowLayout());
jf.add(jb);
jd.add(jl);
jf.add(jta);
setBounds(400,400,400,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400,400);
jf.setVisible(true);
}
class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e){
jd.setVisible(true);
}}
public static void main(String[] args) {
// TODO Auto-generated method stub
new E4();
}
一个小练习,在文本域输入字符,然后在JDialog显示刚才输入的字符,可是这个程序的结果是JDialog没显示刚才输入的结果,求大神指点
------解决方案--------------------
public class E4 extends JFrame {
private JDialog jd;
private JButton jb;
private JLabel jl;
private JTextField jta;
public E4() {
JFrame jf = new JFrame("事件");
jb = new JButton("开始");
jl = new JLabel("结果");
jd = new JDialog(this, "对话框", true);
jd.setBounds(200, 200, 200, 200);
jta = new JTextField(10);
jb.addActionListener(new MyListener());
jf.setLayout(new FlowLayout());
jf.add(jb);
jf.add(jta);
setBounds(400, 400, 400, 400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400, 400);
jf.setVisible(true);
}
class MyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
jl = new JLabel("结果");
jl.setText(jta.getText());
jd.add(jl);
jd.setVisible(true);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new E4();
}
}
------解决方案--------------------
楼上正解,你的
- Java code
import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JTextField;public class E4 extends JFrame { private JDialog jd; private JButton jb; private JLabel jl; private JTextField jta ; //把这个放出来 ,因为你的点击事件重要取出来 public E4() { JFrame jf = new JFrame("事件"); jb = new JButton("开始"); jl = new JLabel("结果"); jd = new JDialog(this, "对话框", true); jd.setBounds(100, 100, 200, 200); jta = new JTextField(15); String s = jta.getText(); jl.setText(s); jb.addActionListener(new MyListener()); jf.setLayout(new FlowLayout()); jf.add(jb);// jd.add(jl); //这时候还没有数据 ,可以不要放上去 jf.add(jta); setBounds(400, 400, 400, 400); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(400, 400); jf.setVisible(true); } class MyListener implements ActionListener { public void actionPerformed(ActionEvent e) { jl.setText(jta.getText());//设置完数据 jd.add(jl); //加到对话框上 jd.setVisible(true); } } public static void main(String[] args) { // TODO Auto-generated method stub new E4(); }}