java - 未能在java上制作我自己的绘图小部件

标签 java eclipse swing

我坚持了 4 行代码。 他们应该让我创建自己的小部件。

但似乎main缺少方法。

我尝试自己编写一个主类并在 paintComponent() 中创建一个对象方法没有运气。

我知道我不应该自己调用该方法,但是当我运行程序时,我收到错误 Main method not found in class....

有人可以解释一下这是如何工作的或者给我一个阅读链接吗?

这是我尝试过的简单代码:

import javax.swing.*;

import java.awt.*;

class MyDrawPanel extends JPanel {

    public void paintComponent(Graphics g) {
        g.setColor(Color.orange);
        g.fillRect(20, 50, 100, 100);
    }
}

最佳答案

尝试这个简单的代码,它应该对您有帮助:

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

public class MyDrawPanel extends JPanel {

    private static final int WIDE = 300;
    private static final int HIGH = 200;


    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.orange);
        g.fillRect(20, 50, 100, 100);
    }

    public MyDrawPanel() {
        setBackground(Color.white);
        // Set a initial size for the program window
        this.setPreferredSize(new Dimension(WIDE, HIGH));
    }

     private void display() {
        // Some statements to let the JFrame appear in a good way
        JFrame f = new JFrame("MyDrawPanel");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

     // Main method is called when the program is runned
     public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MyDrawPanel().display();
            }
        });
    }
}

输出:

enter image description here

关于java - 未能在java上制作我自己的绘图小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36506397/

相关文章:

java - 尝试为 JLabel 设置图像图标,但 URL 返回 null

java - log4j2 和 ch.qos.logback.core.PropertyDefinerBase

java - 如何处理 DirectVmConsumerNotAvailableException

java - 不规则的蓝牙传输速度?

java - Mac Eclipse 项目可以在安装了 Eclipse 的 Windows PC 上运行吗?

java - 使用隐式 Intent 过滤器时如何绕过 Complete Action Using 菜单?

java - 如何让jFilechooser双击打开特定目录?

java - ResultSet.next() 没有选择 jPasswordField && jTextField

eclipse - Eclipse 4.3 的 GWT 插件

java - 如何在以下代码中调整 ImageIcon 数组列表的大小