Java - Scroll to Specific Text Inside Jtextarea

Java - Scroll to specific text inside JTextArea

This is a VERY basic example. This basically walks the document to find the position of the word within the document and ensures that the text is moved to the viewable area.

It also highlights the match

Sample Image

public class MoveToText {

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

public MoveToText() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new FindTextPane());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class FindTextPane extends JPanel {

private JTextField findField;
private JButton findButton;
private JTextArea textArea;
private int pos = 0;

public FindTextPane() {
setLayout(new BorderLayout());
findButton = new JButton("Next");
findField = new JTextField("Java", 10);
textArea = new JTextArea();
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);

Reader reader = null;
try {
reader = new FileReader(new File("Java.txt"));
textArea.read(reader, null);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}

JPanel header = new JPanel(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
header.add(findField, gbc);
gbc.gridx++;
header.add(findButton, gbc);

add(header, BorderLayout.NORTH);
add(new JScrollPane(textArea));

findButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Get the text to find...convert it to lower case for eaiser comparision
String find = findField.getText().toLowerCase();
// Focus the text area, otherwise the highlighting won't show up
textArea.requestFocusInWindow();
// Make sure we have a valid search term
if (find != null && find.length() > 0) {
Document document = textArea.getDocument();
int findLength = find.length();
try {
boolean found = false;
// Rest the search position if we're at the end of the document
if (pos + findLength > document.getLength()) {
pos = 0;
}
// While we haven't reached the end...
// "<=" Correction
while (pos + findLength <= document.getLength()) {
// Extract the text from teh docuemnt
String match = document.getText(pos, findLength).toLowerCase();
// Check to see if it matches or request
if (match.equals(find)) {
found = true;
break;
}
pos++;
}

// Did we find something...
if (found) {
// Get the rectangle of the where the text would be visible...
Rectangle viewRect = textArea.modelToView(pos);
// Scroll to make the rectangle visible
textArea.scrollRectToVisible(viewRect);
// Highlight the text
textArea.setCaretPosition(pos + findLength);
textArea.moveCaretPosition(pos);
// Move the search position beyond the current match
pos += findLength;
}

} catch (Exception exp) {
exp.printStackTrace();
}

}
}
});

}
}
}

JTextArea scroll to bottom only if text is appended

Check out Smart Scrolling.

If the scrollbar is at the bottom, then as text is appended you will see the new text.

If the user has scrolled to a different position, then the viewport will stay there until the user scrolls back to the bottom.

ActionListener for a specific text inside a JTextArea?

Here try this small program, try to click at the start of student://, that will pop up a message Dialog

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

public class TextAreaExample extends JFrame
{
private JTextArea tarea = new JTextArea(10, 10);
private JTextField tfield = new JTextField(10);

private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tarea.setText("Hello there\n");
tarea.append("Hello student://");
JScrollPane scroll = new JScrollPane(tarea);

tfield.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
tarea.append(tfield.getText() + "\n");
}
});

tarea.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
int x = me.getX();
int y = me.getY();
System.out.println("X : " + x);
System.out.println("Y : " + y);
int startOffset = tarea.viewToModel(new Point(x, y));
System.out.println("Start Offset : " + startOffset);
String text = tarea.getText();
int searchLocation = text.indexOf("student://", startOffset);
System.out.println("Search Location : " + searchLocation);
if (searchLocation == startOffset)
JOptionPane.showMessageDialog(TextAreaExample.this, "BINGO you found me.");
}
});

getContentPane().add(scroll, BorderLayout.CENTER);
getContentPane().add(tfield, BorderLayout.PAGE_END);
pack();
setLocationByPlatform(true);
setVisible(true);
}

public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextAreaExample().createAndDisplayGUI();
}
});
}
}

How to make JTextArea autoscroll

You need to remove this line from your code:

consoleOutput.setPreferredSize(new Dimension( 200,300));

Unfortunately, it prevents your JTextArea from being scrollable because you set static size to that element.

P.S. Stay away from Swing - there are better options in Java

Adding a vertical scroll bar to a JTextArea

This code works:

        JFrame frame = new JFrame();
JPanel panel = new JPanel();

frame.setSize(700, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
panel.setLayout(null);

fileContents = new JTextArea();
JScrollPane sp = new JScrollPane(fileContents);
sp.setBounds(175, 75, 300, 300);
panel.add(sp);

Your had 2 problems:

  1. If fileContents added to sp that added to panel, tou needn't add fileContents to panel.
  2. When using JScrollPane, you should add Components only with the constractor JScrollPane(Component view) and not with the add() method.


Related Topics



Leave a reply



Submit