【发布时间】:2025-02-27 05:20:02
【问题描述】:
我正在用 java 创建一个 GUI,并想使用 JTextArea,但是我在将它添加到框架时遇到了很多麻烦。我将如何创建一个文本区域,然后使用它来读取文本或显示文本?
到目前为止,这是我的 GUI 代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class addMemoUI extends JFrame {
JFrame frame = new JFrame();
/**
* Create the application.
*/
public addMemoUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
JButton button = new JButton("Create");
button.setBackground(new Color(100, 149, 237));
button.setBounds(135, 350, 130, 50);
frame.getContentPane().add(button);
JLabel lblMemos = new JLabel("MEMOS");
lblMemos.setForeground(new Color(100, 149, 237));
lblMemos.setFont(new Font("Moire", Font.BOLD, 30));
lblMemos.setBounds(22, 21, 234, 37);
frame.getContentPane().add(lblMemos);
JButton button_1 = new JButton("Cancel");
button_1.setBackground(new Color(100, 149, 237));
button_1.setBounds(5, 350, 130, 50);
frame.getContentPane().add(button_1);
frame.setBounds(100, 100, 270, 400);
frame.setUndecorated(true); //REMOVES MENU BAR
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnExit = new JButton("");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MemoUI window = new MemoUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
非常感谢:)
【问题讨论】:
-
快速说明:您既是从
JFrame扩展而来,又是使用变量JFrame frame。您可能只想要两者之一。 -
谢谢,我会修改的:)
-
要对您的问题进行排序,您应该使用Layout Manager。使用空布局是个坏主意(代码更长、可靠性更低、可扩展性更低......)。一旦您知道如何使用布局,您就会知道如何将
JTextArea添加到框架/面板。 -
@DSquare +1。 Java GUI 可能必须在多个平台、不同的屏幕分辨率和使用不同的 PLAF 上工作。因此,它们不利于组件的精确放置。要为强大的 GUI 组织组件,请改用布局管理器或 combinations of them,以及 white space 的布局填充和边框。
标签: java swing user-interface textarea layout-manager