我正在研究Java Swing,我对以下简单代码有一些问题:
package com.techub.exeute;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class Main{
public static void main(String[] args) {
JFrame frame = new JFrame("FrameDemo");
frame.setMinimumSize(new Dimension(800, 400));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel myLabel = new JLabel("Hello World !!!", SwingConstants.CENTER);
myLabel.setFont(new Font("Serif", Font.BOLD, 22));
myLabel.setBackground(Color.blue);
myLabel.setOpaque(true);
myLabel.setPreferredSize(new Dimension(100, 80));
frame.getContentPane().add(myLabel, BorderLayout.NORTH);
}
}
我的想法是创建一个 JFrame 对象,并在其中插入一个Hello World JLabel 对象设置一些属性。
我在 main()方法中执行此操作。问题是,当我执行程序时,我看不到任何东西!为什么?我的代码出了什么问题?
TNX
安德烈
答案 0 :(得分:10)
您正在创建框架,但您没有显示它。致电
frame.setVisible(true);
显示它。
另一件事:你不应该操纵主线程中的GUI组件。相反,创建一个用于创建框架和设置组件的新方法,并在事件派发线程中运行该方法,如the example from the official tutorial中所示:
import javax.swing.*;
public class HelloWorldSwing {
private static void createAndShowGUI() {
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
答案 1 :(得分:6)
添加
frame.setVisible(true);
代码
请参阅Creating and Showing Java Swing Frames
的步骤//1. Create the frame.
JFrame frame = new JFrame("FrameDemo");
//2. Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//3. Create components and put them in the frame.
//...create emptyLabel...
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//4. Size the frame.
frame.pack();
//5. Show it.
frame.setVisible(true);
你错过了#5
答案 2 :(得分:2)
你需要一个
frame.setVisible(true);
调用您的代码。
正如其他人所说,你不应该使用主Thread
进行gui操作。我建议你应该参考SWING的official tutorials,它们非常有用,你会在那里看到适当线程的例子。
答案 3 :(得分:2)
在你的方法中保留这一行
frame.setVisible(true);