paintComponent不改变形状

use*_*469 1 java swing paintcomponent

有人可以看看我下面的代码并告诉我为什么,当我更改以下两个语句时,我看不到绘制的矩形的更改.所以,如果我改变:

g.setColor(Color.black); 
g.fillRect(l, w, 100, 100);
Run Code Online (Sandbox Code Playgroud)

该程序仍打印出一个黑色矩形,其尺寸相同,位于我最初开始时的位置,即使我将颜色更改为黄色或尝试更改尺寸或位置.我是BlueJ.以下是我的完整代码:

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

public class SwingPaintDemo2 extends JComponent {

public static boolean isWall = true;

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI(); 
        }
    });
}


private static void createAndShowGUI() {
    //System.out.println("Created GUI on EDT? "+
    //SwingUtilities.isEventDispatchThread());
    JFrame f = new JFrame("Swing Paint Demo");
    JPanel MyPanel = new JPanel();
     MyPanel.setBorder(BorderFactory.createEmptyBorder(1000, 1000, 1000, 1000));
     MyPanel.setPreferredSize(new Dimension(250, 200));
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.add(new MyPanel());
    f.pack();
    f.setVisible(true);

}


public void paintComponent(Graphics g) {
    super.paintComponent(g); 
    int l = 10;
    int w = 10;

  g.setColor(Color.black); 
  g.fillRect(l, w, 100, 100);

        }

}
Run Code Online (Sandbox Code Playgroud)

任何意见,将不胜感激.

Dav*_*amp 5

你的SSCCE没有编译在哪里MyPanel上课或你的意思new SwingPaintDemo2()

假设你的意思是new SwingPaintDemo2():

代码确实工作得很好但是JFrame尺寸非常小:

在此输入图像描述

因为你没有给它任何大小,并且没有任何组件有大小,因为它们没有添加任何组件,因此我们必须使JComponent返回正确的大小,所以当我们调用pack()时,我们JFrame的大小正确

倍率getPreferredSize()JComponent返回的宽度和高度,其适合所有附图.

但有些建议:

  • 不要延伸JComponent而是延伸JPanel

这是一个示例(您的代码已实现上述修复):

在此输入图像描述

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

public class SwingPaintDemo2 extends JPanel {

    public static boolean isWall = true;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        //System.out.println("Created GUI on EDT? "+
        //SwingUtilities.isEventDispatchThread());
        JFrame f = new JFrame("Swing Paint Demo");
        JPanel MyPanel = new JPanel();
        MyPanel.setBorder(BorderFactory.createEmptyBorder(1000, 1000, 1000, 1000));
        MyPanel.setPreferredSize(new Dimension(250, 200));
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new SwingPaintDemo2());
        f.pack();
        f.setVisible(true);

    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int l = 10;
        int w = 10;

        g.setColor(Color.black);
        g.fillRect(l, w, 100, 100);

    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(150, 150);
    }
}
Run Code Online (Sandbox Code Playgroud)