How do I get paintComponent to work within my drawArea JPanel? Additionally, my attempts to set the drawArea’s dimensions have failed. No drawing occurs once running, and the JPanel is minimal size. DOes this have to do with MigLayout?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import net.miginfocom.layout.*;
import net.miginfocom.swing.MigLayout;
import java.awt.geom.*;
public class OvalDrawer extends JApplet
{
private JLabel numberL;
private JTextField numberTF;
private NumHandler numHandler;
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public int number;
//Create Layout
public void init()
{
setLayout(new MigLayout("wrap 2"));
numberL = new JLabel("Enter number of ovals to draw:");
numberTF = new JTextField(7);
add(numberL);
add(numberTF);
numHandler = new NumHandler();
numberTF.addActionListener(numHandler);
JPanel drawArea = new JPanel();
drawArea.setSize(400, 400);
drawArea.setBorder(BorderFactory.createTitledBorder("Draw Area"));
add(drawArea, "span 2");
setSize(WIDTH, HEIGHT);
}
//Event Handler
public class NumHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
number = Integer.parseInt(numberTF.getText());
repaint();
}
}
//Draw Ovals
public void paintComponent (Graphics g)
{
super.paintComponents(g);
int x = 10;
int y = 10;
int width = 200;
int height = 100;
for (int i = 0; i < number; i++)
{
g.drawOval(x, y, width, height);
x += 5;
y += 5;
width += 5;
height += 5;
}
}
}
There is no
paintComponentmethod inJApplet.You should avoid painting directly onto a top level container like
JApplet, its much more the just a single layer container.Instead, create a second class, extending from something
JPaneland perform you custom painting there.UPDATED
You should also avoid using
setPreferred/Minimum/MaximumSize, it’s to easy for some one else to circumvent.