Text Fields, Labels and Buttons

前端 未结 2 1005
忘了有多久
忘了有多久 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:18

    Wow... OK, first, ActionListener is spelled incorrectly as "ActionListner." Look very closely at the spelling of those words. Simple typographical errors generate syntax errors.

    The rest of your problems boil down to this very simple caveat: order matters. Your order should be as follows:

    1) declare and create objects; 2) declare and create all dependent objects; 3) configure objects; 4) manipulate objects.

    That means that your code:

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

    Won't work because you're trying to mess with a frame that hasn't yet been created. Create it first, like so:

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

    Same holds true for your label and your button.

    JLabel rictherlabel = new JLabel ("Ricther: ");
    

    needs to come before

    panel.add(label);
    

提交回复
热议问题