0

我对 Java 不是很熟悉,而且我对当前的问题也一无所知。我试图在我的 Main JFrame 的一个单独的类中绘制一个图像,但它总是只绘制一小块图片(可能是 10x10px)。(带有标签的测试有效)

也许我没有正确使用 g.drawImage 方法,或者 JPanel 没有足够的空间?

主窗口:

public class Deconvolutioner extends JFrame {
Draw z;
Picturearea picturearea;

class Draw extends JPanel {
    public void paint(Graphics g) {


    }
}

public Deconvolutioner() {
    setTitle("Deconvolutioner");
    setLocation(30,1);
    setSize(1300,735);
    super.setFont(new Font("Arial",Font.BOLD,11));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    FlowLayout flow = new FlowLayout(FlowLayout.CENTER);

    this.setLayout(flow);

    picturearea = new Picturearea();

    this.add(picturearea);

    add(z = new Draw());
    setVisible(true);

}

class Open implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        JFileChooser fileOpen = new JFileChooser();
        FileFilter filter = new FileNameExtensionFilter("png & jpg files", "png",  
        "jpg");
        fileOpen.addChoosableFileFilter(filter);
        int returnVal = fileOpen.showDialog(null, "Open file");
        if (returnVal == JFileChooser.APPROVE_OPTION)  {
            try {
                String path = fileOpen.getSelectedFile().getPath();
                URL url = new File(path).toURI().toURL();
                BufferedImage img = ImageIO.read(url);

                picturearea.setPicture(img);

            } catch (IOException ex)  {
                System.err.println("Some IOException accured (set the right path?): ");
                System.err.println(ex.getMessage());
            }
        } else   {

        }

        repaint();
    }
}

和单独的类:

public class Picturearea extends JPanel {
  public BufferedImage image;
  Draw z;

  public Picturearea() {
      add(z = new Draw());
      setVisible(true);
  }

class Draw extends JPanel {
    @Override
    public void paint(Graphics g) {
        g.drawImage(image, 0, 0, this);

    }
}

public void setPicture(BufferedImage picture) {
    try  {                
        image = picture;
    }  catch (Exception e)  {
        System.err.println("Some IOException accured (did you set the right path?): ");
        System.err.println(e.getMessage());
    }
    repaint();
}

}

我很感激每一个帮助。
谢谢你的时间。

4

1 回答 1

0
  • 您正在使用FlowLayoutforJFramecontentPane布局。FlowLayout服从组件的preferredSize. 尝试在课堂上设置preferredSize您的pictureAreabypictureArea.setPreferredSize(Dimension) 或覆盖getPreferredSize(Dimension)函数PictureArea

  • paint(Graphics g)用于自定义绘画:

    @Override
    public void paint(Graphics g) {
        g.drawImage(image, 0, 0, this);
    
    }
    

    不要覆盖paint()自定义绘画覆盖paintComponent(Graphics g)。您可能需要缩放图像以适应 JPanel 的大小。g.drawImage(x, y, width, height, observer)如果您需要缩放图像,可以使用函数。

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    
    } 
    
于 2013-10-25T13:37:51.713 回答