简体   繁体   English

JButton开启新的JFrame?

[英]JButton opening new JFrame?

I have been looking for multiple ways to open a JFrame with a button. 我一直在寻找多种方法来打开带有按钮的JFrame。 One of the ways I found was to establish the JFrame with a method and call upon that method with the button. 我找到的方法之一是使用方法建立JFrame并使用按钮调用该方法。 That however does not seem to be working with my program. 然而,这似乎与我的计划无关。 Could someone please tell me what I am doing wrong? 有人可以告诉我我做错了什么吗? I am pretty new to Java and am trying to learn on my own and seem to be doing a pretty terrible job of it. 我是Java的新手,我正在努力学习,并且似乎做得非常糟糕。 I am trying to create a Catalog and at the bottom of it have a button called "Make a New Purchase" which will open a new JFrame that will allow someone to enter their information. 我正在尝试创建一个目录,并在其底部有一个名为“新建购买”的按钮,该按钮将打开一个允许某人输入其信息的新JFrame。 Much of the code in the program is unnecessary and I will edit it later, such as the multiple JPanels. 程序中的大部分代码都是不必要的,我稍后会编辑它,例如多个JPanel。 All I need to do is get the new JFrame to come up with the button click. 我需要做的就是让新的JFrame来点击按钮。 The showNewFrame() method is what I am trying to have activated by the button press. showNewFrame()方法是我试图按下按钮激活的方法。

public class Catalog extends JFrame
{
//Construct a panel for each row

    JPanel firstRow = new JPanel();


    JPanel secondRow = new JPanel();
    JPanel thirdRow = new JPanel();
    JPanel fourthRow = new JPanel();
    JPanel fifthRow = new JPanel();
    JPanel sixthRow = new JPanel();
    JPanel seventhRow = new JPanel();
    JPanel eighthRow = new JPanel();
    JPanel ninthRow = new JPanel();
    JPanel tenthRow = new JPanel();
    JPanel eleventhRow = new JPanel();
    JPanel twelvethRow = new JPanel();
    JPanel thirteenthRow = new JPanel();
    JPanel fourteenthRow = new JPanel();
    JPanel fifteenthRow = new JPanel();
    JPanel sixteenthRow = new JPanel();
    JPanel seventeenthRow = new JPanel();
    JPanel eighteenthRow = new JPanel();
    JPanel nineteenthRow = new JPanel();
    JPanel twentiethRow = new JPanel();
    JPanel twentyfirstRow = new JPanel();
    JPanel twentysecondRow = new JPanel();
    JPanel twentythirdRow = new JPanel();
    JPanel twentyfourthRow = new JPanel();

    //Construct a panel for the fields and buttons
    JPanel fieldPanel = new JPanel();
    JPanel buttonPanel = new JPanel();

    //Construct labels and text boxes
    JLabel coatOneLabel = new JLabel("Coat One");
    ImageIcon pictureOne = new ImageIcon("C:\\Users\\p6\\Desktop\\prodImage.jpeg");
    JLabel picLabelOne = new JLabel(pictureOne);
    JLabel priceOneLabel = new JLabel("Price:");
    JLabel coatTwoLabel = new JLabel("Coat Two");
    ImageIcon pictureTwo = new ImageIcon("snow.png");
    JLabel picLabelTwo = new JLabel(pictureTwo);
    JLabel priceTwoLabel = new JLabel("Price:");
    JLabel coatThreeLabel = new JLabel("Coat Three");
    ImageIcon pictureThree = new ImageIcon("snow.png");
    JLabel picLabelThree = new JLabel(pictureThree);
    JLabel priceThreeLabel = new JLabel("Price:");
    JLabel coatFourLabel = new JLabel("Coat Four");
    ImageIcon pictureFour = new ImageIcon("snow.png");
    JLabel picLabelFour = new JLabel(pictureFour);
    JLabel priceFourLabel = new JLabel("Price:");
    JLabel coatFiveLabel = new JLabel("Coat Five");
    ImageIcon pictureFive = new ImageIcon("snow.png");
    JLabel picLabelFive = new JLabel(pictureFive);
    JLabel priceFiveLabel = new JLabel("Price:");
    JLabel coatSixLabel = new JLabel("Coat Six");
    ImageIcon pictureSix = new ImageIcon("snow.png");
    JLabel picLabelSix = new JLabel(pictureSix);
    JLabel priceSixLabel = new JLabel("Price:");
    JLabel coatSevenLabel = new JLabel("Coat Seven");
    ImageIcon pictureSeven = new ImageIcon("snow.png");
    JLabel picLabelSeven = new JLabel(pictureSeven);
    JLabel priceSevenLabel = new JLabel("Price:");
    JLabel coatEightLabel = new JLabel("Coat Eight");
    ImageIcon pictureEight = new ImageIcon("snow.png");
    JLabel picLabelEight = new JLabel(pictureEight);
    JLabel priceEightLabel = new JLabel("Price:");

    //Construct buttons
    JButton submitButton = new JButton("Make A Purchase");
    JButton exitButton = new JButton("Not Right Now");

    public static void main(String[] args)
    {
        //set the look and feel of the interface
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null,"The UIManager could not set the Look and Feel for this application.","Error",JOptionPane.INFORMATION_MESSAGE);
        }

        Catalog f = new Catalog();
        f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        f.setSize(800,600);
        f.setTitle("Coat Catalog");
        f.setResizable(false);
        f.setLocation(200,200);
        f.setVisible(true);
    }

    public Catalog()
    {
        Container c = getContentPane();
        c.setLayout((new BorderLayout()));
        fieldPanel.setLayout(new GridLayout(20,10));
        FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,5,3);
            firstRow.setLayout(rowSetup);
            secondRow.setLayout(rowSetup);
            thirdRow.setLayout(rowSetup);
            fourthRow.setLayout(rowSetup);
            fifthRow.setLayout(rowSetup);
            sixthRow.setLayout(rowSetup);
            seventhRow.setLayout(rowSetup);
            eighthRow.setLayout(rowSetup);
            ninthRow.setLayout(rowSetup);
            tenthRow.setLayout(rowSetup);
            eleventhRow.setLayout(rowSetup);
            twelvethRow.setLayout(rowSetup);
            thirteenthRow.setLayout(rowSetup);
            fourteenthRow.setLayout(rowSetup);
            fifteenthRow.setLayout(rowSetup);
            sixteenthRow.setLayout(rowSetup);
            seventeenthRow.setLayout(rowSetup);
            eighteenthRow.setLayout(rowSetup);
            nineteenthRow.setLayout(rowSetup);
            twentiethRow.setLayout(rowSetup);
            twentyfirstRow.setLayout(rowSetup);
            twentysecondRow.setLayout(rowSetup);
            twentythirdRow.setLayout(rowSetup);
            twentyfourthRow.setLayout(rowSetup);
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

        //Add fields to rows
        firstRow.add(coatOneLabel);
        firstRow.add(coatTwoLabel);

        secondRow.add(picLabelOne);
        secondRow.add(picLabelTwo);

        thirdRow.add(priceOneLabel);
        thirdRow.add(priceTwoLabel);

        fourthRow.add(coatThreeLabel);
        fourthRow.add(coatFourLabel);

        fifthRow.add(picLabelThree);
        fifthRow.add(picLabelFour);

        sixthRow.add(priceThreeLabel);
        sixthRow.add(priceFourLabel);

        seventhRow.add(coatFiveLabel);
        seventhRow.add(coatSixLabel);

        eighthRow.add(picLabelFive);
        eighthRow.add(picLabelSix);

        ninthRow.add(priceFiveLabel);
        ninthRow.add(priceSixLabel);

        tenthRow.add(coatSevenLabel);
        tenthRow.add(coatEightLabel);

        eleventhRow.add(picLabelSeven);
        eleventhRow.add(picLabelEight);

        twelvethRow.add(priceSevenLabel);
        twelvethRow.add(priceEightLabel);

        //Add rows to panel
        fieldPanel.add(firstRow);
        fieldPanel.add(secondRow);
        fieldPanel.add(thirdRow);
        fieldPanel.add(fourthRow);
        fieldPanel.add(fifthRow);
        fieldPanel.add(sixthRow);
        fieldPanel.add(seventhRow);
        fieldPanel.add(eighthRow);
        fieldPanel.add(ninthRow);
        fieldPanel.add(tenthRow);
        fieldPanel.add(eleventhRow);
        fieldPanel.add(twelvethRow);
        fieldPanel.add(thirteenthRow);
        fieldPanel.add(fourteenthRow);
        fieldPanel.add(fifteenthRow);
        fieldPanel.add(sixteenthRow);
        fieldPanel.add(seventeenthRow);
        fieldPanel.add(eighteenthRow);
        fieldPanel.add(nineteenthRow);
        fieldPanel.add(twentiethRow);
        fieldPanel.add(twentyfirstRow);
        fieldPanel.add(twentysecondRow);
        fieldPanel.add(twentythirdRow);
        fieldPanel.add(twentyfourthRow);


        //Add button to panel
        buttonPanel.add(submitButton);
        buttonPanel.add(exitButton);

        //Add panels to frame
        c.add(fieldPanel, BorderLayout.CENTER);
        c.add(buttonPanel, BorderLayout.SOUTH);

        exitButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent h)
            {
                if (h.getSource() == exitButton)
                {
                        System.exit(0);
                }
            }
        });

        //Add functionality to buttons
        submitButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent d)
            {
                if (d.getSource() == submitButton)
                {
                    showNewFrame();
                }
            }
        });
    }

    private void showNewFrame()
    {
        JFrame BillPayer = new JFrame("BillPayer");
        BillPayer.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        BillPayer.pack();
        BillPayer.setVisible(true);

        class BillPayer extends JFrame implements ActionListener
        {
            //Declare output stream
            DataOutputStream output;

            //Construct a panel for each row
            JPanel firstRow = new JPanel();
            JPanel secondRow = new JPanel();
            JPanel thirdRow = new JPanel();
            JPanel fourthRow = new JPanel();
            JPanel fifthRow = new JPanel();
            JPanel sixthRow = new JPanel();
            JPanel seventhRow = new JPanel();
            JPanel eighthRow = new JPanel();

            //Construct a panel for the fields and buttons
            JPanel fieldPanel = new JPanel();
            JPanel buttonPanel = new JPanel();

            //Construct labels and text boxes
            JLabel acctNumLabel = new JLabel("Account Number:                            ");
                JTextField acctNum = new JTextField(15);
            JLabel pmtLabel = new JLabel("Payment Amount:");
                JTextField pmt = new JTextField(10);
            JLabel firstNameLabel = new JLabel("First Name:         ");
                JTextField firstName = new JTextField(10);
            JLabel lastNameLabel = new JLabel("Last Name:");
                JTextField lastName = new JTextField(20);
            JLabel addressLabel = new JLabel("Address:");
                JTextField address = new JTextField(35);
            JLabel cityLabel = new JLabel("City:                   ");
                JTextField city = new JTextField(10);
            JLabel stateLabel = new JLabel("State:");
                JTextField state = new JTextField(2);
            JLabel zipLabel = new JLabel("Zip:");
                JTextField zip = new JTextField(9);

            //Construct button
            JButton submitButton = new JButton("Submit");

            public void main(String[] args)
            {
                //set the look and feel of the interface
                try
                {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

                }
                catch(Exception e)
                {
                    JOptionPane.showMessageDialog(null,"The UIManager could not set the Look and Feel for this application.","Error",JOptionPane.INFORMATION_MESSAGE);
                }

                BillPayer f = new BillPayer();
                f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                f.setSize(450,300);
                f.setTitle("Crandall Power and Light Customer Payments");
                f.setResizable(false);
                f.setLocation(200,200);
                f.setVisible(true);
            }

            public BillPayer()
            {
                Container c = getContentPane();
                c.setLayout((new BorderLayout()));
                fieldPanel.setLayout(new GridLayout(8,1));
                FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,5,3);
                    firstRow.setLayout(rowSetup);
                    secondRow.setLayout(rowSetup);
                    thirdRow.setLayout(rowSetup);
                    fourthRow.setLayout(rowSetup);
                    fifthRow.setLayout(rowSetup);
                    sixthRow.setLayout(rowSetup);
                    seventhRow.setLayout(rowSetup);
                    eighthRow.setLayout(rowSetup);
                buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

                //Add fields to rows
                firstRow.add(acctNumLabel);
                firstRow.add(pmtLabel);

                secondRow.add(acctNum);
                secondRow.add(pmt);

                thirdRow.add(firstNameLabel);
                thirdRow.add(lastNameLabel);


                fourthRow.add(firstName);
                fourthRow.add(lastName);

                fifthRow.add(addressLabel);

                sixthRow.add(address);

                seventhRow.add(cityLabel);
                seventhRow.add(stateLabel);
                seventhRow.add(zipLabel);

                eighthRow.add(city);
                eighthRow.add(state);
                eighthRow.add(zip);

                //Add rows to panel
                fieldPanel.add(firstRow);
                fieldPanel.add(secondRow);
                fieldPanel.add(thirdRow);
                fieldPanel.add(fourthRow);
                fieldPanel.add(fifthRow);
                fieldPanel.add(sixthRow);
                fieldPanel.add(seventhRow);
                fieldPanel.add(eighthRow);

                //Add button to panel
                buttonPanel.add(submitButton);

                //Add panels to frame
                c.add(fieldPanel, BorderLayout.CENTER);
                c.add(buttonPanel, BorderLayout.SOUTH);

                //Add functionality to buttons
                submitButton.addActionListener(this);

                //Get the current date and open the file
                Date today = new Date();
                SimpleDateFormat myFormat = new SimpleDateFormat("MMddyyyy");
                String filename = "payments" + myFormat.format(today);

                try
                {
                    output = new DataOutputStream(new FileOutputStream(filename));
                }
                catch(IOException io)
                {
                    JOptionPane.showMessageDialog(null,"The program could not create a storage location. Please check the disk drive and then run the program again.","Error",JOptionPane.INFORMATION_MESSAGE);

                    System.exit(1);
                }

                addWindowListener(
                    new WindowAdapter()
                    {
                        public void windowClosing(WindowEvent f)
                        {
                            int answer = JOptionPane.showConfirmDialog(null,"Are you sure you want to exit and submit the file?", "File Submission",JOptionPane.YES_NO_OPTION);
                            if (answer == JOptionPane.YES_OPTION)
                            System.exit(0);
                        }
                    }
                );
            }

            public void actionPerformed(ActionEvent f)
            {
                String arg = f.getActionCommand();

                if(checkFields())
                {
                    try
                    {
                        output.writeUTF(acctNum.getText());
                        output.writeUTF(pmt.getText());
                        output.writeUTF(firstName.getText());
                        output.writeUTF(lastName.getText());
                        output.writeUTF(address.getText());
                        output.writeUTF(city.getText());
                        output.writeUTF(state.getText());
                        output.writeUTF(zip.getText());

                        JOptionPane.showMessageDialog(null,"The payment information has been saved.","Submission successful",JOptionPane.INFORMATION_MESSAGE);
                    }
                    catch(IOException c)
                    {
                        System.exit(1);
                    }
                    clearFields();
                }
            }

            public boolean checkFields()
            {
                if ((acctNum.getText().compareTo("")<1)    ||
                    (pmt.getText().compareTo("")<1)        ||
                    (firstName.getText().compareTo("")<1)  ||
                    (lastName.getText().compareTo("")<1)   ||
                    (address.getText().compareTo("")<1)    ||
                    (city.getText().compareTo("")<1)       ||
                    (state.getText().compareTo("")<1)      ||
                    (zip.getText().compareTo("")<1))
                {
                    JOptionPane.showMessageDialog(null,"You must complete all fields.","Data Entry Error",JOptionPane.WARNING_MESSAGE);
                    return false;
                }
                else
                {
                    return true;
                }
            }

            public void clearFields()
            {
                //Clear fields and reset the focus
                acctNum.setText("");
                pmt.setText("");
                firstName.setText("");
                lastName.setText("");
                address.setText("");
                city.setText("");
                state.setText("");
                zip.setText("");
                acctNum.requestFocus();
            }
        }
    }
}

I tried to make quite a few changes to the program. 我试图对程序做一些改动。 The issue is that now the button does bring up a new window but the window doesn't include the data I need it to have. 问题是,现在按钮确实显示了一个新窗口,但窗口不包含我需要它的数据。 It has the title "Coat Payment", so I believe it is getting to everything but the inner class I have in the BillPayer method (the inner class is PaymentScreen). 它的标题是“Coat Payment”,所以我相信除了我在BillPayer方法中的内部类(内部类是PaymentScreen)之外,它已经到了所有东西。 Once again I believe that my ignorance is leading me astray. 我再次相信我的无知使我误入歧途。

    //Add functionality to buttons
    submitButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent d)
        {
            if (d.getSource() == submitButton)
            {
                BillPayer();
            }
        }
    });
}

private void BillPayer()
{
    JDialog PaymentScreen = new JDialog();
    PaymentScreen.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    PaymentScreen.setSize(900,600);
    PaymentScreen.setTitle("Coat Payment");
    PaymentScreen.setResizable(false);
    PaymentScreen.setLocation(200,200);
    PaymentScreen.setVisible(true);

    class PaymentScreen extends JDialog implements ActionListener
    {

Sorry, but that's some schizophrenic code. 对不起,但这是一些精神分裂症的代码。 Maybe I'm reading it wrong, but I see: 也许我读错了,但我明白了:

  • You create a JFrame variable called BillPayer, and set it visible. 您创建一个名为BillPayer的JFrame变量,并将其设置为可见。 It is a small empty JFrame and nothing else. 它是一个小的空JFrame,没有别的。
  • You then declare a separate BillPayer class , and don't display it, 然后,您声明一个单独的BillPayer ,并且显示它,
  • Except for in code within its (???) main method, a main method that is within a private inner class, which is (appropriately) never called. 除了在其(???)main方法中的代码之外,在私有内部类中的一个main方法,(适当地)从不调用。

Recommendations: 建议:

  • First and foremost, you probably really don't want to display another JFrame. 首先,您可能真的不想显示另一个JFrame。 Most applications should have only one main window, a JFrame. 大多数应用程序应该只有一个主窗口,一个JFrame。
  • If you need another window being displayed from a main window, then use a dialog such as a JDialog. 如果需要从主窗口显示另一个窗口,则使用对话框,例如JDialog。 This is fairly easy to do, and just like a JFrame involves creating a JPanel filled with your GUI, and then placing that JPanel into the JDialog and setting it visible. 这很容易做到,就像JFrame涉及创建一个填充了GUI的JPanel,然后将该JPanel放入JDialog并将其设置为可见。
  • If you use a JDialog, you can choose whether it is modal or not, whether it will freeze the underlying calling window when it is displayed or not. 如果你使用JDialog,你可以选择它是否是模态的,它是否会在显示时冻结底层调用窗口。
  • To display another window from a button press, be it a JFrame or a JDialog, you would call setVisible(true) on the window from within the button press's ActionListener actionPerformed method. 要从按下按钮显示另一个窗口,无论是JFrame还是JDialog,您都可以在按钮的ActionListener actionPerformed方法中调用窗口上的setVisible(true) It looks like you're doing this. 看起来你正在这样做。 Is anything showing at all? 有什么表现吗? Have you debugged the code to see if code you think is being reached is not being called? 您是否调试过代码以查看您认为正在访问的代码是否未被调用?
  • Or if you want to display another view inside of the main window, use a CardLayout. 或者,如果要在主窗口内显示另一个视图,请使用CardLayout。
  • Don't give your variables the exact same name, spelling and capitalization as your classes. 不要为变量提供与类完全相同的名称,拼写和大小写。
  • Learn and follow Java naming conventions: class names begin with an upper case letter and variable and method names with lower-case letters. 学习并遵循Java命名约定:类名以大写字母开头,变量和方法名称以小写字母开头。
  • Don't confuse your code by burying a main method inside of an inner private class. 不要通过在主内部类中嵌入main方法来混淆代码。 This makes little sense. 这没什么意义。
  • Study up on use of arrays and collections such as ArrayLists which can help you make programs that are much more compact, more readable, and easier to debug and extend. 研究使用数组和集合(如ArrayLists),它可以帮助您创建更紧凑,更易读,更易于调试和扩展的程序。 A lot of your code's redundancy can be reduced by doing this. 这样做可以减少很多代码的冗余。
  • If you have code for another GUI view that is distinct from the main view, perhaps this code should be in its own top-level class, and not an inner class. 如果您有另一个与主视图不同的GUI视图的代码,那么此代码可能位于其自己的顶级类中,而不是内部类。

Edit On review of your code some more, I suggest: 编辑在审核您的代码时,我建议:

  • Yes, use a JDialog for the data entry window. 是的,使用JDialog作为数据输入窗口。
  • The data would probably be best displayed in a JTable held in a JScrollPane in the main GUI. 数据可能最好显示在主GUI中的JScrollPane中保存的JTable中。 This would be in place of the rows of JPanels that your current code uses. 这将代替当前代码使用的JPanel行。

This is going to sound rough, but it's more time efficient. 这听起来很粗糙,但效率更高。

Select project > hit delete 选择项目>点击删除

Download Netbeans or Eclipse (or both) and program in these programs. 下载Netbeans或Eclipse(或两者)并在这些程序中编程。 They will help filter out mistakes you've made and provide a help with layout, so that it looks more comprehensible. 它们将有助于过滤掉您所犯的错误并提供布局帮助,使其看起来更易于理解。

Once that's done, follow these tutorials: 完成后,请按照以下教程操作:

http://docs.oracle.com/javase/tutorial/uiswing/start/index.html http://docs.oracle.com/javase/tutorial/uiswing/start/index.html

The answer above already gave a lot of valuable tips, but your problem is that you simply do not know anything yet on how to properly build a program. 上面的答案已经提供了很多有价值的提示,但问题是你根本不知道如何正确构建程序。

My tip: decide for yourself what would be awesome to make. 我的提示:自己决定做什么真棒。 Something you think is useful for yourself or others, then go through the tutorial and try to build it. 你认为对自己或他人有用的东西,然后通过教程并尝试构建它。 This forces you to not only implement what you learn as you go along, but also run into the real issue with any programmming language: learn how to solve problems. 这迫使你不仅要实现你学到的东西,还要用任何编程语言来解决真正的问题:学习如何解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM