/ / Como posso dimensionar um JTextArea Java Swing - java, swing, gerenciador de layout, jtextarea, tamanho preferido

Como posso dimensionar um Java Swing JTextArea - java, swing, gerenciador de layout, jtextarea, preferredsize

Estou tentando colocar uma área de texto em uma caixa de diálogousando Java Swing. Eu tenho um problema de definir o tamanho deste JTextArea. A largura da área de texto é sempre igual a toda a largura da janela e se estende com a janela se eu a redimensionar.

private void arrangeComponents() {
JTextArea textArea = new JTextArea();
JPanel outerPanel = new JPanel();
outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.PAGE_AXIS));

JScrollPane scrollPane = new JScrollPane(textArea);
outerPanel.add(scrollPane, BorderLayout.CENTER);

Container contentPane = getContentPane();
contentPane.add(outerPanel, BorderLayout.CENTER);
}

Quero que o JTextArea seja alinhado horizontalmente ao centro da janela e não mude de tamanho.

O que eu fiz errado?

Respostas:

7 para resposta № 1

Use o JTextArea(int rows, int columns) construtor que especifica linhas e colunas, como mostrado Aquie não negligencie pack() o anexo Window.


2 para resposta № 2
outerPanel.add(scrollPane, BorderLayout.CENTER);

Um BoxLayout não aceita restrições, portanto o BorderLayout.CENTER é desnecessário.

O problema é que um BoxLayout respeita o tamanho máximo do componente que, para uma barra de rolagem, é definido como muito grande.

Em vez de usar um BoxLayout, basta usar um painel com um FlowLayout.

Execute o exemplo abaixo para ver o que você está fazendo no momento. Em seguida, comente a instrução setLayout (...) e execute novamente. Por padrão, o painel usa um FlowLayout para que você obtenha o que deseja.

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

public class SSCCE extends JPanel
{
public SSCCE()
{
setLayout( new BoxLayout(this, BoxLayout.PAGE_AXIS));

JTextArea textArea = new JTextArea(5, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
//scrollPane.setMaximumSize( scrollPane.getPreferredSize() );

add(scrollPane);
}

private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}

public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Ou se você realmente deseja manter o BoxLayout,deixe mantenha a instrução setLayout (...) e defina o tamanho máximo igual ao tamanho preferido. Muitas pessoas dizem que você nunca deve chamar um método "setXXX ()" diretamente e, em vez disso, deve substituir o método setMaximumSize () da barra de rolagem para retornar apenas o tamanho preferido.

Observe que, ao testar essas duas soluções, reduza a janela que a barra de rolagem para ver como cada layout funciona de maneira diferente.


1 para resposta № 3

Encontrei isso em um site de codificação simples. Este exemplo de código pode ser útil para você.

import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class JTextAreaTest {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JTextArea Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String text = "A JTextArea object represents a multiline area for displaying text. "
+ "You can change the number of lines that can be displayed at a time, "
+ "as well as the number of columns. You can wrap lines and words too. "
+ "You can also put your JTextArea in a JScrollPane to make it scrollable.";
JTextArea textAreal = new JTextArea(text, 5, 10);
textAreal.setPreferredSize(new Dimension(100, 100));
JTextArea textArea2 = new JTextArea(text, 5, 10);
textArea2.setPreferredSize(new Dimension(100, 100));
JScrollPane scrollPane = new JScrollPane(textArea2,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
textAreal.setLineWrap(true);
textArea2.setLineWrap(true);
frame.add(textAreal);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
}

1 para resposta № 4

Basta chamar esse método para sua área de texto: setLineWrap(true);


0 para a resposta № 5

Se JTextArea for inicializado JTextArea text = new JTextArea(int rows, int columns)

você acabou de chamar o método text.setLineWrap(true)

o tamanho do texto "é fixo.