gpt4 book ai didi

JAVA:在 Jframe GUI 中将用户输入保存为字符串

转载 作者:行者123 更新时间:2023-11-29 03:16:41 25 4
gpt4 key购买 nike

新人在这里。我已经浏览了几个小时,但我仍然无法找出将用户输入保存为 Jframe 文本字段中的字符串的正确方法。任何帮助,将不胜感激。我想将用户的文本保存到变量 userWords 中。

package cipher;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;

public class cipherApp extends JFrame {


private static final int WIDTH = 700;
private static final int HEIGHT = 700;

private String userWords; // stores user input into a string

public cipherApp(){
setTitle("Camo Cipher");
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

}
public static void main(String[] args){
cipherApp newInstance = new cipherApp();

}
}

最佳答案

您必须使用 JTextField 和 JButton 来提交使用输入:

public class Test extends JFrame {

String userWord = "";
JTextField userInput = new JTextField(10);
JButton submit = new JButton("Submit");

public Test() {
super("Camo Cipher");
JPanel centerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null); // This center the window on the screen
submit.addActionListener( (e)-> {
submitAction();
});
centerPanel.add(userInput);
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
southPanel.add(submit);
Box theBox = Box.createVerticalBox();
theBox.add(Box.createVerticalStrut(100));
theBox.add(centerPanel);
theBox.add(Box.createVerticalStrut(200));
theBox.add(southPanel);
add(theBox);
}

private void submitAction() {
// You can do some validation here before assign the text to the variable
userWord = userInput.getText();
}

public static void main(String[] args) {
new Test().setVisible(true);
}
}

关于JAVA:在 Jframe GUI 中将用户输入保存为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26151920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com