如何在另一个 class Java 中从 JTextfield 读取用户输入

How to read user input from JTextfield in another class Java

我正在尝试创建将打开指定 URL 的桌面应用程序。

我正在使用 Java 构建应用程序,这是我目前的代码。

browseropen.java

 public class browseropen {


    public static void main(String[] args) {

            JFrame frame = new JFrame("Desktop Browser Search"); // We create our initial app frame
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // next we are making sure our app stops running
            JPanel panel = new JPanel(); // Our new application window
            JLabel optext = new JLabel("Welcome Please Enter URL to Begin!"); // Our new window text
            frame.setSize(400, 400); // Set Application Window Size
            //pack();
            // Now adding Text box
            JTextField txtbox = new JTextField(10);
            JButton gourl = new JButton("Go To URL"); // creating new button to activate browser function
            frame.setVisible(true);
            optext.setVisible(true);
            frame.setLayout( new GridLayout(3,4,5,10));
            panel.add(optext); // We are adding our objects to our app window
            panel.add(txtbox);
            panel.add(gourl);
            frame.add(panel); // And finally we add our app panel to our frame 
            String geturl = txtbox.getText();


     gourl.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             //run client main
             runClient();
         }




public void runClient() {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            String[] args1={"10"};
            openbrowserurl.main(args1);
        }
    });
}
});
    }

    public void texturl() {



    };



}

openbrowser.java

public class openbrowserurl extends browseropen {

    public static void main(String[] args)  {

        Desktop desktop = Desktop.getDesktop();
        String urlinput = "https://www.google.com";
        if( !java.awt.Desktop.isDesktopSupported() ) {
            System.err.println("Desktop Not Supported");
            System.exit(1);
        }
        if (args.length == 0) {
              System.out.println( "Usage: OpenURI [URI [URI ... ]]" );
                System.exit( 0 );
        }

        if(!desktop.isSupported( java.awt.Desktop.Action.BROWSE ) ) {

            System.err.println( "Desktop doesn't support the browse action (fatal)" );
            System.exit( 1 );
        }

        for ( String arg : args ) {

            try {

                java.net.URI uri = new java.net.URI( urlinput );
                desktop.browse( uri );
            }
            catch ( Exception e ) {

                System.err.println( e.getMessage() );
            }
    }

}
}

我可以打开指定的URL,如果它在openbrowser.java中指定,但我想读取我在browseropen.java中创建的JTextField的值。

您目前无法从 browseropen class 中的 JTextField 获取信息,因为它是在静态 main 方法中声明的,因此仅在该方法中可见。你的整个项目让我们大吃一惊——他还不知道面向对象编程或者 Java 如何实现它,因为这阻碍了你的尝试。

建议:

  • 首先,学习 Java 的面向对象编程,包括非静态方法和字段的使用。有很多关于这方面的教程很容易找到,包括可以在这里找到的教程:The Really Big Index
  • 通过提供非静态字段和方法,包括私有 JTextField 字段,使您的浏览器打开更 "OOP" 兼容。
  • 给它一个 public 方法,returns JTextField
  • 持有的字符串
  • 不要让您的 openbrowserurl class 扩展 browseropen,因为这毫无意义。而是让第一个 class 包含第二个 class 的实例。

其他问题:

  • 您尝试使用布局管理器而不是空布局和 setBounds(...) 很好,但我对您尝试做的事情感到困惑。您将 JFrame 的布局设置为 GridLayout,它需要 3 行和 4 列(总共 12 个组件),但您只向 JFrame 添加 一个 组件,"panel" J面板。我不确定您要做什么,因此在这种情况下很难给出建议。

例如,您可以像这样创建一个 class:

public class GetUrlPanel extends JPanel {
    private static final String PROMPT = "Welcome Please Enter URL to Begin!";
    private JTextField urlField = new JTextField(10);
    private JButton goToUrlButton = new JButton("Go To URL");

    public GetUrlPanel() {
        add(new JLabel(PROMPT));
        add(urlField);
        add(goToUrlButton);
    }

    public String getUrlFieldText() {
        return urlField.getText();
    }

    public void addGoToUrlListener(ActionListener listener) {
        goToUrlButton.addActionListener(listener);
    }
}

这将允许外部 classes 在需要的地方显示此 JPanel,将允许他们决定按下按钮时要做什么,并允许他们提取 JTextField 的内容。

另一种选择是更简单地从 JOptionPane 中获取 URL,例如:

public static void main(String[] args) {
    if (!Desktop.isDesktopSupported()) {
        System.err.println("Desktop is not supported. Exiting");
        System.exit(1);
    }
    String message = "Welcome Please Enter URL to Begin!";
    String title = "Enter URL";
    int messageType = JOptionPane.PLAIN_MESSAGE;
    String url = JOptionPane.showInputDialog(null, message, title, messageType);
    if (url == null) {
        System.err.println("Cancelled by user");
        System.exit(0);
    } else if (url.trim().isEmpty()) {
        System.err.println("You must enter a URL. Exiting");
        System.exit(2);
    }


    URI uri = null;
    try {
        uri = new URI(url);
        Desktop desktop = Desktop.getDesktop();
        desktop.browse(uri);
    } catch (URISyntaxException | IOException e) {
        String text = "Invalid URL \"" + url + "\". Exiting";
        System.err.println(text);
        e.printStackTrace();            
    }
}

有很多方法可以给这只猫剥皮,但如果在回答这个问题时我想强调一件事,那就是:

在做任何其他事情之前,您需要研究和学习 OOPS 概念和技术。