我的代码
package pack.TAgame;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class AL_Test {
public static void main(String[] args){
//JFrame
JFrame Frame = new JFrame("AL Test");
Frame.setSize(720,480);
Frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Frame.setVisible(true);
Frame.setResizable(false);
//Text Area
JTextArea textArea = new JTextArea();
textArea.setBackground(Color.BLACK);
textArea.setForeground(Color.GRAY);
JLabel jl = new JLabel();
Frame.add(textArea);
textArea.setEditable(false);
//Text Field
JTextField jt = new JTextField(50);
JPanel jp = new JPanel();
jp.add(jt);
Frame.add(jt, BorderLayout.SOUTH);
class UserInput extends JFrame implements ActionListener{
public UserInput() {
}
public void actionPerformed(ActionEvent e) {
JTextField jt = new JTextField();
JTextArea textArea = new JTextArea();
jt.addActionListener(this);
String text = jt.getText();
textArea.append("\n>What does the scouter say about his power level?");
}
}
}
}
这可能有点像我的其他帖子......(在我放弃的 actionlistener
部分的代码中,我可能有一些无用的代码)
所以基本上我想要一个 JTextField
,当我键入某个命令时将某些内容打印到我的 JTextArea 中。 (不使用按钮(即按 Enter 键))
最佳答案
从 How to Use Text Fields 上的 Swing 教程中的 TextDemo.java
代码开始。这个例子正是你想要的:
它将 ActionListener 添加到文本字段。当按下 Enter 并且焦点位于文本字段时,将调用 ActionListener。
ActionListener 将从文本字段中获取文本并将其附加到文本区域。
作为奖励,您还将学习如何通过将组件添加到面板,然后将面板添加到框架来更好地构建代码。变量也将在类中定义。
关于java - 使用 JTextField 和 JTextArea (JAVA) 输入特定数字/单词时如何打印一行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32267568/