GUI对话框,可以接受用户输入为文本或打开要处理的文件

时间:2015-05-19 06:43:49

标签: java

我正在尝试编写一个GUI对话框,该对话框会在我的程序启动时弹出,并为用户提供输入文本的选项,直接到文本输入框 '或者在他们的机器上某处找到一个文本文件。

程序随后处理此输入以确定它所写的人类语言。

此时我有这个代码,使用户可以选择一个文件,但它不是很容易导航:

   //GET THE USER INPUT

    JFileChooser chooser = new JFileChooser();

    int returnValue = chooser.showOpenDialog( null ) ;

    File file = null;
    if( returnValue == JFileChooser.APPROVE_OPTION ) 
    {
           file = chooser.getSelectedFile() ;
    }
    if(file != null)
    {
         String filePath = file.getPath();
    } 

    //put the input in a useful way
    Scanner s = new Scanner( file );
    ArrayList<String> input_text = new ArrayList<String>();
    while (s.hasNext()){
        input_text.add(s.next());
    }
    s.close();

在我让用户以这种方式向控制台输入文本之前:

扫描仪输入=新扫描仪(System.in);

  System.out.println("Please enter a sentence: ");

  String[] input_text = in.nextLine().split("\\s");

或者可能是这样的:

    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a file name: ");
    System.out.flush();
    String filename = scanner.nextLine();
    File file = new File(filename);

有没有办法合成这两个过程,直接输入文本&amp;选择一个文件,进入一个可用的GUI?

如果他们想要使用文件选择器或输入文本,那么首先让他们选择会更好,但这样做不那么优雅。

1 个答案:

答案 0 :(得分:3)

简短的回答是“是”。答案很长,有点复杂

您需要的是一个能够询问用户他们希望文本来自何处的组件。虽然您可以使用JComboBoxJRadioButton可以做出更好的选择,因为根据用户选择的内容,您获取文字的方式会有所不同。

每次用户更改选择时,您都可以根据需要启用/禁用组件。

最后,您提供了一种方法,当对话框被取消时(希望通过按[OK]),您可以获得文本...

Show me the text

此示例使用Swing,但从概念上讲,它对任何UI框架都是一样的

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                UserInputPane userInputPane = new UserInputPane();
                int result = JOptionPane.showConfirmDialog(null, userInputPane, "Sentence", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
                if (result == JOptionPane.OK_OPTION) {
                    try {
                        List<String> text = userInputPane.getText();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
    }

    public class UserInputPane extends JPanel {

        private JTextField fldText;
        private JTextField fldFileName;
        private JButton browseFileButton;

        private File selectedFile;

        private JRadioButton rbText;
        private JRadioButton rbFile;

        public UserInputPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();

            rbText = new JRadioButton("Text: ");
            rbFile = new JRadioButton("File: ");
            ButtonGroup bg = new ButtonGroup();
            bg.add(rbText);
            bg.add(rbFile);

            fldText = new JTextField(10);
            fldFileName = new JTextField(10);
            fldFileName.setEditable(false);
            browseFileButton = new JButton("...");

            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.WEST;
            add(rbText, gbc);
            gbc.anchor = GridBagConstraints.EAST;
            gbc.gridx++;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            add(fldText, gbc);

            gbc.gridwidth = 1;
            gbc.fill = GridBagConstraints.NONE;
            gbc.gridx = 0;
            gbc.gridy++;
            gbc.anchor = GridBagConstraints.WEST;
            add(rbFile, gbc);
            gbc.anchor = GridBagConstraints.EAST;
            gbc.gridx++;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            add(fldFileName, gbc);
            gbc.gridx++;
            gbc.fill = GridBagConstraints.NONE;
            add(browseFileButton, gbc);

            fldText.setEnabled(false);
            fldFileName.setEnabled(false);
            browseFileButton.setEnabled(false);

            ActionListener listener = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    fldText.setEnabled(rbText.isSelected());
                    fldFileName.setEnabled(!rbText.isSelected());
                    browseFileButton.setEnabled(!rbText.isSelected());

                    if (rbText.isSelected()) {
                        fldText.requestFocusInWindow();
                    }
                }
            };

            rbFile.addActionListener(listener);
            rbText.addActionListener(listener);

            browseFileButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JFileChooser chooser = new JFileChooser();

                    int returnValue = chooser.showOpenDialog(null);

                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        selectedFile = chooser.getSelectedFile();
                        fldFileName.setText(selectedFile.getName());
                    }
                }
            });

        }

        public List<String> getText() throws IOException {
            List<String> text = new ArrayList<>(25);
            if (rbText.isSelected()) {
                text.add(fldText.getText());
            } else if (selectedFile != null) {

                try (BufferedReader br = new BufferedReader(new FileReader(selectedFile))) {
                    String value = null;
                    while ((value = br.readLine()) != null) {
                        text.add(value);
                    }
                }

            }
            return text;
        }

    }

}

详细了解How to Use Buttons, Check Boxes, and Radio ButtonsHow to Make Dialogs了解详情