[英]How to create a JPanel inside a Jframe?
I have a class that extends JFrame that has a menubar and menu Items inside of it. 我有一个扩展JFrame的类,其中的JMenu具有菜单栏和菜单项。 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? 我想在菜单栏下添加一个JPanel,可以在其中添加组件和绘制形状。如何在此类内添加JPanel? 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);
}
}
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 UI应用程序之前,您可能想先学习Java的基础知识 。 Swing shouldn't be your "first stop" when looking for examples to learn about Java. 寻找有关Java的示例时,Swing不应成为您的“第一站”。 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. 而且,如果您仍然想从Java入手-然后阅读现有的教程-“试错法”不是学习诸如Swing之类的框架的有效策略。 There are many subtle details you have to know about - not knowing them translates to: running from one problem to the next. 您必须了解许多细微的细节-不知道它们会转化为:从一个问题到另一个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.