jframe窗口添加文本
时间: 2023-10-10 09:08:01 浏览: 80
你可以使用JTextArea或JLabel组件来向JFrame窗口中添加文本。以下是使用JTextArea组件向JFrame添加文本的示例代码:
```
import javax.swing.*;
public class MyFrame extends JFrame {
public MyFrame() {
JTextArea textArea = new JTextArea("Hello World!");
add(textArea);
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new MyFrame();
}
}
```
这将创建一个包含文本“Hello World!”的JTextArea组件,并将其添加到JFrame窗口中。你可以根据需要更改文本内容和窗口大小。
相关问题
如何创建 JFrame窗口 并显示文本
首先,你需要导入 Java 的 Swing 库。然后,你可以按照以下步骤创建 JFrame 窗口并在其中显示文本:
1. 创建 JFrame 对象:
```java
JFrame frame = new JFrame("My Frame");
```
2. 设置 JFrame 的大小和位置:
```java
frame.setSize(400, 300);
frame.setLocationRelativeTo(null); // 将窗口放在屏幕正中央
```
3. 创建一个 JTextArea 对象:
```java
JTextArea textArea = new JTextArea("Hello, World!");
```
4. 将 JTextArea 添加到 JFrame 中:
```java
frame.add(textArea);
```
5. 设置 JFrame 可见:
```java
frame.setVisible(true);
```
完整代码如下:
```java
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
JTextArea textArea = new JTextArea("Hello, World!");
frame.add(textArea);
frame.setVisible(true);
}
}
```
运行该程序,你将看到一个包含文本 "Hello, World!" 的 JFrame 窗口。
在Java窗口添加文字
在Java窗口中添加文字可以使用JLabel组件,在JLabel中设置需要显示的文本即可。
以下是一个简单的示例代码:
```java
import javax.swing.JFrame;
import javax.swing.JLabel;
public class AddTextToWindow {
public static void main(String[] args) {
// 创建 JFrame 实例
JFrame frame = new JFrame("添加文字到窗口");
// 设置窗口大小
frame.setSize(350, 200);
// 创建一个 JLabel 实例
JLabel label = new JLabel("这是添加到窗口的文字");
// 将标签添加到窗口
frame.add(label);
// 设置窗口可见
frame.setVisible(true);
}
}
```
在该代码中,首先创建了一个JFrame窗口实例,并设置了窗口的大小。然后创建一个JLabel实例,并将该实例添加到窗口中。最后设置窗口可见。执行该代码后,窗口中将会显示添加的文字。
阅读全文
相关推荐
















