Show text in JFrame

1

I would like to know how I can put text in my Java class, but this text would have the contents of a record in my database. I've done more or less this using JLabel but it creates one-line labels and would like to create multi-line running text. I would like to put this text inside a JFrame , but I do not know how to do it or what component to use: JLabel, JTextField, JTextArea?

    
asked by anonymous 13.11.2016 / 22:38

1 answer

4

For multi-line text, you can use the JTextArea even. In order for the line break to be made to adapt the text to the size of its component, call the method setLineWrap and setWrapStyleWord of JtextArea , passing true as a parameter.

See 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:

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

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

    
13.11.2016 / 22:56