M
M
mr_firuzinho2019-01-07 10:29:02
Java
mr_firuzinho, 2019-01-07 10:29:02

How to draw correctly on jpanel?

Hello, I have a main window (MainFrame), where the menu, table, etc., and there is free space where an empty JPANEL (MainDrawPanel) is placed, I want to draw shapes there.
I have a code that I have already prepared, but I can only draw in a new window, JFRAME:

public class MainFrame extends javax.swing.JFrame {
. . .  
private void metName () {
class MyPanel extends JPanel {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawString("Contours: " + contours.size(), 20, 20);

                for (Contour c : contours) {
                    System.out.println(c.getArea());
                    int gg = rnd.nextInt(250);
                    int r = rnd.nextInt(250);
                    int B = rnd.nextInt(250);
                    g.setColor(new Color(0, 0, 0));

                    ListIterator<Point_dt> itr = c.points.listIterator();
                    Point_dt a = itr.next();//throws Exception if points size = 0

                    while (a != null && itr.hasNext()) {
                        Point_dt b = itr.next();
                        
                        g.drawLine((int) a.x, (int) a.y, (int) b.x, (int) b.y);
                       //g.drawString("(" + a.x + ", " + a.y + ") ", (int)a.x, (int)a.y);
                        //g.drawString("(" + b.x + ", " + b.y + ") ", (int)b.x, (int)b.y);
                        g.fillOval((int) a.x, (int) a.y, 4, 4);
                        g.fillOval((int) b.x, (int) b.y, 4, 4);
                        a = b;
                    }
                }
            }
        }

        JFrame frame = new JFrame("Рисунок");
        JPanel viewer = new MyPanel();
      
        frame.getContentPane().add(viewer);
        frame.setSize(new Dimension(900, 780));
        frame.setVisible(true);
}
. . .
}

This code works but it draws on a separate window, how do I make it work on the main window (MainFrame), on an empty JPANEL(mainDrawPanel) ?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question