使用静态方法从另一个类中的JTextField获取文本



我得到了一些面板。第一个包含一个JTextField,用于获取玩家的用户名


public class FirstPanel extends JPanel {
public static final JTextField usernameText = new JTextField(30);
public FirstPanel() {
this.setBackground(Color.GREEN);
JLabel enterName = new JLabel("ENTER YOUR NAME");
this.add(enterName);
this.add(usernameText);
usernameText.addActionListener(e ->
{
if (isThereUsername()) ;
CardLAyout.cl.show(CardLAyout.panelCont, "2");
});

当你输入文本时,你被重定向到另一个面板,在那里我想显示下面的消息";Hello*由于JTextfield"从第一个面板获得的用户名;让我们玩个游戏。

我在第二个JPanel的类中写了以下代码(ifThereUsername函数只是用来判断是否有文本(。然而,用户名没有显示,我只是阅读了消息的其余部分

if (FirstPanel.isThereUsername()) {
hello = new JLabel("HELLO " + FirstPanel.getUsername() + "n LET'S START THE GAME RIGHT NOW ! ");
this.add(hello);
} else {
hello = new JLabel("HELLO n let's start the game !");
this.add(hello);
}

函数getUsername在第一个面板中

public static String getUsername(){
return usernameText.getText();
}

我真的很难将它们之间的类连接起来。起初,我在同一个类中编写了所有的JPanel,但它非常混乱。所以我使用静态方法

不建议静态访问。。。

让FirstPanel访问SecondPanel(或其他方式(

在FirstPanel中介绍所需的构造函数,并记住字段中对secondPanel的引用

以及在addActionListener实现中调用secondPanel.setUserName((;

public FirstPanel() {
private SecondPanel secondPanel;
FirstPanel(SecondPanel secondPanel) {
secondPanel = secondPanel;
}
}

代码中的某个位置:新的第一小组(第二小组(;

最新更新