【问题标题】:Multiple JFrames in One Application一个应用程序中的多个 JFrame
【发布时间】:2014-12-23 01:50:43
【问题描述】:

我还在学习 Java 的 Swing 包,我正在制作一个应用程序来跟踪一个人购买/吃过多少星冰乐。我遇到了一个巨大的错误。

应用程序中有一个按钮,单击该按钮将打开另一个 JFrame,其作用类似于 JavaScript 的 prompt() 命令。我知道这可以自己工作,在添加主 JFrame 之前,这在代码中调用时效果很好。

但是当我尝试单击按钮创建第二个 JFrame 时,整个应用程序冻结并继续使用我 50% 的 RAM。发生这种情况时,我无法关闭程序,必须使用任务管理器结束它。

这是我的代码...

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.nio.file.*;

class Frappucinos{
    //initialize the main window
    public static JFrame window;

    // initializing values for ask()
    private static String inValue;
    private static boolean askPush = false;
    // popup asking box, like JavaScript's prompt()
    private static String ask(String message){
        // setup frame
        JFrame askPane = new JFrame("Frappucinos");
        askPane.setLayout(null);
        askPane.setBounds(150, 100, 300, 200);
        // setup question label
        JLabel askText = new JLabel(
            message,
            SwingConstants.CENTER
        );
        askText.setBounds(0, 25, 300, 25);
        // setup input field
        JTextField askType = new JTextField(25);
        askType.setBounds(50, 75, 200, 25);
        // setup button
        JButton askButn = new JButton("Submit");
        askButn.setBounds(100, 125, 100, 25);
        // add elements to frame
        askPane.add(askText);
        askPane.add(askType);
        askPane.add(askButn);
        // make buttons click event
        askButn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                // set variable to content of the textfield
                inValue = askType.getText();
                // tell program button has been pushed
                askPush = true;
                //hide window
                askPane.setVisible(false);
            }
        });
        // set size of window and make it visible
        askPane.setMinimumSize(new Dimension(300, 200));
        askPane.setPreferredSize(new Dimension(300, 200));
        askPane.setMaximumSize(new Dimension(300, 200));
        askPane.setLocationRelativeTo(null);
        askPane.setVisible(true);
        // tell program button hasn't been pushed yet
        askPush = false;
        // suspend program until button is pushed
        // i know, this is not a very good way of doing it...
        while(!askPush){}
        // return the value
        return inValue;
    }

    // initializing frapp eating variables
    public static String obtaining;
    public static String eating;
    public static Integer obtained;
    public static Float eaten;
    public static String buyAmount;
    public static String eatAmount;
    public static Integer eatInt;

    // writing to files
    public static void fileWrite(String fPath, String fContent){
        FileOutputStream fileOut;
        try{
            fileOut = new FileOutputStream(fPath);
            new PrintStream(fileOut).println(fContent);
            fileOut.close();
        }catch(IOException e){
            System.out.println(" Unable to write to file " + fPath);
            System.exit(0);
        }
    }

    public static void main(String[] args){
        // set file path
        Path file = Paths.get("bought.txt");
        try{
            // create the file
            Files.createFile(file);
        // if it already exists
        }catch(FileAlreadyExistsException x){
            System.out.println(" File bought.txt already exists");
        }catch(IOException x){
        // if theres an error
            System.out.println(" Error making file bought.txt:");
            System.out.println(x);
        }
        // make an input stream
        FileInputStream fileIn;
        try{
            // the input file stream ready
            fileIn = new FileInputStream("bought.txt");
            // read a line
            obtaining = new DataInputStream(fileIn).readLine();
            // if line is blank
            if(obtaining == null){
                // make variable 0
                obtaining = "0";
            }
            // close the file
            fileIn.close();
        // errors
        }catch(IOException e){
            System.out.println(" Unable to read from file bought.txt");
            // make variable 0
            obtaining = "0";
        }
        // set file path
        file = Paths.get("eaten.txt");
        try{
            // make the file
            Files.createFile(file);
        // if already there
        }catch(FileAlreadyExistsException x){
            System.out.println(" File eaten.txt already exists.");
        // if errors
        }catch(IOException x){
            System.out.println(" Error making file eaten.txt:");
            System.out.println(x);
        }
        try{
            // set file input stream to new file
            fileIn = new FileInputStream("eaten.txt");
            // set variable to line in file
            eating = new DataInputStream(fileIn).readLine();
            // if blank then make it 0.0
            if(eating == null){
                eating = "0.0";
            }
            // close that file
            fileIn.close();
        // if theres an error
        }catch(IOException e){
            // do the same stuff as all the other ones did...
            System.out.println(" Unable to read from file eaten.txt");
            eating = "0";
        }
        obtained = Integer.valueOf(obtaining);
        eaten = Float.parseFloat(eating);

        window = new JFrame("Frappucinos");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton buyFrapp = new JButton("Bought a Frapp");
        JButton eatFrapp = new JButton("Drank some Frapp");
        JLabel frappDet = new JLabel("Loading...", SwingConstants.CENTER);
        window.setLayout(null);
        window.setBounds(    0,  0, 600, 500);
        buyFrapp.setBounds( 25, 25, 100,  25);
        eatFrapp.setBounds(475, 25, 100,  25);
        frappDet.setBounds(  0, 75, 600, 425);
        buyFrapp.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                buyAmount = ask("How many frappucinos have you bought?");
                obtained = obtained + Integer.parseInt(buyAmount);
                fileWrite("bought.txt", "" + obtained);
            }
        });
        eatFrapp.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                eatAmount = ask("What percentage of a frappucino have you eaten (without % sign)");
                eatInt = Integer.parseInt(eatAmount);
                if(eatInt > 99){
                    eaten = eaten + Float.parseFloat("" + eatInt / 100 + "." + (eatInt - ((eatInt / 100) * 100)));
                }else if(eatInt > 9){
                    eaten = eaten + Float.parseFloat("0.0" + eatAmount);
                }else{
                    eaten = eaten + Float.parseFloat("0." + eatAmount);
                }
                fileWrite("eaten.txt", "" + eaten);
            }
        });
        window.add(buyFrapp);
        window.add(eatFrapp);
        window.add(frappDet);
        window.setLocationRelativeTo(null);
        window.setVisible(true);
    }
}

我添加了整个代码,因为我知道添加一小部分代码有时可能不会包含它的重要功能。

为了澄清,我需要做的是在单击按钮时出现新的 JFrame。但真正发生的是应用程序冻结并开始使用我 50% 的 RAM。

如果需要任何额外的细节或说明,请随时发布,我会在看到后立即回复。

是的,我在很多地方都做过研究,包括 Stack Overflow,但我没有看到任何帮助,而且我不想要 JInternalFrame。

【问题讨论】:

  • 避免使用null 布局,像素完美的布局是现代用户界面设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 Swing 旨在与核心布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正
  • Concurrency in Swing - 这基本上就是 HovercraftFullOfEels 所说的
  • “我知道这可以自己工作” - 这实际上是一个侥幸,可能归结为您在事件调度线程上下文之外调用了这个方法.另一方面,该按钮在 EDT 中运行,这就是它不再起作用的原因
  • 我要指出为什么它似乎比你更有效。

标签: java swing jframe


【解决方案1】:

这里:

    // suspend program until button is pushed
    // i know, **this is not a very good way of doing it...** (emphasis mine)
    while(!askPush){}

如您所知,这是"is not a very good way of doing it..."。这不仅不是一个很好的方式,而且是一种糟糕的方式,会冻结你的 Swing 事件线程,而不是应该如何进行事件驱动编程。根本不要这样做。

您想要使用的是模态对话框,例如 JOptionPane 或模态 JDialog。这将在请求时冻结您的调用代码,而不冻结 Swing 事件线程。一旦对话框不再可见,调用代码将恢复。

其他问题:

  • 您的程序只不过是一大堆静态字段和方法,没有具有状态和行为的真正类。就好像您试图将控制台程序推入事件驱动程序一样。不要这样做。相反,首先提取将需要的非 GUI 对象并为它们创建类。然后创建一个具有真正非静态方法和字段的 GUI,并使用非 GUI 对象作为其“模型”。
  • 模式对话框示例:

【讨论】:

  • 通过使用 JDialog,我是否能够摆脱整个 ask() 方法?
  • @user3928546:它将取代它。
  • @user3928546:请查看添加到答案的链接。
  • 谢谢,我用过JInputDialog,程序运行正常!我会投票,但我需要达到 15 级。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
相关资源
最近更新 更多