paintComponent不改变形状

时间:2012-12-11 18:47:34

标签: java swing paintcomponent

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

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

即使我将颜色变为黄色或尝试更改尺寸或位置,程序仍然会打印一个尺寸相同且与我刚开始时位置相同的黑色矩形。我是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);

        }

}

任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:5)

您的SSCCE没有编译MyPanel课程的位置,或者您的意思是new SwingPaintDemo2()

假设您的意思是new SwingPaintDemo2()

代码确实运行正常,但JFrame的大小非常小:

enter image description here

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

<强>解决方案

覆盖getPreferredSize()的{​​{1}},以返回适合所有图纸的宽度和高度。

但有些建议:

  • 不要延伸JComponent而是延伸JComponent

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

enter image description here

JPanel