gpt4 book ai didi

java - 使用 JLayer 在图像上放置网格

转载 作者:行者123 更新时间:2023-11-30 08:57:17 25 4
gpt4 key购买 nike

我想在图像上放置一个网格。我使用了一个使用 paintComponent 方法保存图像的 JLabel,我使用这个方法是因为在我的项目和 JLayer< 的不同阶段图像会发生变化 GridDrawer extends LayerUI 类有助于绘制网格(对于较小的示例,我只使用了 drawRect() 方法)。

我的代码:

GridPhoto(主)类:

 /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gridphoto;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;

/**
*
* @author VJ
*/
public class GridPhoto {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new GUI();
} catch (IOException ex) {
Logger.getLogger(GridPhoto.class.getName()).log(Level.SEVERE, null, ex);
}
}

});
}

}

GUI 类:

   package gridphoto;

import java.awt.image.BufferedImage;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JLayer;
import javax.swing.plaf.LayerUI;

public class GUI {
JFrame frame;
JPanel panel;
JLayer<JLabel> GridLayer;
JLabel imagelabel;
LayerUI<JLabel> GridUI;
BufferedImage img;

public GUI() throws IOException {
frame = new JFrame("GridImage Test");
panel = new JPanel();
img = ImageIO.read(new File("/Users/VJ/Desktop/gs.png"));
imagelabel = new JLabel() {
public void paintComponent(Graphics g) {
g.drawImage(img.getScaledInstance(500, 500, BOTTOM), 0, 0, null);
}
};
GridUI = new GridDrawer();
GridLayer = new JLayer(imagelabel, GridUI);
panel.setLayout(new BorderLayout());
frame.setLayout(new BorderLayout());
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 700);
panel.add(GridLayer);
frame.add(panel);
frame.setVisible(true);

}

public class GridDrawer extends LayerUI<JLabel> {

public void paintComponent(Graphics g) {
g.drawRect(0, 0, 250, 250);
}

}

}

我的问题是,即使在将 JLayer 添加到 JPanel 之后,它也只显示图像而不显示网格。例如,GridDrawer 类的 paintComponent 方法仅绘制一个 Rectangle

请告诉我我的代码有什么问题,或者除了使用 JLayer 将网格放置在 Image 之外还有其他方法吗?

输出。

最佳答案

LayerUI 没有 paintComponent(...) 方法。

无论何时覆盖方法,请确保使用 @Override,这样您就知道您正在覆盖正确的方法:

@Override
public void paint(...)

并且不要忘记调用 super.paint(...)。

How to Decorate Components With JLayer Class 上阅读 Swing 教程获取更多信息和工作示例。

关于java - 使用 JLayer 在图像上放置网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28239699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com