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

时间:2014-10-01 22:47:45

标签: java string swing

Noob在这里。我已经浏览了几个小时,我仍然无法弄清楚将用户输入从我的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();

    }
}

2 个答案:

答案 0 :(得分:4)

您必须使用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);
    }
}

答案 1 :(得分:0)

这是BilaDja代码的变体(我主要更改了图形)。这将使窗口大小在屏幕中间大约一半的屏幕上。如果您想更改尺寸,请更改字段' jf.setSize(x,y);'

package test;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Test extends JFrame {

private static final long serialVersionUID = -5624404136485946868L;

String userWord = "";
JTextField userInput;

public Test() {
JFrame jf = new JFrame();
JPanel panel = new JPanel();
JLabel jl = new JLabel("Test");
JButton jButton = new JButton("Click");
userInput = new JTextField("", 30);
jButton.addActionListener( (e) -> {
    submitAction();
});
jf.setSize(500, 500);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(panel);
panel.add(jl);
panel.add(userInput);
panel.add(jButton);
}

private void submitAction() {
userWord = userInput.getText();
//do something with the variabe userWord here (print it to the console, etc.)
}

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