我有一个扩展 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);
有关更多信息,请开始阅读 here .
除此之外:您应该首先了解静态字段和非静态字段之间的区别。拥有所有静态字段(在类的实例之间共享)是一种不好的做法;然后将它们用作构造函数中的“普通”字段。
换句话说:在编写 Swing UI 应用程序之前,您可能想先学习 Java 的基础知识。在寻找学习 Java 的示例时,Swing 不应该是您的“第一站”。如果您仍然想从 Java 开始 - 那么请学习现有教程 - “反复试验”并不是学习 Swing 等框架的有效策略。您必须了解许多微妙的细节 - 不了解它们就意味着:从一个问题跑到下一个问题。
关于java - 如何在 Jframe 中创建 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43975008/