I want to draw a recangle on a JPanel. Am able to draw with the following code.
public class DrawingColor extends JFrame
{
public static void main(String[] args)
{
DrawingColor d = new DrawingColor();
}
public DrawingColor()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new MyComponent());
setSize(400,400);
setVisible(true);
}
public class MyComponent extends JComponent
{
@Override
public void paint(Graphics g)
{
int height = 200;
int width = 120;
g.setColor(Color.red);
g.drawRect(10, 10, height, width);
g.setColor(Color.gray);
g.fillRect(11, 11, height, width);
g.setColor(Color.red);
g.drawOval(250, 20, height, width);
g.setColor(Color.magenta);
g.fillOval(249, 19, height, width);
}
}
}
But getContentPane().add(new MyComponent());
Instead of this statement,I need to add one base panel to the frame. On the base panel I want to add the MyComponent panel.
JPanel basePanel = new JPanel();
basePanel = new MyComponent();
getContentPane().add(basePanel);
If I do like this, the rectangle is not getting visible. any idea?
And also I need to change the size of the rectangle at runtime. is it possible?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…