问题描述
在这里您将看到我的代码:我只是试图制作一个小窗口,显示你好,Java!".
Here you will see my code:I am just trying to make a little window that displays "Hello, Java!".
我当前正在Ubuntu 14.04上运行.为了更深入地研究我的问题,当我运行该程序时,带有咖啡杯的图标会显示出来,就像有一个窗口,但是没有附加窗口,如果单击该窗口,则不会弹出任何窗口.
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.
任何帮助将不胜感激!
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);
}
}
此外,我正在使用javac HelloJava1.java通过命令行进行编译,并使用java HelloJava1进行了运行.
Additionally, I am compiling via command line using javac HelloJava1.java and running using java HelloJava1.
我正在通过gedit编写代码.
I am writing the code via gedit.
推荐答案
此代码应可靠运行:
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);
}
}
这篇关于JFrame代码可以编译并运行,但不会打开窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!