话说内部类与匿名内部类、正则表达式检验计算器输入(00)处理方式、设置JRame背景颜色实例

package com.meteor.regx;

import java.awt.FlowLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.regex.Pattern;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 * 
 * @author Xuyunfei
 * 本实例程序是为测试计算器输入无效的数字(00······)编写
 *其中涉及了内部类以及匿名内部类、正则表达式、事件监听的用法
 */
public class TestFieldInput extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unused")
	private final int width;
	@SuppressWarnings("unused")
	private final int height;
	@SuppressWarnings("unused")
	private Pattern p;
	private String regx = "^0+";
	private JTextField jtx;

	public static void main(String[] args) {
		new TestFieldInput(300, 400);
	}

	private TestFieldInput(int width, int height) {
		this.width = width;
		this.height = height;

		// this.getContentPane().setLayout(new FlowLayout());
		this.setLayout(new FlowLayout());
		this.setLocation(300, 200);
		this.setSize(width, height);
		jtx = new JTextField("0.0", 15);
		jtx.addFocusListener(new TextFocusMoniter());
		/*
		 * JAVA SWING中JFRAME构造的时候为默认添加一个RootPane
		 * 默认的布局管理器为BORDERLayout
		 * 通常我们在调用使用下面一条语句设置背景颜色时是看不到的
		 * 这里其实我们设置的是FRAME,被ROOTPANE挡住了看不到
		 * 这时可用下面这条语句 this.getContentPane().setBackground(Color.blue)
		 * 达到想要的效果
		 */
		// this.setBackground(Color.red);
		// this.getContentPane().setBackground(Color.blue);
		this.add(jtx);

		this.setResizable(false);
		this.setVisible(true);
		this.pack();
		// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//这是为使用匿名内而写的匿名内,上一行语句可达到同样的结果
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				setVisible(false);
				System.exit(-1);
			}
		});
	}

	public void inputMatches() {
		p = Pattern.compile(regx, Pattern.CASE_INSENSITIVE);

		if (this.jtx.getText() == null || this.jtx.getText().equals("")) {
			return;
		}

		if (Pattern.matches(regx, this.jtx.getText())) {
			JOptionPane.showMessageDialog(null, "你输入了不正确的数据,请重新输入!!!");
			this.jtx.setText("输入的数字没有任何意义!");
		} else {
			return;
		}
	}

	private class TextFocusMoniter extends FocusAdapter {
		@Override
		public void focusGained(FocusEvent e) {
			inputMatches();
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值