Wednesday, August 19, 2009

RegEx Test - Swing Application


If validation is part of your chore or you are a RegEx beginner, this tool could make life easier.

Download the source from here.


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

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class RegExTest extends JFrame {
private static final long serialVersionUID = 1L;
private static int WIDTH = 300;
private static int HEIGHT = 150;

private JFrame parent;
private JLabel lblPattern, lblTestString;
private JTextField tfPattern, tfTestString;
private JButton btnTest;

public RegExTest() {
super("RegEx Test");
parent = this;

lblPattern = new JLabel("Pattern");
lblTestString = new JLabel("Test String");
tfPattern = new JTextField();
tfTestString = new JTextField();
btnTest = new JButton("Test");

setLayout(new GridLayout(5,1));
add(lblPattern); add(tfPattern);
add(lblTestString); add(tfTestString);
add(btnTest);

setResizable(false);
setBackground(Color.lightGray);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setLocation(200, 200);
setVisible(true);

btnTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String pattern = tfPattern.getText().toString();
String testString = tfTestString.getText().toString();

if(testString.matches(pattern))
JOptionPane.showMessageDialog(parent, "POSITIVE", "RegEx Test Result!", JOptionPane.INFORMATION_MESSAGE, null);
else
JOptionPane.showMessageDialog(parent, "NEGATIVE", "RegEx Test Result!", JOptionPane.INFORMATION_MESSAGE, null);
}
});
}

public static void main(String[] args) {
new RegExTest();
}
}

No comments:

Post a Comment