无法在java上创建我自己的绘图小部件[关闭]

问题描述 投票:1回答:2

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

但似乎缺少main方法。

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

我知道我不应该自己调用这个方法,但是当我运行程序时,我得到的错误主要方法没有在课堂上找到....

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

这是我尝试的简单代码:

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);
    }
}
java eclipse swing
2个回答
2
投票

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

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


0
投票

如果你是java的新手,我建议你在Tutorials | Javatpoint上给4-5天。

Java规则是java文件名应该与包含main方法的类名匹配。

所以主要方法的简单代码:

class Simple {  
    public static void main(String args[]) {  
    System.out.println("Hello Java");  
    }  
}  

在这种情况下,此代码应该在Simple.java文件中。

© www.soinside.com 2019 - 2024. All rights reserved.