【发布时间】:2021-05-04 07:27:39
【问题描述】:
我在实现 getText() 方法时遇到了问题。出于某种原因,当我在文本框中按 Enter 时,输入没有被传输到名为 playerOneName 的字符串中。我尝试了一个动作监听器和其他方法,但我没有成功,任何建议将不胜感激。
//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) {
}
}
【问题讨论】:
-
不要重写paintComponent来改变面板的背景颜色。相反,您只需使用:
main.setBackground( Color.WHITE );