使用JLayer将网格放在图像上

时间:2015-01-30 15:54:04

标签: java swing jlayer

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

我的代码:

GridPhoto(Main)Class:

drawRect()

GUI类:

 /*
 * 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);
                }
            }

        });
    }

}

我的问题是,即使将 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类的paintComponent方法仅绘制GridDrawer

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

输出。

1 个答案:

答案 0 :(得分:2)

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

每当您覆盖某个方法时,请确保使用@Override,这样您就知道要覆盖正确的方法:

@Override
public void paint(...)

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

阅读How to Decorate Components With JLayer Class上的Swing教程,了解更多信息和工作示例。