简体   繁体   中英

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. 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. Your method returns a JButton object, but you're not doing anything with this object.

  • Create a JPanel
  • Add the JButton to the JPanel
  • Add the JPanel to the JFrame
  • Display the JFrame by calling setVisible(true)
  • 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 .

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);
         }
      });
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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