我有一个扩展JFrame的类,里面有一个菜单栏和菜单项。在菜单栏下,我想添加一个 JPanel,我可以在其中添加组件和绘制形状。如何在此类中添加 JPanel?对不起,如果这是一个简单的问题,我是初学者。
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);
}
}
简单:
- 创建面板
- 将其添加到框架中
喜欢:
JPanel p = new JPanel();
f.getContentPane().add(p);
有关更多信息,请在此处开始阅读。
除此之外:您应该首先阅读静态字段和非静态字段之间的区别。拥有所有静态字段(在类的实例之间共享(只是不好的做法;然后将它们用作构造函数中的"普通"字段。
换句话说:在编写 Swing UI 应用程序之前,您可能希望先学习 Java 的基础知识。Swing不应该是你寻找学习Java的例子时的"第一站"。如果你仍然想从Java开始 - 那么采取现有的教程 - "试错"并不是学习像Swing这样的框架的有效策略。你必须知道许多微妙的细节 - 不知道它们转化为:从一个问题跑到下一个问题。