Text Fields, Labels and Buttons

前端 未结 2 978
忘了有多久
忘了有多久 2021-01-29 10:47

I am having some difficulty understanding GUIs and why my program won\'t run properly. Is it because I have to extend to a JFrame class? Here is a code:

import j         


        
2条回答
  •  情歌与酒
    2021-01-29 11:11

    Issue 1 :

     frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
     frame.setTitle("Richter Scale");
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setVisible(true); 
    
     JFrame frame = new JFrame();
    

    You are trying to use an object that is not yet created. frame object is created at a later point in time. It should be as below :

     JFrame frame = new JFrame();
     frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
     frame.setTitle("Richter Scale");
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setVisible(true); 
    

    Issue 2:

    Same issue further down the code. Brother, first you need to declare an object, then only you can use it and implement functions on it. If you are not declaring the object first, how would compiler parse it and treat it as a valid variable.

     panel.add(button);
     panel.add(label);
     panel.add(rictherfield);
     panel.add(rictherlabel);
     add(panel);
    
     JLabel rictherlabel = new JLabel ("Ricther: ");
    
     final int FIELD_WIDTH = 10;
     JTextField rictherField = new JTextField(FIELD_WIDTH);
     richterField.setText("" + EARTHQUAKE_RATE);
    
    
     JButton button = new JButton("Enter");
    

    'button', 'richterlabel' & 'richterField' are used before their declaration. As compiler does not know what dese variables mean at the time of execution, it throws up saying cannot find symbol.

    First declare them and then use them. Hope you got the point.

    Issue 3:

    import java.awt.event.ActionListner;
    

    ActionListner is not a class in the Event package. It should be :

    import java.awt.event.ActionListener;
    

    Looking for other issues, Meanwhile start working on this.

提交回复
热议问题