JTextField getText() 工作不正常 [英] JTextField getText() not working correctly
问题描述
我在实现 getText() 方法时遇到问题.出于某种原因,当我在文本框中按 Enter 键时,输入不会被传输到名为 playerOneName 的字符串中.我曾尝试使用动作侦听器和其他方法,但没有成功,任何建议将不胜感激.
I am having trouble implementing the getText() method. For some reason when I press enter on the text box the input is not being transferred into a string called playerOneName. I've tried to put in an action listener and other methods but I have had no success, any advice would be greatly appreciated.
//imports
import java.lang.*;
import java.util.*;
import java.util.List;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class mainClass extends JPanel implements ActionListener {
//constant variables to use
private static JTextField textField;
private static final long serialVersionUID = 1L;
public mainClass() {
}
public void paintComponent(Graphics g) {
//set background color to white
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
public static void initializeBoard() {
}
public static void main(String[] args) {
// title of frame
JFrame frame = new JFrame("Risk");
textField = new JTextField(20);
frame.add(textField, BorderLayout.SOUTH);
String playerOneName= textField.getText();
JLabel Name = new JLabel("");
Name.setText(playerOneName);
frame.add(Name,BorderLayout.EAST);
JLabel welcome = new JLabel("");
welcome.setText("Please Enter name for Player 2 in the text box at the bottom");
frame.add(welcome,BorderLayout.NORTH);
// make sure it closes correctly
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame size in pixels
final int FRAME_WIDTH = 1000;
final int FRAME_HEIGHT = 700;
frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
// makes sure the frame is visible
frame.setVisible(true);
mainClass main = new mainClass();
frame.add(main);
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
推荐答案
我猜想您想在将 playerOneName 写入 textField 后,在每次按 Enter 键时都想获得它.问题是您没有向组件添加侦听器,因此您提供的代码中没有发生任何事情
I guess that you want to get the playerOneName whenever you hit enter after having written it in the textField. The problem is that you are not adding a listener to the component, so nothing is happening in the code you provided
在这里,您将添加侦听器(例如,按下 Enter 后会触发)并打印它.您现在可以获取并使用该值.
Here, you would be adding the listener (which would triggered after pressing enter, for instance) and just printing it. You can now take the value and use it.
...
frame.add(textField, BorderLayout.SOUTH);
textField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(textField.getText());
}
});
...
这篇关于JTextField getText() 工作不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!