swing學習3--按鈕觸發事件及獲取文本框值


package swing;

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.JPanel;
import javax.swing.JTextField;

public class Test {
    public static void main(String[] args) {
        new Text2().setVisible(true);
    }
}
class Text2 extends JFrame{
    private JButton button;
    private JTextField text;
    public Text2(){
        //設置窗口屬性
        super("我是標題");
        this.setSize(250,200);
        this.setLayout(null);
        this.setLocation(500,500);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        
        button = new JButton("按鈕");
        text = new JTextField(20);
        JPanel panel = new JPanel();
        panel.add(button);
        panel.add(text);
        //添加面板
        setContentPane(panel);
        
        //按鈕觸發事件
        button.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                //彈出新窗口
                new Text3(text).setVisible(true);
            }
            
        });
    }
}
class Text3 extends JFrame{
    public Text3(JTextField text){
        super("我是標題");
        this.setSize(200,200);
        this.setLocation(600,300);
        this.setLayout(null);
        //獲取文本框中的值
        String info = ""+text.getText();
        JLabel label = new JLabel(info);
        JPanel panel = new JPanel();
        panel.add(label);
        setContentPane(panel);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM