问题描述
我希望用户输入玩家 1 的名称并按 Enter,然后让文本字段再次为空,以便用户可以输入玩家 2 的名称。到目前为止,我只能获取玩家的姓名作为输入但不是玩家二。由于某种原因,我的代码不起作用。任何帮助将不胜感激。提前致谢。
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
static String playerOneName;
static String playerTwoName;
static boolean playerOneNameSet;
static boolean playerTwoNameSet;
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,getWidth(),getHeight());
}
public static void initializeBoard() {
}
public static void main(String[] args) {
// title of frame
JFrame frame = new JFrame("Risk");
JTextField textField = new JTextField(20);
frame.add(textField,BorderLayout.SOUTH);
JLabel welcome = new JLabel("");
welcome.setText("Please Enter name for Player 1 in the text box at the bottom");
frame.add(welcome,BorderLayout.NORTH);
//action listener listens for enter key
textField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
playerOneName= textField.getText();
System.out.println(playerOneName);
playerOneNameSet = true;
System.out.println(playerOneNameSet);
}
});
if(playerOneNameSet == true) {
JTextField textField2 = new JTextField(20);
frame.add(textField2,BorderLayout.SOUTH);
JLabel welcome2 = new JLabel("");
welcome2.setText("Please Enter name for Player 2 in the text box at the bottom");
frame.add(welcome2,BorderLayout.NORTH);
//action listener listens for enter key
textField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
playerTwoName= textField2.getText();
System.out.println(playerTwoName);
playerTwoNameSet = true;
System.out.println(playerTwoNameSet);
}
});
}
// 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) {
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)