Java GUI 输入对话框出现两次

Java GUI Input Dialogs are showing up twice

我有 class 的作业,我在 Java 中用 GUI 制作了一个简单的会计程序。这是我第一次在 Java 中使用 GUI,我不是一个很好的程序员。

当程序运行时,用户可以 select 五个 JButton,单击这些按钮会将它们带到带有一些输入对话框的新 JFrame,这些对话框另存为 String 和 Double。 我的变量设置为

variable = JOptionPane.showInputDialog("TEXTGOESHERE");

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

Code for one of the buttons:

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-----------------------------------------

The input dialogs which are showing up twice:

              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 时,用户应该输入他们的姓名、文件等。但是,每个对话框输入都会显示两次。我希望输入只显示一次。

非常感谢任何帮助,谢谢。

抱歉,那全错了。你应该 never 调用 JOptionPanes 或做除了从 paintComponent 方法中绘画以外的任何事情。您永远无法完全控制何时甚至是否调用该方法,并且您的程序的感知响应能力部分取决于该方法完成其工作的速度。所以我的主要建议 -- 将所有 non-painting 代码从该方法中取出并放入一个 您可以完全控制 的方法中。

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

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