Java 常用动作事件监听

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class guess extends JFrame{
	
	public guess(){
		
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setBounds(500,200,500,120);
		Container c = getContentPane();
		
		JPanel centerP = new JPanel();//JPanel 是轻量级容器
		centerP.setLayout(new FlowLayout());
		c.add(centerP,BorderLayout.CENTER);
		
		
		JPanel southP = new JPanel();
		JLabel console = new JLabel("点击组件");
		southP.add(console);
		c.add(southP, BorderLayout.SOUTH);
		
		JButton btn = new JButton("按钮");
		centerP.add(btn);
		btn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				console.setText("按钮被点击");
			}
		});
		
		JTextField it = new JTextField(10);//构造指定10列的新的JTextField
		centerP.add(it);
		it.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				
				//动作事件可以捕捉是由谁触发
				Object object = e.getSource();
				JTextField jTextField = (JTextField) object;
				System.out.println(jTextField.getText());
				
				console.setText("文本框中点击了回车");
			}
		});
	
		
		JCheckBox jCheckBox = new JCheckBox("多选框");
		centerP.add(jCheckBox);
		jCheckBox.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				console.setText("多选框被点击");
			}
		});
		
		
		
		JRadioButton jRadioButton = new JRadioButton("单选框");
		centerP.add(jRadioButton);
		jRadioButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				console.setText("单选框被点击");
			}
		});
		
		
		String val[] = {"单选1", "单选2", "单选3"};
		JComboBox jComboBox = new JComboBox(val);
		centerP.add(jComboBox);
		jComboBox.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				console.setText("下拉列表被选择");
			}
		});
		
	}
	
	
	public static void main(String[] args) {
		new guess().setVisible(true);
	}
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券