gpt4 book ai didi

Java GUI 输入对话框出现两次

转载 作者:行者123 更新时间:2023-12-01 10:34:46 25 4
gpt4 key购买 nike

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

当程序运行时,用户可以选择五个 JButton,单击这些 JButton 会将它们带到带有一些输入对话框的新 JFrame,这些对话框保存为字符串和 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 时,用户应该输入他们的姓名、文件等。但是,每个对话框输入都会显示两次。我希望输入只显示一次。

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

最佳答案

抱歉,但那是错误的。您不应该永远调用 JOptionPanes 或执行除在 PaintComponent 方法中进行绘制以外的任何操作。您永远无法完全控制该方法何时或是否被调用,并且您的程序感知的响应能力部分取决于该方法完成其工作的速度。所以我的主要建议是——将所有非绘制代码从该方法中取出并放入您可以完全控制的方法中。

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

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

关于Java GUI 输入对话框出现两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34830637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com