I have written a program that paints 5 pictures onto a canvas in jframe. I have now added a jtextfield so that the user can input a number using an actionlistener.
Ideally, the number that the user enters should then produce that amount of pictures on a new canvas.
problem is, i cant remove the canvas object and add a new canvas with the new amount of pictures on it.
please help
public class TaxiFrame extends JFrame implements ActionListener {
private JLabel L1 = new JLabel("Number of Taxis:");
private JLabel L2 = new JLabel("Type an integer and press enter");
private JTextField t1 = new JTextField (" ");
public TaxiFrame() {
super("This is the Frame");
setSize(600, 400);
getContentPane().setBackground(Color.CYAN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
Random rx = new Random();
Random ry = new Random();
for(int i = 0; i < 5; i ++)
{
TaxiCanvas tax = new TaxiCanvas();
tax.setBounds(rx.nextInt(600 - 100), ry.nextInt(400 - 100), 100, 100);
add(tax);
}
JPanel p = new JPanel();
p.setOpaque(false);
p.add(L1);
getContentPane().
add("South", p);
p.setOpaque(false);
p.add(t1);
getContentPane().
add("South", p);
p.setOpaque(false);
p.add(L2);
getContentPane().
add("South", p);
setVisible(true);
t1.addActionListener(this);
}
public static void main(String[] args) {
new TaxiFrame();
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == t1)
{
if(Integer.parseInt(t1.getText()) > 0)
{
getContentPane().removeAll();
TaxiCanvas tax = new TaxiCanvas();
add(tax);
}
}
}
}
thanks alot
taxi canvas code is
import java.awt.*;
import javax.swing.*;
public class TaxiCanvas extends JComponent
{
private Taxi taxi = new Taxi();
public void paint(Graphics g)
{
taxi.paint(g);
}
}
taxi code
import java.awt.*; public class Taxi { public void paint(Graphics g) { // drawing the car body g.setColor(Color.yellow); g.fillRect(0,10, 60, 15); // drawing the wheels g.setColor(Color.black); g.fillOval(10, 20, 12, 12); // left wheel g.fillOval(40, 20, 12, 12); // right wheel int x[] = {10, 20, 40, 50}; // coordinate arrays for the int y[] = {10, 0, 0, 10}; // car cabin g.setColor(Color.yellow); g.fillPolygon(x, y, 4); // drawing the cabin in yellow g.setColor(Color.black); g.drawString("20", 25, 22); g.drawLine(0, 25, 60, 25); } }