Display text in Jframe

Asked

Viewed 2,024 times

1

I would like to know how to assemble a text in my Java class, but this text would have the contents of a record of my database. I’ve done more or less that using JLabel but it creates one-line labels and would like to create a multi-line text. I would like to place this text within a JFrame, but I don’t know how to do it or what component to use: Jlabel, Jtextfield, Jtextarea?

1 answer

4


For multi-line text, you can make use of the component JTextArea same. In order for the line breaking to be done in order to adapt the text to the size of its component, call the method setLineWrap and setWrapStyleWord of JtextArea, passing by true as a parameter.

Take an example:

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

public class JTextAreaTest {
  public static void main(String[] args) {

    JFrame frame = new JFrame("JTextArea Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    String text = "Lorem Ipsum is simply dummy text of "
    + "the printing and typesetting industry. Lorem Ipsum has been "
    + "the industry's standard dummy text ever since the 1500s, when an "
    + "unknown printer took a galley of type and scrambled it to make a type "
    + "specimen book. It has survived not only five centuries, "
    + "but also the leap into electronic typesetting, remaining essentially unchanged.";

    JTextArea textAreal = new JTextArea(text);
    textAreal.setPreferredSize(new Dimension(300, 150));
    textAreal.setLineWrap(true);
    textAreal.setWrapStyleWord(true);

    JScrollPane scrollPane = new JScrollPane(textAreal,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    frame.add(scrollPane);
    frame.pack();
    frame.setVisible(true);
  }
}

Resulting in:

inserir a descrição da imagem aqui

In the example, I left the active Scrolls only for demonstrative purposes, if you do not want this scroll to appear without the need, start the JScrollPane passing only to textarea.

Recalling that the JtextArea, because it is a component that can be expanded according to its content, it should always be passed to a JScrollPane, otherwise it will not be able to create Scrolls when the text inside it exceeds the visible area.

  • Thank you, it’s very nice!!!!

  • @Sarah :)

  • I just realized to delete the text

  • sorry but there would be a way to stop it ??

  • @Sarah textArea.setEditable(false);

  • It worked!! Tks Tks Tks :)

  • How to call it inside an event in jmenuBar ? If you just put it as a class it does nothing, if it is main ...

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.