Java Swing : Get text value from JOptionPane

标签 java swing joptionpane

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

这是我的代码:

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
}

有什么建议吗?

最佳答案

使用输入对话框获取用户输入

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 : Get text value from JOptionPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26613879/

相关文章:

java - 使用自定义 JOptionPane 按钮? int 延迟错误?

java - 谁处理由 java 中的组件创建的事件

java - 内容辅助在 Eclipse 中不起作用

java - 将资源文件捆绑到 ecs 集群上使用的 java app jar 文件中

java - 您如何组织 Java bean 属性名称?

java - 使用一个类创建并运行多个 Java 窗口

java - 创建一个带有 swing 布局的简单控制台

java - 检查用户输入插入的字符串是否对应于特定格式

java - 自定义 JOptionPane 对话框

java - android.os.Bundle 中 getInt(string key) 返回的整数是多少?