0

I'm learning java and I start from beginning:)

I want to draw line on Panel but I cant

it's my code:

public class Window extends JFrame{

    public Window(){    
        setSize(600,600); 
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    Container pow = getContentPane(); 
    Component k = new Test();           
    pow.add(k); 

    Panel p1 = new Panel();
    p1.setBounds(40, 40, 520, 520);
    p1.setBackground(Color.white);
    pow.add(p1);    
}
}

and Panel class

import java.awt.*;
import javax.swing.*;

public class Test extends JPanel{

public void paintComponent(Graphics g){
    g.drawLine(30, 50, 30, 550);
    g.drawLine(30, 550, 550, 550);

    g.drawLine(30, 50, 20, 60);
    g.drawLine(30, 50, 40, 60);

    g.drawLine(550, 550, 540, 540);
    g.drawLine(550, 550, 540, 560);
}

}

and main

    public static void main(String[] args){
    Window mo = new Window();
    mo.setVisible(true);
}

Why my component is under Panel? Sory it's my code

Micchaleq
  • 433
  • 1
  • 5
  • 21
  • `Panel` and `Component` is AWT, `JPanel` and `JComponent` is Swing. AWT does not use `paintComponent` but `paint`. Switch the AWT classes to the Swing ones or `paintComponent` to `paint` and it _might_ work. – PurkkaKoodari Jan 11 '14 at 16:50
  • Post the complete code, so that we can paste it in our IDE and test it. And learn how to use layout managers. – JB Nizet Jan 11 '14 at 16:52
  • If your class extends an AWT `Panel`, there is no `paintComponent` method, so any painting would cease to show, since you're not actually overriding anything – Paul Samsotha Jan 11 '14 at 16:55

2 Answers2

1
  • The contentPane uses a BorderLayout as its default layout.
  • When you add a component to a BorderLayout container without specifying where, it gets added BorderLayout.CENTER.
  • This will then cover up any other components previously added to the same location.

Solution:

  • Read up on and experiment with using other layout managers. Check this tutorial.
  • Don't setBounds or use null layouts.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

Panel and Component is AWT, JPanel and JComponent is Swing. AWT does not use paintComponent but paint. Switch the AWT classes to the Swing ones or paintComponent to paint and it might work.

This is why adding @Override to overriding methods is a good idea, as it tells you that paintComponent is not a method of Component.

Also you are adding both the component and the panel to the same container. Put the component in the panel.

p1.add(k); // yes (add this to your code)
pow.add(k); // no (remove this from your code)
pow.add(p1); // previous would get covered
PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58