public class NotHelloWorld {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run(){
JFrame frame = new NotHelloWorldFrame();
frame.setTitle("NotHelloWorld");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
程序主体,在事件队列中创建一个将运行的接口。设置窗口的标题和退出按钮。
JFrame frame = new NotHelloWorldFrame();
创建一个新的窗口类。
class NotHelloWorldFrame extends JFrame{
private static final long serialVersionUID = 1L;
public NotHelloWorldFrame() {
add(new NotHelloWorldComonent());
pack(); //只使用首选大小
}
}
在新的窗口类NotHelloWorldFrame里面,添加组件NotHelloWorldComonent到内容窗格里。
class NotHelloWorldComonent extends JComponent{
private static final long serialVersionUID = 1L;
public static final int Message_X = 75;
public static final int Message_Y = 100;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public void paintComponent(Graphics g){
g.drawString("I am Zhang JunFeng", Message_X, Message_Y);
}
public Dimension getPreferredSize() {return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);} //
}
定义组件,组件设置了要显示消息的窗口位置,窗口的位置,消息的内容。最后一行设置返回组件的首选大小。
package notHelloWorld;
import javax.swing.*;
import java.awt.*;
/**
* @version 2020/2/1
*/
public class NotHelloWorld {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run(){
JFrame frame = new NotHelloWorldFrame();
frame.setTitle("NotHelloWorld");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* Frame和NotHelloWorld的接口
*/
class NotHelloWorldFrame extends JFrame{
private static final long serialVersionUID = 1L;
public NotHelloWorldFrame() {
add(new NotHelloWorldComonent()); //添加一个内容窗格
pack();
}
}
/**
* 组件,设置内容窗格的属性
*/
class NotHelloWorldComonent extends JComponent{
private static final long serialVersionUID = 1L;
public static final int Message_X = 75;
public static final int Message_Y = 100;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public void paintComponent(Graphics g){
g.drawString("I am Zhang JunFeng", Message_X, Message_Y);
}
public Dimension getPreferredSize() {return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);} //返回组件的首选大小
}