话说内部类与匿名内部类、正则表达式检验计算器输入(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() {@Overridepublic 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 {@Overridepublic void focusGained(FocusEvent e) {inputMatches();}}}