I've got question regarding to typing in JTextField. My program search thru few csv files and look for specified in JTextField string. I have add to readLine function ".toLowerCase" to read all strings as lowercase. Is it possible to set JTextField to automatically convert uppercase to lower case while writing to JTextField?
if (line.toLowerCase().contains(searchedString))...
Yes, you can use the KeyListener and when a key is pressed in the textfield, you will make the input string lowerCase while keeping the cursor position where it was. Like the code below:
jTextField1.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
int pos = jTextField1.getCaretPosition();
jTextField1.setText(jTextField1.getText().toLowerCase());
jTextField1.setCaretPosition(pos);
}
});
Source:
Value Change Listener to JTextField
Finding the cursor text position in JTextField
You can create a class that extends DocumentFilter class and override methods insertString and replace so that:
In insertString method it will call it's super, passing in one of the parameters string.toLowerCase()
In replace method it will call it's super, passing in one of the parameters text.toLowerCase()
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
class LowerCaseDocumentFilter extends DocumentFilter {
#Override
public void insertString(final FilterBypass fb, final int offset, final String string, final AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, string.toLowerCase(), attr);
}
#Override
public void replace(final FilterBypass fb, final int offset, final int length, final String text, final AttributeSet attrs) throws BadLocationException {
super.replace(fb, offset, length, text.toLowerCase(), attrs);
}
}
then adds an instance of this class so that the JTextField will automatically convert to lower case:
class Main {
public static void main(String[]args) {
JFrame jFrame = new JFrame("Example");
jFrame.setSize(500, 500);
jFrame.setVisible(true);
JPanel jPanel = new JPanel();
jFrame.add(jPanel);
JTextField jTextField = new JTextField("Example JTextField");
((AbstractDocument)jTextField.getDocument()).setDocumentFilter(new LowerCaseDocumentFilter());
jPanel.add(jTextField);
jFrame.pack();
}
}
Source:
https://stackoverflow.com/a/11573312
You can create your own class by extending the JTextfield and override constructor/setter method.
Related
I'm using java swing and trying to enter Numbers only into a JTextField.
when typing a char I want to show an Invalid message, and prevent from typing the char into the JTextField.
idText.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
try
{
int i = Integer.parseInt(idText.getText()+e.getKeyChar());
validText.setText("");
}
catch(NumberFormatException e1) {
e.consume();
validText.setText("Numbers Only!");
}
}
});
for some reason, e.consume() doesnt work as I expected, and i can type chars.
Generally, adding a custom KeyListener to prevent characters in a JTextField is not recommended. It would be better for users (and easier for you as programmer) to use a component that it has been created for only-numbers input.
JSpinner is one of them.
JFormattedTextField is another one.
If you insist of doing it your self though, it would be better to achieve it with a DocumentFilter and not with a KeyListener. Here is another example as well.
In addition to these examples, here is my solution:
public class DocumentFilterExample extends JFrame {
public DocumentFilterExample() {
super("example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
JTextField field = new JTextField(15);
AbstractDocument document = (AbstractDocument) field.getDocument();
document.setDocumentFilter(new OnlyDigitsDocumentFilter());
add(field);
setLocationByPlatform(true);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DocumentFilterExample().setVisible(true));
}
private static class OnlyDigitsDocumentFilter extends DocumentFilter {
#Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
text = keepOnlyDigits(text);
super.replace(fb, offset, length, text, attrs);
}
#Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
string = keepOnlyDigits(string);
super.insertString(fb, offset, string, attr);
}
private String keepOnlyDigits(String text) {
StringBuilder sb = new StringBuilder();
text.chars().filter(Character::isDigit).forEach(sb::append);
return sb.toString();
}
}
}
Is there a way to make the end of a JTextArea editable and make anything that has already been printed to it not editable?
What I mean by this is if I've written "Hello World" for example to a JTextArea, how could I make it so that the user can type in whatever they want after "Hello World" but they cannot type before that or delete the already printed text?
Below is a small program to demonstrate my troubles...
public class Test {
public static void main(String[] args) {
//Here I create a simple JFrame with JTextArea
JTextArea textArea = new JTextArea();
JFrame frame = new JFrame();
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setSize(250, 250);
textArea.setEditable(true);
textArea.setVisible(true);
frame.add(textArea);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*Here I print "Hello World" onto the text area.. after the ">>" I want the
the user to be able to type whatever they want.. however I don't want them
to be able to edit the "Hello World"*/
textArea.append("Hello World\n>>");
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
In the example the user is able to enter whatever text they want.. which is what I want.. however they are also able to edit the text that I printed using append.. which I don't want..
How can I solve this?
Yes, a DocumentFilter will work. Create one that only allows addition of text if the addition is at the end of the document -- that is if the offset equals the document's length. Also totally inactivate the remove method. Something like so:
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class MyFilter extends DocumentFilter {
#Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException {
// only insert text if at the end of the document
// if offset == document length
if (offset == fb.getDocument().getLength()) {
super.insertString(fb, offset, string, attr);
}
}
#Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
// only replace text if at the end of the document
// if offset == document length
if (offset == fb.getDocument().getLength()) {
super.replace(fb, offset, length, text, attrs);
}
}
#Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
// do nothing. Totally inactivate this
}
}
And you could test it like so:
import javax.swing.*;
import javax.swing.text.PlainDocument;
#SuppressWarnings("serial")
public class LimitedTextArea extends JPanel {
private JTextArea textArea = new JTextArea(15, 50);
public LimitedTextArea() {
// get textArea's Document and cast to PlainDocument:
PlainDocument document = (PlainDocument) textArea.getDocument();
// set the document's filter with "MyFilter"
document.setDocumentFilter(new MyFilter());
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(scrollPane);
}
private static void createAndShowGui() {
LimitedTextArea mainPanel = new LimitedTextArea();
JFrame frame = new JFrame("LimitedTextArea");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
You could also use a NavigationFilter:
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class NavigationFilterPrefix extends NavigationFilter
{
private int prefixLength;
private Action deletePrevious;
public NavigationFilterPrefix(int prefixLength, JTextComponent component)
{
this.prefixLength = prefixLength;
deletePrevious = component.getActionMap().get("delete-previous");
component.getActionMap().put("delete-previous", new BackspaceAction());
component.setCaretPosition(prefixLength);
}
#Override
public void setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
{
fb.setDot(Math.max(dot, prefixLength), bias);
}
#Override
public void moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
{
fb.moveDot(Math.max(dot, prefixLength), bias);
}
class BackspaceAction extends AbstractAction
{
#Override
public void actionPerformed(ActionEvent e)
{
JTextComponent component = (JTextComponent)e.getSource();
if (component.getCaretPosition() > prefixLength)
{
deletePrevious.actionPerformed( null );
}
}
}
private static void createAndShowUI()
{
JTextField textField = new JTextField("Prefix_", 20);
textField.setNavigationFilter( new NavigationFilterPrefix(7, textField) );
JFrame frame = new JFrame("Navigation Filter Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(textField);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
This will allow the user to edit the text they add to the text field.
This will prevent the fixed text from being selected.
For more advanced features, check out the Protected Document which allows you to protect multiple areas of the Document from being changed.
I have created an external class that overrides JTextField. In the class I have added a DocumentListener which replaces prevents a certain character from being entered. Below is code (its not exact code, for purpose of simplicity of this question):
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
class test extends JTextField{
private String filteredText;
public void getDefaultText(){
super.getText();
}
public String getText(){
return filteredText;
}
public void remword(){
super.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent arg0) {
}
#Override
public void insertUpdate(DocumentEvent arg0) {
Runnable ru = new Runnable() {
#Override
public void run() {
String finalText = getDefaultText().replace("xyz", "asd");
setText(finalText);
filteredText = finalText;
}
}
};
SwingUtilities.invokeLater(ru);
}
#Override
public void removeUpdate(DocumentEvent arg0) {
}
});
}
}
Now this code works fine unless I use the getText() method which returns error Attempt to mutate in notificaton. I have tried messing around with synchronized and Runnable to no avail.
From DocumentListener:
The DocumentEvent notification is based upon the JavaBeans event model. There is no guarantee about the order of delivery to listeners, and all listeners must be notified prior to making further mutations to the Document. This means implementations of the DocumentListener may not mutate the source of the event (i.e. the associated Document).
You should use a DocumentFilter for control over document manipulation.
By the way, using getText() shouldn't throw this exception. You probably meant setText(String).
You don't need to subclass JTextField for this use case:
((AbstractDocument) textField.getDocument()).setDocumentFilter(new DocumentFilter() {
#Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, sanitize(string), attr);
}
#Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
super.replace(fb, offset, length, sanitize(text), attrs);
}
private String sanitize(String s) {
return s == null ? null : s.replace("xyz", "asd");
}
});
Beware that my solution would still allow "xyz" in the document if entered letter by letter or by removing e.g. "_" from "xy_z".
I wanted to make a JTextArea where the user can't erase the previous line. Just like the Command Prompt in Windows and the terminal in Linux, you can't edit previous lines.
This is what I've come up with, but it doesn't seem to work, and I can only come up with one reason for this, but it appears to be more than just one reason.
if(commandArea.getCaretPosition() < commandArea.getText().lastIndexOf("\n")){
commandArea.setCaretPosition(commandArea.getText().lastIndexOf("\n"));
}
This block of code lives inside this method:
private void commandAreaKeyPressed(java.awt.event.KeyEvent evt)
You can use DocumentFilter for JTextArea's Document. Runnable working example that allows editing last line only in JTextArea:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.DocumentFilter.FilterBypass;
public class MainClass {
public static void main(String[] args) {
JFrame frame = new JFrame("text area test");
JPanel panelContent = new JPanel(new BorderLayout());
frame.setContentPane(panelContent);
UIManager.getDefaults().put("TextArea.font", UIManager.getFont("TextField.font")); //let text area respect DPI
panelContent.add(createSpecialTextArea(), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null); //center screen
frame.setVisible(true);
}
private static JTextArea createSpecialTextArea() {
final JTextArea textArea = new JTextArea("first line\nsecond line\nthird line");
((AbstractDocument)textArea.getDocument()).setDocumentFilter(new DocumentFilter() {
private boolean allowChange(int offset) {
try {
int offsetLastLine = textArea.getLineCount() == 0 ? 0 : textArea.getLineStartOffset(textArea.getLineCount() - 1);
return offset >= offsetLastLine;
} catch (BadLocationException ex) {
throw new RuntimeException(ex); //should never happen anyway
}
}
#Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
if (allowChange(offset)) {
super.remove(fb, offset, length);
}
}
#Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if (allowChange(offset)) {
super.replace(fb, offset, length, text, attrs);
}
}
#Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
if (allowChange(offset)) {
super.insertString(fb, offset, string, attr);
}
}
});
return textArea;
}
}
How does it work? JTextArea is a text control, actual data has Document. Document allows listening for changes (DocumentListener), and some documents allow to set DocumentFilter to forbid changes. Both PlainDocument and DefaultStyledDocument extend from AbstractDocument, which allows setting a filter.
Be sure to read java doc:
JTextArea
AbstractDocument
DocumentFilter
I recommend also tutorials:
How to use text area
How to Write a Document Listener
Implementing a Document Filter
I use a DocumentListener to handle any change in a JTextPane document. while the user types i want to delete the contents of JTextPane and insert a customized text instead. it is not possible to change the document in the DocumentListener,instead a solution is said here:
java.lang.IllegalStateException while using Document Listener in TextArea, Java
,but i don't understand that, at least i don't know what to do in my case?
DocumentListener is really only good for notification of changes and should never be used to modify a text field/document.
Instead, use a DocumentFilter
Check here for examples
FYI
The root course of your problem is that the DocumentListener is notified WHILE the document is been updated. Attempts to modify the document (apart from risking a infinite loop) put the document into a invalid state, hence the exception
Updated with an example
This is VERY basic example...It doesn't handle insert or remove, but my testing had remove working without doing anything anyway...
public class TestHighlight {
public static void main(String[] args) {
new TestHighlight();
}
public TestHighlight() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextPane textPane = new JTextPane(new DefaultStyledDocument());
((AbstractDocument) textPane.getDocument()).setDocumentFilter(new HighlightDocumentFilter(textPane));
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(textPane));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class HighlightDocumentFilter extends DocumentFilter {
private DefaultHighlightPainter highlightPainter = new DefaultHighlightPainter(Color.YELLOW);
private JTextPane textPane;
private SimpleAttributeSet background;
public HighlightDocumentFilter(JTextPane textPane) {
this.textPane = textPane;
background = new SimpleAttributeSet();
StyleConstants.setBackground(background, Color.RED);
}
#Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
System.out.println("insert");
super.insertString(fb, offset, text, attr);
}
#Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
System.out.println("remove");
super.remove(fb, offset, length);
}
#Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
String match = "test";
super.replace(fb, offset, length, text, attrs);
int startIndex = offset - match.length();
if (startIndex >= 0) {
String last = fb.getDocument().getText(startIndex, match.length()).trim();
System.out.println(last);
if (last.equalsIgnoreCase(match)) {
textPane.getHighlighter().addHighlight(startIndex, startIndex + match.length(), highlightPainter);
}
}
}
}
}
while the user types i want to delete the contents of JTextPane and
insert a customized text instead.
this isn't job for DocumentListener, basically this Listener is designed to firing events out from JTextComponents to the another JComponent, to Swing GUI, implemented methods in used Java
have look at DocumentFilter, this provide desired methods to change, modify or update own Document (model for JTextComponents) on runtime
Wrap the code you call in SwingUtilities.invokeLater()