Java Swing:从JOptionPane获取文本值 [英] Java Swing: Get text value from JOptionPane

查看:96
本文介绍了Java Swing:从JOptionPane获取文本值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个用于POS系统的新窗口.用户输入用于客户拥有的金额,并且窗口必须显示兑换金额.我是JOptionPane功能的新手(我一直在使用JAVAFX,而且有所不同).

I'd like to create a new window which is used in POS system. The user input is for an amount of money the customer has and the window has to display the exchange amount. I'm new with JOptionPane feature (I have been using JAVAFX and it's different).

这是我的代码:

public static void main(String[] argv) throws Exception {
    String newline = System.getProperty("line.separator");
    int cost = 100;
    int amount = Integer.parseInt(JOptionPane.getText()) // this is wrong! This needs to come     from user input box in the same window.
    JFrame frame = new JFrame();
    String message = "Enter the amount of money"+newline+"The exchange money is: "+amount-cost;
    String text = JOptionPane.showInputDialog(frame, message);
    if (text == null) {
      // User clicked cancel
}

有什么建议吗?

推荐答案

使用InputDialog获取用户输入

use InputDialog for get userinput

public static void main(String[] argv) throws Exception {
      //JFrame frame = new JFrame();
      //frame.setVisible(true);
      int cost = 100;
      JLabel l=new JLabel("The exchange money is");

      JPanel p=new JPanel(new GridLayout(1, 2, 10, 10));
      p.setPreferredSize(new Dimension(400, 50));
      JTextField t=new JTextField("Enter the amount of money");
      t.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyReleased(java.awt.event.KeyEvent evt) {
            try{
            int amount=Integer.parseInt(t.getText());
            l.setText("The exchange money is: \n" + (amount - cost));
            }catch(Exception ex){
               // ex.printStackTrace();
            }
        }
      });
      p.add(t);
      p.add(l);

    int option = JOptionPane.showConfirmDialog(null,p,"JOptionPane Example : ",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
    if(option==0){
        System.out.println("ok clicked");
    }else{
        System.out.println("cancel clicked");
    }
}

这篇关于Java Swing:从JOptionPane获取文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆