java-swing在组件中显示信息

package com.http;
import java.awt.*;

import javax.swing.*;

public class TestSwing2
{
//创建了一个能够绘制的组件
class HelloWorldComponent extends JComponent
{
    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("hello world",MESSAGE_X,MESSAGE_Y);
    }
    
    public Dimension getPreferredSize()
    {
        return new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT);
    }
}

//添加内容到frame
class HelloWorldFrame extends JFrame { public HelloWorldFrame() { add(new HelloWorldComponent()); pack(); } } public static void main(String[] argvs) { EventQueue.invokeLater(new Runnable() { public void run() {
       //在实例化内部类时,需要先实例化外部类 JFrame frame
= new TestSwing2().new HelloWorldFrame(); frame.setTitle("hello world"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } }
原文地址:https://www.cnblogs.com/Pierre-de-Ronsard/p/3986716.html