Home Tutorial Java Swing Set TextField Appearance in java Swing

 
 

Share on Google+Share on Google+
Set TextField Appearance in java Swing
Posted on: December 1, 2009 at 12:00 AM
Advertisement
In this section, you will learn how to change the border color of the textbox.

Set TextField Appearance in java Swing

In this section, we are going to change the border color of the textbox. For this purpose, we have allowed the user to input name. If the user will enter any integer in place of his/her name, the color of the textbox border will changed to red. To set the border color, we have used the method setBorder(BorderFactory.createLineBorder(Color.red)).

Here is the code:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.regex.*;

public class TextFieldBorderColor extends JFrame {
	JTextField text1, text2;
	JLabel label1, label2;
	JPanel panel;
	JButton b;

	public TextFieldBorderColor() {
		label1 = new JLabel("Enter Name");
		text1 = new JTextField(10);
		b = new JButton("Submit");
		panel = new JPanel(new GridLayout(2, 2));
		panel.add(label1);
		panel.add(text1);
		panel.add(b);
		b.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String value1 = text1.getText();
				Pattern p = Pattern.compile("[0-9]");
				Matcher m = p.matcher(value1);
				if (m.find()) {
					text1.setBorder(BorderFactory.createLineBorder(Color.red));
				} else if (text1.equals("")) {
					text1.setBorder(BorderFactory.createLineBorder(Color.red));
				} else {
					text1.setBorder(BorderFactory.createLineBorder(Color.gray));
				}
			}
		});
		add(panel);
		setVisible(true);
		pack();
	}

	public static void main(String[] args) {
		TextFieldBorderColor color = new TextFieldBorderColor();
	}
}

Output:

On clicking the button, a red border line will get displayed on the textfield.

Advertisement

Related Tags for Set TextField Appearance in java Swing:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 1, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com