繁体   English   中英

Java GUI按钮不起作用

[英]java gui buttons not working

单击此代码中的清除和退出按钮不会执行任何操作。我做错了什么?

public class VehicleMenu extends JFrame implements ActionListener{

private static final long serialVersionUID = 1L;
private static final String FILE_NAME = "BB_Automobil's_Inventory Record.txt";
private JTextField jtfCode, jtfBrand, jtfEngineNumber, jtfEngineType, jtfMaxHorsepower, jtfRangePerFillUp, jtfPrice, jtfResult;
private JButton calculateButton, saveButton, clearButton, exitButton;
private JComboBox typeCombo;
private JPanel comboPanel, buttonPanel;
private String[] type = {"Sports Car","Hybrid Car"};


private Container windowContainer;

private JMenuItem jmiSearch, jmiUpdate, jmiDelete, jmiClose;



public VehicleMenu (int w, int h){

    //Set window size and title
    this.setSize(w, h);
    this.setTitle("BB Automobile's Inventory Record");

    //create menu bar
    JMenuBar jmb = new JMenuBar();

    //add menu "Exit" to menu bar
    JMenu optionsMenu = new JMenu("Options");
    optionsMenu.setMnemonic('O');
    jmb.add(optionsMenu);

    //add menu "Exit" to menu bar
    JMenu exitMenu = new JMenu("Exit");
    exitMenu.setMnemonic('E');
    jmb.add(exitMenu);

    //add menu items
    optionsMenu.add(jmiSearch=new JMenuItem("Search",'S'));
    optionsMenu.add(jmiUpdate=new JMenuItem("Update",'U'));
    optionsMenu.add(jmiDelete = new JMenuItem("Delete",'D'));
    exitMenu.add(jmiClose = new JMenuItem("Close",'C'));

    //Create textfields
    jtfCode = new JTextField(10);
    jtfBrand = new JTextField(10);
    jtfEngineType = new JTextField(10);
    jtfPrice = new JTextField(10);

    //Create buttons
    calculateButton = new JButton("Calculate");
    saveButton = new JButton("Save");
    clearButton = new JButton("Clear");
    exitButton = new JButton("Exit");
    //exitButton.setToolTipText("Out of Program");

    //Attach listeners to the buttons
    calculateButton.addActionListener(this);
    saveButton.addActionListener(this);
    clearButton.addActionListener(this);
    exitButton.addActionListener(this);

    //Create combobox
    typeCombo = new JComboBox(type);

    //Attach listeners to the comboboxes
    typeCombo.addActionListener(this);

    //attach ActionListener to menu item
    jmiClose.addActionListener(this);

    //Create panels
    comboPanel=new JPanel();
    buttonPanel = new JPanel();

    //Get contentPane and set its layout
    windowContainer = getContentPane();

    //add menu bar to the frame
    windowContainer.add(jmb,BorderLayout.NORTH);


    //to create topPanel with label and text field
    JPanel topPanel = new JPanel();
    topPanel.setLayout(new GridLayout(9,2,10,5));
    //Create combobox
    topPanel.add(new JLabel("Type:"));
    topPanel.add(typeCombo = new JComboBox(type));
    topPanel.add(new JLabel("Code:"));
    topPanel.add(jtfCode = new JTextField(3));
    topPanel.add(new JLabel("Brand:"));
    topPanel.add(jtfBrand = new JTextField(3));
    topPanel.add(new JLabel("Engine Number:"));
    topPanel.add(jtfEngineNumber = new JTextField(3));
    topPanel.add(new JLabel("Engine Type:"));
    topPanel.add(jtfEngineType = new JTextField(3));
    topPanel.add(new JLabel("Maximum horse power(Sports Car):"));
    topPanel.add(jtfMaxHorsepower = new JTextField(3));
    topPanel.add(new JLabel("Range per fill up(Hybrid Car):"));
    topPanel.add(jtfRangePerFillUp = new JTextField(3));
    topPanel.add(new JLabel("Price: RM"));
    topPanel.add(jtfPrice = new JTextField(3));
    topPanel.add(new JLabel("Discount: RM"));
    topPanel.add(jtfResult = new JTextField(3));
    jtfResult.setEditable(false);

    //to create bottom panel with buttons
    JPanel bottomPanel = new JPanel();

    bottomPanel.setLayout(new FlowLayout());
    bottomPanel.add(calculateButton = new JButton("Calculate"));
    bottomPanel.add(saveButton = new JButton("Save"));
    bottomPanel.add(clearButton = new JButton("Clear"));
    bottomPanel.add(exitButton = new JButton("Exit"));

    //ADD topPanel, middlePanel and bottomPanel to the frame
    windowContainer.add(topPanel,BorderLayout.CENTER);

    windowContainer.add(bottomPanel,BorderLayout.SOUTH);

    //Add buttons to buttonPanel
    buttonPanel.add(calculateButton);
    buttonPanel.add(saveButton);
    buttonPanel.add(clearButton);
    buttonPanel.add(exitButton);


    //Add panels to content panel

    this.add(buttonPanel, BorderLayout.SOUTH);

}//end constructor



public void actionPerformed(ActionEvent ae) {

    typeCombo.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent arg0) {
                            if (typeCombo.getSelectedItem().toString()
                            .equalsIgnoreCase("Sports Car")) {
                                jtfMaxHorsepower.setVisible(true);
                                jtfRangePerFillUp.setVisible(false);
                            } else {
                                jtfMaxHorsepower.setVisible(false);
                                jtfRangePerFillUp.setVisible(true);
                            }

                        }
                    });

    //declare Clicked to make JButton can move
    //JButton Clicked = (JButton) ae.getSource();

    //assign value from JTextField to new variable to link all the data members to GUI
    String typeM = typeCombo.getName();
    String codeM = jtfCode.getText();
    String brandM = jtfBrand.getText();
    String engineNumberM = jtfEngineNumber.getText();
    String engineTypeM = jtfEngineType.getText();


    //Invoke the composition into GUI with data members
    Engine eng = new Engine(engineNumberM,engineTypeM);
    double priceM = 0;
    //Invoke the superclass into GUI with their data members
    Car car = new Car(eng,priceM,codeM,brandM);
    double maxHorsepowerM = 0;
    //Invoke the subclasses into GUI together with their data members
    SportsCar sportsCar = new SportsCar(maxHorsepowerM,eng,priceM);
    double rangePerFillUpM = 0;
    HybridCar hybridCar = new HybridCar(rangePerFillUpM,eng,priceM);


        if(ae.getSource() == saveButton) {
            try
            {

                if(car.getEngine().equals("") || car.getPrice()==0.0
                || eng.getEngineNumber().equals("")|| eng.getEngineType().equals("")
                || (sportsCar.getMaxHorsepower()==0.0 || hybridCar.getRangePerFillUp()==0.0))
                {
                    //exception for empty field
                    JOptionPane.showMessageDialog(null,"Inserting data is incomplete. Please fully insert the data",
                    "Wrong input", JOptionPane.WARNING_MESSAGE);
                }
                //SAVE the data into text file
                else 
                {
                    String typeN = typeM.trim();

                    String engineNumberN = eng.getEngineNumber().trim();
                    String engineTypeN = eng.getEngineType().trim();
                    double maxHorsepowerN = sportsCar.getMaxHorsepower();
                    double rangePerFillUpN = hybridCar.getRangePerFillUp();
                    double priceN = car.getPrice();



                    //declaring object to write data to file
                    CustomFileWriter fw = new CustomFileWriter();

                    //either fill maxHorsepower(SportsCar) or rangePerFillUp(HybridCar)
                    if(maxHorsepowerM != 0.0) 
                    {
                        String input = typeN +", "+ codeM +", "+ brandM +", "+ engineNumberN +", "
                                    + engineTypeN +", "+ maxHorsepowerN +", "+ priceN;
                         fw.writeToFile(FILE_NAME, sportsCar, true);
                    }
                    else if(rangePerFillUpM != 0.0)
                    {
                          String input = typeN +", "+ codeM +", "+ brandM +", "+ engineNumberN +", "
                                    + engineTypeN +", "+ rangePerFillUpN +", "+ priceN;
                          fw.writeToFile(FILE_NAME, hybridCar, true);
                    }
                }

                } //end else if AND try for SAVE


                catch (Exception e1)
                {
                    e1.printStackTrace();
                }



            }// end if SAVE


        {
        //to reset the input in the textfield
         if(ae.getSource() == clearButton)
        {  
            jtfCode.setText(""); 
            jtfBrand.setText(""); 
            jtfEngineNumber.setText("");
            jtfEngineType.setText("");
            jtfMaxHorsepower.setText("");
            jtfRangePerFillUp.setText("");
            jtfPrice.setText(""); 
        }

        else if(ae.getSource() == exitButton)
        {  System.exit(0); }


        else if(ae.getSource()== jmiClose)
            { System.exit(0);}
        }


        {    
    //DELETE
  if(ae.getSource() == jmiDelete)
          {
            //open file to DELETE saved data
            PrintWriter pw;
            try {
                pw = new PrintWriter(FILE_NAME);
                pw.print("");
                pw.close();
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }

            JOptionPane.showMessageDialog(null,
                        "Successfully delete content from BB's_Automobile_Inventory_Record.txt",
                        "Delete from file", JOptionPane.INFORMATION_MESSAGE);
          }
          }

按钮创建完成,动作监听器在那里,是actionPerformed吗? 请帮助我,这非常令人困惑。

好吧,您在此块中声明并创建按钮:

//Create buttons
calculateButton = new JButton("Calculate");
saveButton = new JButton("Save");
clearButton = new JButton("Clear");
exitButton = new JButton("Exit");

然后将these按钮添加到动作侦听器中,但是在此块中,您将创建新按钮,这些按钮是可见的。

//to create bottom panel with buttons
JPanel bottomPanel = new JPanel();

bottomPanel.setLayout(new FlowLayout());
bottomPanel.add(calculateButton = new JButton("Calculate"));
bottomPanel.add(saveButton = new JButton("Save"));
bottomPanel.add(clearButton = new JButton("Clear"));
bottomPanel.add(exitButton = new JButton("Exit"));

只需将其更改为此,就可以了:

JPanel bottomPanel = new JPanel();

bottomPanel.setLayout(new FlowLayout());
bottomPanel.add(calculateButton );
bottomPanel.add(saveButton )
bottomPanel.add(clearButton );
bottomPanel.add(exitButton);

但是,为了使代码更具可读性,您应该使用匿名侦听器(有人已经在注释中提到了它)。 所以代替这个:

calculateButton.addActionListener(this);

对每个按钮使用类似这样的东西:

calculateButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        //Your code
    }
});

希望这可以帮助 (:

暂无
暂无

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

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