Furvus Furvus - 27 days ago 10
Java Question

Frames and Buttons

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?

Answer Source

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.