1

新细节:

从我的主类的 actionPerformed 事件内部调用时,我的 JPanel 对象的重绘方法不起作用。它确实在主类 ImageViewer 的 ImageViewer 方法中工作,但在此类的 actionPerformed 方法中不起作用。

这些是我的代码中无法正常工作的基本部分(重绘部分):

主类:

/**
 * @(#)NeatImageViewer.java
 *
 * NeatImageViewer application
 *
 * @author
 * @version 1.00 2010/11/1
 */

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;


public class NeatImageViewer extends JFrame implements ActionListener {

    GraphicsPanel gp;

    NeatImageViewer() {
               //... window components ...
    }

    public static void main(String[] args) {

        NeatImageViewer niv = new NeatImageViewer();
        niv.setSize(500,500);
        niv.setLocationRelativeTo(niv);
        niv.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
            //...
                gp = new GraphicsPanel();
                gp.img = img;
                gp.repaint(); //<!--- Not Working!
                this.add(gp);
            //...
    }

}

图形面板类:

/**
 * @(#)GraphicsPanel.java
 *
 *
 * @author
 * @version 1.00 2010/11/1
 */

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;


public class GraphicsPanel extends JPanel {
    BufferedImage img;

    GraphicsPanel() {
        super();
    }

    protected void paintComponent(Graphics g) {
        //paint method isn't executed???
        super.paintComponent(g);
        System.out.println("Paint!");
    }

}
4

3 回答 3

1

您必须覆盖paintComponent(Graphics g)而不是paint(Graphics g).
因此,您发布的方法应重命名为paintComponent.

编辑:初始化完成后,您是否pack()编辑了框架?

编辑:repaint()当组件不可见时,该方法不执行任何操作。因此,您必须先将其添加到 JFrame,pack()即框架。打包后,不再需要重新粉刷。

于 2010-11-01T19:33:47.140 回答
0

In Swing you don't use a Canvas. You do custom painting on a JPanel or JComponent and you override the paintComponent(...) method as already stated. Read the Swing tutorial on Custom Painting for more information and working examples.

Also, with Swing there is no need to create a custom components to show an image. You just use a JLabel with an ImageIcon. Read the section on "How to Use Icons".

Bookmark the tutorial for all the Swing basics.

Edit:

When you add a component to a visible GUI the basic code should be:

panel.add( ... );
panel.revalidate();
panel.repaint();
于 2010-11-01T20:13:50.683 回答
0

(我是 Skyfe,但来自另一个 IP,所以没有“登录”也无法发表评论)

我很抱歉,但我不明白这是什么问题???

我提供了我的代码,并且在从 actionPerformed 方法调用 repaint 时它没有执行 paintComponent 函数。只需复制粘贴我的代码并使用 java 编译器编译它,它不会在执行我可以判断的操作时执行 paintComponent 方法,因为我在 paint 方法中使用了 System.out.println() 方法。不,它不会绘制任何东西,因为我只是想检查它是否完全调用了绘制方法,因为我将系统输出放在了使用重绘时不执行的 paintComponent 方法中。这只是一个测试,它没有工作。

所以你的意思是SSCCE在哪里,这就是我拥有的所有代码。我完全编译了我在主帖中发布的代码,它的问题是它在执行操作时不显示任何系统输出(并且调用了重绘事件)。我看不到我的帖子中遗漏了什么?

于 2010-11-02T08:29:12.337 回答