I have a main window (MainFrame), where the menu, table, etc., and there is an empty space where an empty JPANEL (MainDrawPanel) is placed, I want to draw figures 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) ax, (int) ay, (int) bx, (int) by); //g.drawString("(" + ax + ", " + ay + ") ", (int)ax, (int)ay); //g.drawString("(" + bx + ", " + by + ") ", (int)bx, (int)by); g.fillOval((int) ax, (int) ay, 4, 4); g.fillOval((int) bx, (int) by, 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 can I make it work in the main window (MainFrame), on an empty JPANEL (mainDrawPanel)?

  • It should work in the main window. Check out the layout. - talex
  • It is not necessary to review JPanel from Component . - talex
  • and then add to the MainDrawPanel panel like this: MainDrawPanel.add (viewer); ? So does not show anything - firuz

1 answer 1

there is a suspicion that you simply do not see either the MainDrawPanel or the MyPanel that you are not putting it. Try this

 mainDrawPanel.setLayout(new BorderLayout()); mainDrawPanel.add(viewer,BorderLayout.CENTER); 

Thus, the entire viewer panel should stretch the entire central area of ​​the MainDrawPanel panel. Here is the BorderLayout documentation . Also check the dimensions of the MainDrawPanel.

If I remember correctly, then frame.getContentPane () has a default BorderLayout. And when added without explicitly indicating the zone, the element is added to the center. Therefore, in the new frame you have everything displayed.

  • Earned how the size specification was added to your code: mainDrawPanel.setSize(new Dimension(600, 600)); - firuz