Repositioning Viewable Text in TextArea

Repositioning Viewable Text in TextArea

Question:
Can I make the text in a TextArea scroll to a given line? For example, I have 100 lines of text in a TextArea with 20 viewable rows. Can I scroll the text (without manipulating the scrollbars physically) so that lines 70-90 are displayed in the TextArea?

Answer:
This is an excellent example of where you should use the Swing classes because of their enhanced functionality. With the regular AWT classes, it is almost impossible to scroll aTextArea automatically. To do so requires getting a reference to theTextArea‘s scrollbar and changing its value with setValue() or setValues(). But there is noway to get a reference to the scrollbar. There may be some intricate trickery you can go through to reach the desired result, but I cannot immediately see it.

Life is much simpler if you use JTextArea. Rather, I should say it is possible to do many more things withJTextArea. The Swing classes are powerful and often simple to use, but also have some idiosyncracies that can entail greater complexity. JTextArea stores its text as a linear sequence of characters, indexed by a single offset. This makes it difficult to reference its contents on a row and column basis.You can, however, query the begin and end offsets of each line of text with getLineStartOffset andgetLineEndOffset. Once you obtain a location offset, you have to convert it to a view coordinate to scroll down to that position.

Unlike TextArea, JTextArea does not have a built-in set of scrollbars. None of the Swing classes do. To create a scrollable component, you have to add it to a JScrollPane. Each component stores a model of its contents that it converts to a coordinate that can be used by the scroll view to position and draw the scrolling area. ForJTextArea, that model implements thejavax.swing.text.Document interface. The class in charge of rendering the component subclasses javax.swing.text.View. These classes need not always be accessed directly because JTextArea contains convenience methods such as modelToView and the already mentionedgetLineStartOffset. The modelToView method will convert a document offset into a view coordinate. Now you have all the pieces necessary to scroll the JTextArea automatically.

Once you obtain a view coordinate, all you have to do is tell the ScrollPane viewport to move to a new position by callingsetViewPosition. The following code listing demonstrates how to make a JTextArea scroll to an arbitrary row. The only tricky part is to remember that a component already must be painted before you call setViewPosition.

import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.text.*;public final class ScrollText extends JFrame {  public static final int FIRST_VISIBLE_ROW = 69;  private JTextArea __textArea;  private JScrollPane __scrollPane;  public ScrollText() {    super("Scroll Text Demo");    Container contentPane;    __textArea = new JTextArea();    __textArea.setColumns(40);    __textArea.setRows(20);    for(int row=1; row < 100; row++)      __textArea.append(Integer.toString(row) + "
");    __scrollPane = new JScrollPane();    __scrollPane.getViewport().add(__textArea);    contentPane = getContentPane();        contentPane.setLayout(new BorderLayout());    contentPane.add(__scrollPane, BorderLayout.CENTER);  }  public void scrollToRow(int row) {    int offset;    JViewport viewport;    Rectangle startLocation;    viewport = __scrollPane.getViewport();    try {      offset =	__textArea.getLineStartOffset(FIRST_VISIBLE_ROW);      startLocation = __textArea.modelToView(offset);      viewport.setViewPosition(new Point(startLocation.x, startLocation.y));    } catch(BadLocationException e) {    }  }  public static void main(String[] args) {    final ScrollText demo;    WindowListener exitListener;    exitListener = new WindowAdapter() {      public void windowClosing(WindowEvent e) {	Window window = e.getWindow();	window.setVisible(false);	window.dispose();	System.exit(0);      }    };    demo = new ScrollText();    demo.addWindowListener(exitListener);    demo.pack();    demo.setVisible(true);    // We have to make sure the JTextArea is painted before    // changing the viewport position.  Otherwise modelToView()    // will return null (see source to JTextComponent and    // javax.swing.plaf.basic.BasicTextUI).  Calling setVisible does    // not guarantee that the window will be painted before    // scrollToRow() is called.    Dimension size = demo.getSize();    ((JComponent)(demo.getContentPane())).paintImmediately(				   0, 0, size.width, size.height);    demo.scrollToRow(FIRST_VISIBLE_ROW);  }}
devx-admin

devx-admin

Share the Post:
5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time