JFrame code compiles and runs, but does not open window

我与影子孤独终老i 提交于 2019-12-24 22:57:18

问题


Here you will see my code: I am just trying to make a little window that displays "Hello, Java!".

I am currently running on Ubuntu 14.04. To go more in depth with my problem, the icon with the coffee cup shows up when I run the program like there is a window, but there is not window attached to it and if clicked, no window pops up.

Any help would be much appreciated!

public class HelloJava1 extends javax.swing.JComponent
{
    public static void main(String[] args)
    {
        javax.swing.JFrame f = new javax.swing.JFrame("HelloJava1");
        f.setSize(300, 300);
        f.getContentPane().add(new HelloJava1());
        f.setVisible(true);
    }   

    public void paintComponent(java.awt.Graphics g)
    {
        g.drawString("Hello, Java!", 125, 95);
    }
}

Additionally, I am compiling via command line using javac HelloJava1.java and running using java HelloJava1.

I am writing the code via gedit.


回答1:


This code should work reliably:

import java.awt.*;
import javax.swing.*;

public class HelloJava1 extends JComponent {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                JFrame f = new JFrame("HelloJava1");
                // f.setSize(300, 300);  better to pack() the frame
                f.getContentPane().add(new HelloJava1());
                // pack should be AFTER components are added..
                f.pack();
                f.setVisible(true);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        SwingUtilities.invokeLater(r);
    }    

    @Override  // good practice..
    public void paintComponent(java.awt.Graphics g) {
        // always call super method 1st!
        super.paintComponent(g);
        g.drawString("Hello, Java!", 125, 95);
    }

    // instead of setting the size of components, it is 
    // better to override the preferred size.
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300,300);
    }
}


来源:https://stackoverflow.com/questions/25965176/jframe-code-compiles-and-runs-but-does-not-open-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!