0

Hi though i did complete the basics of java which im fairly new of, i keep getting errors when i try to add buttons on a new Frame/Panel. Care to educate me on what the problem might be?

import javax.swing.*;
import java.awt.*;

class MainClass {
    String cont_orders;
    private JFrame frame1;
    private JPanel mainpanel;
    JButton bt1, bt2, bt3, bt4, bt5;
    private JButton btotal = new JButton("Order");
    private JButton clearOr = new JButton("Clear");
    private JTextField pricetotal = new JTextField();
    private JTextField list_of_orders = new JTextField();

public MainClass(){
    gui();
}

private void gui(){
    frame1 = new JFrame("Order");
    frame1.setSize(500,430);
    frame1.setVisible(true);
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame1.setResizable(false);

    mainpanel = new JPanel();
    mainpanel.setBackground(Color.BLUE);

    mainpanel.add(bt1);
        bt1 = new JButton("M-Item 1 [Soda]");  
    frame1.add(mainpanel,BorderLayout.CENTER);
}
public static void main (String[]args){
    new MainClass();
}

}

im trying to practice on coding normally instead of relying on that automatic one in NetBeans [JFrame Form/JPanel Form]

care to help?

Furvus
  • 3
  • 4
  • what are the errors? – Reimeus Aug 23 '17 at 14:40
  • Please post the stacktrace if you're getting an error, or a screenshot if you're getting a graphical issue. One thing I see is you never set the layout of your panel - there should be a default one anyway though – dustinroepsch Aug 23 '17 at 14:42
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Paul Aug 23 '17 at 14:42
  • The exception is - or at least thats my guess from the posted code - a NPE. Should be simple enough to solve with a debugger. – Paul Aug 23 '17 at 14:43
  • first you have to initialize the button,change to this one, bt1 = new JButton("M-Item 1 [Soda]"); mainpanel.add(bt1); it is working fine. – Balasubramanian Aug 23 '17 at 14:49

2 Answers2

1

Now this cannot be done in java

mainpanel.add(bt1);
bt1 = new JButton("M-Item 1 [Soda]");  

Turn it around.

Explanation: the field bt1 is at that time a variable holding the null object. That object (value) is added, not some variable address as in other languages.

Joop Eggen
  • 96,344
  • 7
  • 73
  • 121
1

Reverse it bt1 = new JButton("M-Item 1 [Soda]" mainpanel.add(bt1); Because if not the value of bt1 would be null so you must fill it first then use it . Or mainpanel.add(new JButton("..."));