如何让 JTextArea textArea在JFrame居中显示
时间: 2024-05-07 15:20:56 浏览: 82
可以通过设置JScrollPane的位置和大小来让JTextArea在JFrame居中显示。具体的实现方法如下:
```
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setBounds(50, 50, 300, 200); // 设置JScrollPane的位置和大小
frame.add(scrollPane); // 将JScrollPane添加到JFrame中
```
在上面的代码中,我们首先创建了一个JTextArea和一个JScrollPane,并将JTextArea添加到JScrollPane中。然后,我们通过设置JScrollPane的位置和大小来确定JTextArea在JFrame中的位置和大小。最后,我们将JScrollPane添加到JFrame中即可。
如果你想让JTextArea在JFrame的中央显示,可以通过以下代码来实现:
```
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int centerX = (int) (screenSize.getWidth() - scrollPane.getWidth()) / 2;
int centerY = (int) (screenSize.getHeight() - scrollPane.getHeight()) / 2;
scrollPane.setBounds(centerX, centerY, 300, 200); // 设置JScrollPane的位置和大小
frame.add(scrollPane); // 将JScrollPane添加到JFrame中
```
在上面的代码中,我们首先获取了屏幕的大小,然后通过计算JScrollPane的位置,将JTextArea居中显示在JFrame中。最后,我们将JScrollPane添加到JFrame中即可。
阅读全文
相关推荐














