标签:方法 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