【问题标题】:How to create a JPanel inside a Jframe?如何在 Jframe 中创建 JPanel?
【发布时间】:2017-10-13 23:22:29
【问题描述】:

我有一个扩展 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);
 }
}

【问题讨论】:

  • 与您目前所做的原则相同......
  • 快速的方法是在netbeans或eclipse中使用gui builder
  • 除此之外:阅读有关 java 命名约定的信息。类名采用 CamelCase。总是。

标签: java swing jframe jpanel


【解决方案1】:

简单:

  • 您创建了一个面板
  • 你将它添加到框架中

喜欢:

JPanel p = new JPanel(); 
f.getContentPane().add(p);

欲了解更多信息,请开始阅读here

除此之外:您应该首先了解静态和非静态字段之间的区别。拥有 all 静态字段(在您的类的实例之间共享)是一种不好的做法;然后将它们用作构造函数中的“普通”字段。

换句话说:在编写 Swing UI 应用程序之前,您可能想先学习 Java 的基础。在寻找学习 Java 的示例时,Swing 不应该是您的“第一站”。而且,如果您仍想从 Java 开始 - 然后学习 现有 教程 - “反复试验”并不是学习 Swing 等框架的有效策略。您必须了解许多微妙的细节 - 不了解它们会转化为:从一个问题运行到下一个问题。

【讨论】:

    猜你喜欢
    • 2013-10-04
    • 2019-07-07
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 2011-09-22
    • 1970-01-01
    • 2012-04-17
    相关资源
    最近更新 更多