在Jpanel中绘制矩形

Jac*_*des 5 java swing

我试图在java中进行GUI编程,并希望在Jpanel中绘制一个矩形.代码没有给出任何错误,但我无法在GUI中获得矩形.有人可以告诉我以下代码中缺少的内容.我相信这很简单,所以请保持温柔.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HelloWorldGUI2 {

    private static class ButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
        System.exit(0);
        }
        }
    private static class RectDraw extends JPanel {
        public void paintComponent(Graphics g) {
        super.paintComponent(g);  
         g.drawRect(230,80,10,10);  
         g.setColor(Color.RED);  
         g.fillRect(230,80,10,10);  
        }
        }
    public static void main(String[] args) {
        JPanel content = new JPanel();
        RectDraw newrect= new RectDraw();
        JButton okButton= new JButton("OK");
        JButton clearButton= new JButton("Clear");
        ButtonHandler listener= new ButtonHandler();
        okButton.addActionListener(listener);
        clearButton.addActionListener(listener);
        content.add(okButton);
        content.add(clearButton);
        content.add(newrect);
        JFrame window = new JFrame("GUI Test");
        window.setContentPane(content);
        window.setSize(250,100);
        window.setLocation(100,100);
        window.setVisible(true);
        }

    }
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 11

你的newrect RectDraw的大小可能会非常小,可能是[0,0],因为它已经使用JPanel添加到FlowLayout并且没有设置preferredSize.考虑重写其getPreferredSize()方法并返回合适的Dimension,以便可以看到它的绘图.

private static class RectDraw extends JPanel {
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);  
    g.drawRect(230,80,10,10);  
    g.setColor(Color.RED);  
    g.fillRect(230,80,10,10);  
  }

  public Dimension getPreferredSize() {
    return new Dimension(PREF_W, PREF_H); // appropriate constants
  }
}
Run Code Online (Sandbox Code Playgroud)

也,

  • paintComponent方法应该受到保护,而不是公开的
  • @Override在您的方法覆盖之前不要忘记使用.
  • 瞄准的主要方法更少的代码和更多的代码在"实例"的世界,而不是静态的世界.
  • 注意代码格式.糟糕的代码格式化,尤其是误导性的缩进,会导致愚蠢的错误.


cam*_*ckr 5

我试图在java中使用GUI编程

然后你应该先阅读Swing教程.

对于这个问题,您可以从自定义绘画部分开始.

本教程不仅向您展示了一个工作示例,而且还向您展示了如何通过在EDT上执行代码来正确创建框架.阅读本节以Concurrency获取更多信息.