【问题标题】:Java GUI Input Dialogs are showing up twiceJava GUI 输入对话框出现两次
【发布时间】:2016-01-16 18:36:04
【问题描述】:

我有一个课堂作业,我用 Java 制作了一个带有 GUI 的简单会计程序。这是我第一次在 Java 中使用 GUI,而且我不是一个优秀的程序员。

当程序运行时,用户可以选择五个 JButton,单击这些按钮会将它们带到一个带有一些输入对话框的新 JFrame,这些对话框保存为字符串和双精度。 我的变量设置为类似

变量 = JOptionPane.showInputDialog("TEXTGOESHERE");

我的问题是,在对话框中输入值后,它们会再次弹出,就像在循环中一样。用户必须在每个对话框中输入两次。

其中一个按钮的代码:

pcButton.addActionListener(new ActionListener() 
{
  public void actionPerformed(ActionEvent e)
  {

    JFrame pcframe = new JFrame("Choosing a File Menu");
    pcframe.setSize(760,500);
         pcframe.add( new JPanel() 
         {
           public void paintComponent( Graphics g ) 
            {
              super.paintComponent(g);
              //ACTION BEGIN-----------------------------------------

出现两次的输入对话框:

              compName = JOptionPane.showInputDialog("What is the name of your business?");
              firstName = JOptionPane.showInputDialog("What is your first name?");
              lastName = JOptionPane.showInputDialog("What is your last name?");

              day = JOptionPane.showInputDialog("What is the day?");
              month = JOptionPane.showInputDialog("What is the month?");
              year = JOptionPane.showInputDialog("What is the year?");

              String filename = JOptionPane.showInputDialog("Would you like file 1, 2, or 3? (Type in 1, 2, or 3");

              filename = (filename + ".txt");

              //Storing File into array

              //Calculations

              g.drawString("" + compName, 330, 15);
              //More drawStrings


              //ACTION END-------------------------------------------
            }
         });
        pcframe.setVisible( true );

  }
});
modePanel.add(pcButton);

当按下 pcButton 时,用户应该输入他们的姓名、文件等。但是,每个对话框输入都会显示两次。我希望输入只显示一次。

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: java swing user-interface joptionpane


    【解决方案1】:

    对不起,那完全错了。您应该永远不要调用 JOptionPanes 或在paintComponent 方法中进行绘画以外的任何操作。您永远无法完全控制何时甚至是否调用该方法,并且您的程序感知到的响应能力部分取决于该方法完成其工作的速度。所以我的主要建议 - 将所有非绘画代码从该方法中取出并放入一个您可以完全控制的方法中。

    我自己,而不是向用户扔一堆 JOptionPanes,我会创建一个 JPanel,其中包含我希望用户填写的所有字段,然后显示一个包含该 JPanel 的单个 JOptionPane,并获取所有一次输入。

    接下来,您的辅助对话框窗口应该是一个真正的对话框,对于 Swing,这意味着 JDialog(或 JOptionPane,它是一种模态 JDialog)而不是 JFrame。

    【讨论】:

    • 谢谢!我已经为对话框制作了一个方法,现在它可以工作了。非常感谢您的帮助。
    猜你喜欢
    • 2021-12-25
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多