码迷,mamicode.com
首页 > 其他好文 > 详细

按钮组件

时间:2019-05-14 23:11:25      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:方法   cti   npe   listener   str   java   ttext   list   点击   

流布局 为按钮添加监听事件  

方法一:

抽象类与接口 

package JAVA20190514;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class TestJFrame extends JFrame {

    JPanel jp;
    JButton jbSave;
    JButton jbCancel;
    JTextField tx1;
    JTextField tx2;
    
    public TestJFrame(){
        super("窗口");
        jp = new JPanel();
        tx1 = new JTextField(5);
        tx2 = new JTextField(5);
        jbSave = new JButton("保存");
        jbCancel = new JButton("取消");
        add(jp);
        jp.add(jbSave);
        jp.add(jbCancel);
        jp.add(tx1);
        jp.add(tx2);
        setVisible(true);
        setBounds(500, 500, 500, 500);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        jbSave.addActionListener(new JbSaveAction());
        jbCancel.addActionListener(new JbCancelAction());

    }
    
    class JbSaveAction implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            tx1.setText("保存按钮");        
        }        
    }
    
    class JbCancelAction implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            tx2.setText("取消按钮");        
        }        
    }
        
    public static void main(String[] args) {
        TestJFrame ceshi =new TestJFrame();   
    }
}

方法二:

package 外来;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestJFrame2 extends JFrame {

    JPanel jp;
    JButton jbSave;
    JButton jbCancel;
    JTextField tx1;
    JTextField tx2;
    
    public TestJFrame2(){
        super("窗口");
        jp = new JPanel();
        tx1 = new JTextField(5);
        tx2 = new JTextField(5);
        jbSave = new JButton("保存");
        jbCancel = new JButton("取消");
        add(jp);
        jp.add(jbSave);
        jp.add(jbCancel);
        jp.add(tx1);
        jp.add(tx2);
        setVisible(true);
        setBounds(500, 500, 500, 500);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        jbSave.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tx1.setText("点击了保存按钮");    
            }});
        jbCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tx2.setText("点击了取消按钮");    
            }});
    }
    public static void main(String[] args) {
        TestJFrame ceshi =new TestJFrame();   
    }
}

 

按钮组件

标签:方法   cti   npe   listener   str   java   ttext   list   点击   

原文地址:https://www.cnblogs.com/LiangRJ/p/10865211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!