简体   繁体   English

在Mac上将JFrame与Netbeans一起使用

[英]Using JFrame with Netbeans on a Mac

I want to run this code that will create a window with a simple button on it. 我想运行此代码,这将创建一个带有简单按钮的窗口。 The program will run in Netbeans on a Mac but the problem is that it does not work. 该程序将在Mac上的Netbeans中运行,但问题是它无法正常工作。 Here is the code below. 这是下面的代码。

    import javax.swing.JFrame;

    public class Test {

    public static JButton button(){
    JButton button = new JButton("random button");
    }

    public static void main(String[] args) {
    button();
    new JFrame();

    }
    }

Please help me figure this out soon please. 请帮我尽快解决这个问题。 Thank you. 谢谢。

You're not adding the button to anything or displaying the JFrame. 您没有将按钮添加到任何内容或显示JFrame。 Your method returns a JButton object, but you're not doing anything with this object. 您的方法返回一个JButton对象,但是您没有对该对象做任何事情。

  • Create a JPanel 创建一个JPanel
  • Add the JButton to the JPanel 将JButton添加到JPanel
  • Add the JPanel to the JFrame 将JPanel添加到JFrame
  • Display the JFrame by calling setVisible(true) 通过调用setVisible(true)显示JFrame
  • Most important: Making up code and hoping it will magically work is not a successful heuristic for learning to program. 最重要的是:编写代码并希望它能神奇地工作并不是学习编程的成功试探法。 Instead read the Swing tutorials which you can find here . 相反,请阅读Swing教程,您可以在这里找到。

For example 例如

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class MyTest {
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            JButton button = new JButton("Button");
            JPanel panel = new JPanel();
            panel.add(button);
            JFrame frame = new JFrame("foo");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.add(panel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
         }
      });
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM