Dibujando un rectángulo en un JPanel
Quiero dibujar un rectángulo en un JPanel. Puedo dibujar con el siguiente código.
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 ()); En lugar de esta declaración, necesito agregar un panel base al marco. En el panel base, quiero agregar el panel MyComponent.
JPanel basePanel = new JPanel();
basePanel = new MyComponent();
getContentPane().add(basePanel);
Si me gusta esto, el rectángulo no se hace visible. ¿alguna idea? Y también necesito cambiar el tamaño del rectángulo en tiempo de ejecución. ¿Es posible