簡體   English   中英

JButton開啟新的JFrame?

[英]JButton opening new JFrame?

我一直在尋找多種方法來打開帶有按鈕的JFrame。 我找到的方法之一是使用方法建立JFrame並使用按鈕調用該方法。 然而,這似乎與我的計划無關。 有人可以告訴我我做錯了什么嗎? 我是Java的新手,我正在努力學習,並且似乎做得非常糟糕。 我正在嘗試創建一個目錄,並在其底部有一個名為“新建購買”的按鈕,該按鈕將打開一個允許某人輸入其信息的新JFrame。 程序中的大部分代碼都是不必要的,我稍后會編輯它,例如多個JPanel。 我需要做的就是讓新的JFrame來點擊按鈕。 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();
            }
        }
    }
}

我試圖對程序做一些改動。 問題是,現在按鈕確實顯示了一個新窗口,但窗口不包含我需要它的數據。 它的標題是“Coat Payment”,所以我相信除了我在BillPayer方法中的內部類(內部類是PaymentScreen)之外,它已經到了所有東西。 我再次相信我的無知使我誤入歧途。

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

對不起,但這是一些精神分裂症的代碼。 也許我讀錯了,但我明白了:

  • 您創建一個名為BillPayer的JFrame變量,並將其設置為可見。 它是一個小的空JFrame,沒有別的。
  • 然后,您聲明一個單獨的BillPayer ,並且顯示它,
  • 除了在其(???)main方法中的代碼之外,在私有內部類中的一個main方法,(適當地)從不調用。

建議:

  • 首先,您可能真的不想顯示另一個JFrame。 大多數應用程序應該只有一個主窗口,一個JFrame。
  • 如果需要從主窗口顯示另一個窗口,則使用對話框,例如JDialog。 這很容易做到,就像JFrame涉及創建一個填充了GUI的JPanel,然后將該JPanel放入JDialog並將其設置為可見。
  • 如果你使用JDialog,你可以選擇它是否是模態的,它是否會在顯示時凍結底層調用窗口。
  • 要從按下按鈕顯示另一個窗口,無論是JFrame還是JDialog,您都可以在按鈕的ActionListener actionPerformed方法中調用窗口上的setVisible(true) 看起來你正在這樣做。 有什么表現嗎? 您是否調試過代碼以查看您認為正在訪問的代碼是否未被調用?
  • 或者,如果要在主窗口內顯示另一個視圖,請使用CardLayout。
  • 不要為變量提供與類完全相同的名稱,拼寫和大小寫。
  • 學習並遵循Java命名約定:類名以大寫字母開頭,變量和方法名稱以小寫字母開頭。
  • 不要通過在主內部類中嵌入main方法來混淆代碼。 這沒什么意義。
  • 研究使用數組和集合(如ArrayLists),它可以幫助您創建更緊湊,更易讀,更易於調試和擴展的程序。 這樣做可以減少很多代碼的冗余。
  • 如果您有另一個與主視圖不同的GUI視圖的代碼,那么此代碼可能位於其自己的頂級類中,而不是內部類。

編輯在審核您的代碼時,我建議:

  • 是的,使用JDialog作為數據輸入窗口。
  • 數據可能最好顯示在主GUI中的JScrollPane中保存的JTable中。 這將代替當前代碼使用的JPanel行。

這聽起來很粗糙,但效率更高。

選擇項目>點擊刪除

下載Netbeans或Eclipse(或兩者)並在這些程序中編程。 它們將有助於過濾掉您所犯的錯誤並提供布局幫助,使其看起來更易於理解。

完成后,請按照以下教程操作:

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

上面的答案已經提供了很多有價值的提示,但問題是你根本不知道如何正確構建程序。

我的提示:自己決定做什么真棒。 你認為對自己或他人有用的東西,然后通過教程並嘗試構建它。 這迫使你不僅要實現你學到的東西,還要用任何編程語言來解決真正的問題:學習如何解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM