Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Paint specific component ? (Repost1)

Anh Nguyen
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say that I have 2 diff. JPanels . I want to draw in 1 Panel only (that mean the paint won't touch other 2 ) . How can I do that .
I tried paintComponent(Graphics g) but nothing happen . But when I tried paint(Graphics g) then the whole program is messing up .
I have also read the tutorial at sun about how to use paintComponent but it's not really helpful .
Please help . Ex code include is good
Ex code problem :
This Test program supposed to draw a line in panel2 as the user drag the mouse.
Unfortunity, it does not work. Please take a look and correct it.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame{
private int xVal1=-1,yVal1=-1,xVal2=-1,yVal2=-1;
public Test(){
super("Test paint specific Panel");
Container c = getContentPane();
JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("Panel 1", SwingConstants.LEFT);
final JPanel panel2 = new JPanel();
panel2.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
xVal1 = e.getX();
yVal1 = e.getY();
public void mouseReleased(MouseEvent e){
xVal2 = e.getX();
yVal2 = e.getY();
c.add(panel2, BorderLayout.CENTER);
}//end no-argument constructor
public void paintComponent(Graphics g){
public static void main(String [] args){
Test app = new Test();
new WindowAdapter(){
public void windowClosing(WindowEvent e){
}//end main
}//end program

... No one can escape .......
Heavenly Evil Knight
deekasha gunwant
Ranch Hand
Posts: 396
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Anh,
here is the modified program that works correctly.just compile and run it.

I'm in a bit hurry so not explaining the case u need help do get back.
just two points.
1)u needed to override the paintComponent() of panel2.
2) u were calling this.paintComponent() ...this was a recursive call to same method .instead u need to call super.paintComponent().
hope this helps
[This message has been edited by deekasha gunwant (edited February 14, 2001).]
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic