Reputation: 187
I have a class that extends JFrame that has a menubar and menu Items inside of it. Under the menu bar I want to add a JPanel where I can add components and draw shapes.How would I add a JPanel inside of this class? Sorry if this is an easy question I am a beginner.
import java.awt.FlowLayout;
import javax.swing.*;
public class theMenu extends JFrame {
static JMenuBar menubar;
JMenu shape, color;
JCheckBox fill;
JButton btn1,btn2;
JMenuItem circle, rectangle, line,triangle;
JMenuItem red, green, blue, yellow;
public theMenu(){
super("Using JMenus");
menubar=new JMenuBar ();
shape=new JMenu ("Shape");
add(menubar);
setJMenuBar(menubar); // add menu bar to application
shape=new JMenu ("Shape");
color=new JMenu ("Color");
fill=new JCheckBox("fill");
btn1=new JButton("save");
btn2=new JButton("import");
circle=new JMenuItem ("Circle");
rectangle=new JMenuItem ("Rectangle");
line=new JMenuItem ("Line");
triangle = new JMenuItem ("Triangle");
red=new JMenuItem ("Red");
green=new JMenuItem ("Green");
blue=new JMenuItem ("Blue");
yellow=new JMenuItem ("Yellow");
shape.add (circle);
shape.add (rectangle);
shape.add (line);
shape.add (triangle);
color.add (red);
color.add (green);
color.add (blue);
color.add (yellow);
menubar.add (shape);
menubar.add(color);
menubar.add(fill);
menubar.add(btn1);
menubar.add(btn2);
}
}
Upvotes: 0
Views: 3992
Reputation: 140613
Simple:
Like:
JPanel p = new JPanel();
f.getContentPane().add(p);
For more information, start reading here.
Beyond that: you should first read about the difference between static and non-static fields. It is simply bad practice to have all static fields (shared between instances of your class); and to then use those as "normal" fields within your constructor.
In other words: you might want to study the basics of Java first, before writing Swing UI applications. Swing shouldn't be your "first stop" when looking for examples to learn about Java. And if you still want to start with Java - then take existing tutorials - "trial and error" isn't an efficient strategy to learn a framework such as Swing. There are many subtle details you have to know about - not knowing them translates to: running from one problem to the next.
Upvotes: 4