JTextArea大小可变
时间: 2023-05-29 10:01:28 浏览: 73
JTextArea大小可变,一般可以通过设置其可编辑和自动换行等属性实现:
1.设置可编辑属性为true。
```java
JTextArea textArea = new JTextArea();
textArea.setEditable(true);
```
2.设置自动换行属性为true。
```java
JTextArea textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
```
其中setLineWrap(true)表示启用自动换行,setWrapStyleWord(true)表示只在单词或汉字之间换行。
此外,如果需要在窗口大小改变时,JTextArea的大小也跟着改变,可以将其添加到JScrollPane中,并将该JScrollPane添加到窗口中。
```java
JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane, BorderLayout.CENTER);
```
相关问题
设置 JTextArea的大小可变
要设置 JTextArea 的大小可变,需要将其放置在 JScrollPane 中。在默认情况下,JScrollPane 中的 JTextArea 是可以滚动的,并且可以自动适应其大小。通过设置 JScrollPane 的 preferredSize 属性,可以控制 JScrollPane 的大小。
以下是一个示例代码,演示如何设置 JTextArea 的大小可变:
```
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame {
private JTextArea textArea;
public MainFrame() {
initComponents();
}
private void initComponents() {
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(400, 400));
add(scrollPane, BorderLayout.CENTER);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
}
```
在上述代码中,将 JTextArea 放置在 JScrollPane 中,并设置 JScrollPane 的 preferredSize 为 400x400。当 JTextArea 中的文本超出了它的可见区域时,JScrollPane 将自动启用滚动条。使用此方法,可以使 JTextArea 随着窗口的调整而自动适应大小。
jtextArea设置大小
要设置JTextArea的大小,可以使用setPreferredSize(Dimension)方法或者setBounds(int,int,int,int)方法。其中,setPreferredSize(Dimension)方法接受一个Dimension对象,该对象包含了JTextArea的宽度和高度。例如,下面的代码设置了JTextArea的大小为400x300像素:
```
JTextArea textArea = new JTextArea();
textArea.setPreferredSize(new Dimension(400, 300));
```
另外,setBounds(int,int,int,int)方法接受4个参数,分别是x、y坐标和宽度、高度。例如,下面的代码设置了JTextArea的位置和大小:
```
JTextArea textArea = new JTextArea();
textArea.setBounds(50, 50, 400, 300);
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)