简体   繁体   English

JPanel从另一个类重新粉刷

[英]JPanel repaint from another class

I have a JPanel which displays an image. 我有一个显示图像的JPanel。 In a separate class, I'm reading from an xml file points. 在一个单独的类中,我从xml文件中读取要点。 I am firstly creating an arraylist of triangles from these points. 我首先从这些点创建三角形的数组列表。 However I need to show the triangles on the image, ie draw them on! 但是,我需要在图像上显示三角形,即在其上绘制! (yes this should be simple). (是的,这应该很简单)。 But as these points and triangles are created in another class, I do not seem to be able to draw them on the already-displayed image within the GUI class. 但是,由于这些点和三角形是在另一个类中创建的,因此我似乎无法在GUI类中已经显示的图像上绘制它们。 I have tried creating a ArrayList in the JPanel itself, which I update and then want to repaint, although it will not let me do this as shown below: 我尝试在JPanel本身中创建一个ArrayList,我对其进行了更新,然后想要重新绘制,尽管它不允许我这样做,如下所示:

Class

triangles = clips.getTriangles();
tempPanel.setTriangles(triangles){

JPanel JPanel

 public void settriangles(ArrayList<Point[]> t){
 triangles = t;
 repaint();
}

My only other idea is for the JPanel to have a listener waiting for when triangles are returned, updating the field and hence then repainting. 我唯一的另一个想法是让JPanel拥有一个侦听器,等待返回三角形时进行更新,从而更新字段,然后重新绘制。

Any ideas? 有任何想法吗?

Thanks 谢谢

Edit: Code for Drawing 编辑:绘图代码

public void settriangles(ArrayList<Point[]> t){
    triangles = t;
    repaint();
}

public void paintComponent(Graphics g) {

    System.out.println("in paint component");
if (g != null) {
    Graphics2D graphics = (Graphics2D) g;
    try {
        Rectangle back_rect = new Rectangle(0, 0, getWidth(),
                getHeight());
        graphics.setColor(GuiComponentGenerator.GUI_BACKGROUND_COLOUR);
        graphics.fill(back_rect);
        if (image != null) {
            int width = Math.round(image.getWidth() * magnification);
            int height = Math.round(image.getHeight() * magnification);
            Rectangle image_rect = new Rectangle(offset.x, offset.y,
                    width, height);
            graphics.setColor(Color.BLACK);
            graphics.draw(image_rect);
            graphics.drawImage(image, offset.x, offset.y, width,
                    height, null);
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            for(int pos = 0; pos < triangles.size(); pos++){
                Point[] current = triangles.get(pos);                   
                ArrayList<Point> current_triangle = new ArrayList<Point>();
                current_triangle.add(current[0]);
                current_triangle.add(current[1]);
                current_triangle.add(current[2]);
                drawRegion(graphics, current_triangle); 
            }
        }
    }

finally {
        graphics.dispose();
}
}



private void drawRegion(Graphics2D graphics, ArrayList<Point> points) {
    graphics.setColor(trans_grey);
    Area area = getArea(points);
    graphics.fill(area);
    graphics.setStroke(new BasicStroke(2));
    graphics.setColor(Color.BLACK);
    graphics.draw(area);
}

private Area getArea(ArrayList<Point> points) {
    Area area = new Area(getPath(points, true));
    return area;
}

private GeneralPath getPath(ArrayList<Point> points, boolean close_path) {
    GeneralPath path = new GeneralPath();
    Point current_screen_point = calculateScreenPoint(points.get(0));
    path.moveTo(current_screen_point.x, current_screen_point.y);
    for (int point_num = 1; point_num < points.size(); point_num++) {
        current_screen_point = calculateScreenPoint(points.get(point_num));
        path.lineTo(current_screen_point.x, current_screen_point.y);
    }
    if (close_path)
        path.closePath();
    return path;
}

public Point calculateScreenPoint(Point image_point) {
    float h_proportion = (float) image_point.x / (float) image.getWidth();
    float v_proportion = (float) image_point.y / (float) image.getHeight();
    float image_width_in_panel = (float) image.getWidth() * magnification;
    float image_height_in_panel = (float) image.getHeight() * magnification;

    Point on_screen_point = new Point(0, 0);
    on_screen_point.x = offset.x
            + Math.round(h_proportion * image_width_in_panel);
    on_screen_point.y = offset.y
            + Math.round(v_proportion * image_height_in_panel);
    return on_screen_point;
}

Your paintComponent leaves a little to be desired ;) 您的paintComponent有点不足;)

Firstly, you should never get a null graphics unless the paint method has been called in correctly, which in case they deserve for it to fail. 首先,除非正确调用了paint方法,否则绝对不要获得空图形,以防万一他们应该使它失败。

You should try and use Graphics.create to create a copy of the incoming Graphics context. 您应该尝试使用Graphics.create创建传入Graphics上下文的副本。 This allows you to mess with the Graphics properties (such as transforms etc) without adversly effecting the original 这使您可以在不不利影响原始图像的情况下弄乱Graphics属性(例如transforms等)

I don't know what the image is all about, but basically, if its null , your triangles will never paint (don't know if this is what you want or not). 我不知道image的全部含义,但是基本上,如果imagenull ,三角形将永远不会绘制(不知道这是否是您想要的)。

I don't know what the offset relates to, but just in case, the 0x0 point is always the top, left corner of your component. 我不知道offset与什么有关,但以防万一,0x0点始终是组件的左上角。

天空中的三角形

public void paintComponent(Graphics g) {

    // This is important, you will to have a very good reason not to call this
    super.paintComponent(g);

    System.out.println("in paint component");
    // Should never need this.  You should never call the paintComponent
    // directly.
    // if (g != null) {
    // Create a copy of the graphics, with which you can play...
    Graphics2D graphics = (Graphics2D) g.create();
    try {
        Rectangle back_rect = new Rectangle(0, 0, getWidth(),
                        getHeight());
        graphics.setColor(Color.GREEN);
        graphics.fill(back_rect);
        // What's this trying to do...
        // Where do you produce this???
        // Because I didn't know where the image was been produced
        // I commented out the code, but you should be aware
        // That if the image is null, you triangles will never paint...
//            if (image != null) {
//                int width = Math.round(image.getWidth() * magnification);
//                int height = Math.round(image.getHeight() * magnification);
//                
//                Rectangle image_rect = new Rectangle(offset.x, offset.y,
//                                width, height);
//                graphics.setColor(Color.BLACK);
//                graphics.draw(image_rect);
//                graphics.drawImage(image, offset.x, offset.y, width,
//                                height, null);
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
            for (int pos = 0; pos < triangles.size(); pos++) {
                Point[] current = triangles.get(pos);
                ArrayList<Point> current_triangle = new ArrayList<Point>(3);
                current_triangle.add(current[0]);
                current_triangle.add(current[1]);
                current_triangle.add(current[2]);
                drawRegion(graphics, current_triangle);
            }
        //} // From the image != null
    } finally {
        graphics.dispose();
    }
}

I'd also suggest you have a read through 我还建议您通读

If you haven't already ;) 如果您还没有;)

This article will give you all the info you need http://java.sun.com/products/jfc/tsc/articles/painting/ 本文将为您提供所有您需要的信息http://java.sun.com/products/jfc/tsc/articles/painting/

but I think you are missing - super.paintComponent(g); 但我认为您不见了-super.paintComponent(g);

public class MyPanel extends JPanel {
    protected void paintComponent(Graphics g) {
    // Let UI delegate paint first 
    // (including background filling, if I'm opaque)
    super.paintComponent(g); 
    // paint my contents next....
    }
}

I worked out how to draw triangles on the image, when passing through an arrayList, where each Point[] represents the points of the triangle. 当通过arrayList时,我想出了如何在图像上绘制三角形,其中每个Point []代表三角形的点。

Note that this is now in a single entire class which is passed the information, rather than trying to call repaint from another class. 请注意,这现在是传递信息的单个完整类,而不是尝试从另一个类调用重绘。

public AnnotatedDisplayTriangles(BufferedImage image, String image_path, ArrayList<Point[]> triangles) {

    this.image = image;
    this.image_path = image_path;
    this.triangles = triangles;

}

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    // Draw image centered.
    int x = (getWidth() - image.getWidth())/2;
    int y = (getHeight() - image.getHeight())/2;
    g.drawImage(image, x, y, this);

    Stroke drawingStroke = new BasicStroke(2);
    Graphics2D graph = (Graphics2D)g;
    graph.setStroke(drawingStroke);
    graph.setPaint(Color.black);


    for(int p = 0; p < triangles.size(); p++){

        Point[] current_triangles = triangles.get(p);

        for(int triangle = 0; triangle < current_triangles.length; triangle++ ){

            Point current = current_triangles[triangle];
            Point next;
            if(triangle == current_triangles.length -1 )
                next = current_triangles[0];
            else
                next = current_triangles[triangle + 1];

            Line2D line = new Line2D.Double(current.x, current.y, next.x, next.y);
            graph.draw(line);

        }
    }
}

public static void main(String image_path,ArrayList<Point[]> triangles, String panel_name) throws IOException {
    String path = image_path;
    BufferedImage image = ImageIO.read(new File(path));
    AnnotatedDisplayTriangles contentPane = new AnnotatedDisplayTriangles(image, path, triangles);
    // You'll want to be sure this component is opaque
    // since it is required for contentPanes. Some
    // LAFs may use non-opaque components.
    contentPane.setOpaque(true);

    int w = image.getWidth();
    int h = image.getHeight();

    JFrame f = new JFrame(panel_name);
//  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(contentPane);
    f.setSize(w,h);
    f.setLocation(200,200);
    f.setVisible(true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM