【问题标题】:Can't see GUI components in applet?在小程序中看不到 GUI 组件?
【发布时间】:2018-02-11 01:18:44
【问题描述】:

由于某种原因,我的 GUI 组件没有显示在我的小程序中。我设置了一个单独的类,在其中创建所有 GUI 组件并将它们添加到我创建的面板中。之后,我将该对象与创建的面板添加到小程序中,但由于某种原因,它没有显示在我的小程序中。在添加了包含我的组件的对象后,我确保将我的小程序上的可见性设置为 true,但这也无济于事。

public class CreatePannel extends JPanel{

JPanel panel=new JPanel();

public CreatePanel()  {//This is my constructor for the object that I created to create my components and add them to my panel called leftPanel that I set as an instance variable at the start of this class.  
  JButton button=new JButton();
  panel.add(button);
  }
}

 public class GUI extends JApplet{

  public void init() {// In a separate class that extends Applet
   setLayout(new BorderLayout());
   CreatePanel test=new CreatePanel();
   add(test);//TRYING TO ADD GUI COMPONENTS TO MY APPLET
   setVisible(true); 
   }

 }

【问题讨论】:

  • 请发一个有效的minimal reproducible example。让我们看看你到底在做什么。
  • 另外,如果这是你需要使用小程序的学校作业,那就这样吧,但请理解小程序被认为是“死”技术,因为大多数浏览器并不完全支持它们,甚至 Java 背后的力量甲骨文也将不再支持它们。请参阅Moving to a Plugin-Free Web。其他选项包括使用 HTML5/CSS3/JavaScript 和 JavaFX/WebView。
  • 好吧,这意味着你被一个教授死技术的老师困住了,我真的很同情你。但同样,如果您需要我们帮助找出问题所在,我们将需要更多代码,而不是全部,但足以让我们运行代码并遇到问题,minimal reproducible example。请阅读链接。
  • 确定添加了我拥有的所有内容。我认为我的问题是我在添加组件之前使用了 setVisible(true) ,但这里似乎就是这种情况。
  • 发布您的真实代码,而不是输入代码。然后,您似乎没有向 CreatePanel 实例添加任何内容,因此当然不会显示任何内容。

标签: java swing user-interface graphics applet


【解决方案1】:

您永远不会将组件添加到 GUI。这个构造函数:

public CreatePanel()  {
    JButton button=new JButton();
    panel.add(button);
}

创建一个 JButton 并将其添加到面板 JPanel 中,但随后对这些人不执行任何操作,因为它们从未添加到包含 JPanel 的类中。你需要更多,特别是:

public CreatePanel()  {
    JButton button=new JButton();
    panel.add(button);
    this.add(panel);  // the "this" is not actually needed but there for emphasis
}

此代码现在将面板 JPanel 添加到包含 CreatePanel 对象,然后最终添加到 JApplet。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    相关资源
    最近更新 更多