Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: How to repaint() a class in a JFrame, with a JTextfield user input

  1. #1
    Junior Member
    Join Date
    Dec 2012
    Location
    Shrewsbury, UK
    Posts
    12
    My Mood
    Cool
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default How to repaint() a class in a JFrame, with a JTextfield user input

    I have written a;

    Taxi() which draws polygons in the shape of a car, using paint method (Graphics g).
    TaxiCanvas() which creates the amount of taxis to draw using a for loop.

    The problem, I think is with the following TaxiFrame(). I'm trying to get it use the inputNum from the JTextField to repaint() the Taxi(). But I enter an int and press enter and it displays correctly, but if I hit enter again it doubles the already defined number without redrawing, creating 2 instances of the Taxi(), if I clear the JTextField and use a new int, it adds even more instances of Taxi().

    How can I clear the user input and then enter a new int, so it redraws the Taxi().

    Also, what should I put in the catch (NumberFormatException nfe) section.

    Thanks for any info.

     
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
     
    public class TaxiFrame extends JFrame implements ActionListener 
    {
        JTextField jt = new JTextField(8);
        JPanel jp = new JPanel();
        JLabel jl = new JLabel();
        JLabel jl1 = new JLabel();
     
        public TaxiFrame()
        {
            super("Taxi Express");
            setSize(800, 600);
            setLocation(100, 100);
            getContentPane().setBackground(Color.CYAN);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
     
            jp.setBackground(Color.YELLOW);
            jp.add(jl1);
            jl1.setText("Number of taxis");
            jp.add(jt);
            jt.addActionListener(this);
     
            jl.setText("Type a number and press [Enter]");
            jp.add(jl);
            getContentPane().add("South", jp);
            setVisible(true);
        }
        //printout input number
     
        public void actionPerformed(ActionEvent e)
        {
            int inputNum = 1;
            try 
            {
                inputNum = Integer.parseInt(jt.getText());
            } 
     
            catch (NumberFormatException nfe)
     
            {
     
            }
     
            {
                getContentPane().add("Center", new TaxiCanvas(inputNum));
            }
     
            setVisible(true);
        }
     
        public static void main(String[] args)
        {
          new TaxiFrame();      
        }
    }


    --- Update ---

     
    import java.awt.*;
    import javax.swing.*;
     
    public class TaxiCanvas extends JComponent 
    {
        private Taxi[] taxis;
        int numberofTaxis;
     
        public TaxiCanvas(int numberofTaxis) 
        {
            super();
            this.numberofTaxis = numberofTaxis;
            setOpaque(false);
        }
            public void paint(Graphics g) 
            {
            //create taxi numbers   
            taxis = new Taxi[100];
     
            for (int loop = 0; loop < numberofTaxis; loop++) 
     
            {
               taxis[loop] = new Taxi(loop);
               taxis[loop].paint(g, randomInt(0, 600), randomInt(0, 400));
            }
     
     
            Font myFont = new Font("Times New Roman", Font.BOLD, 25);
            g.setFont(myFont);
            g.drawString(numberofTaxis + " Taxis", getWidth() / 2 - 30, 20);
        }
     
            private int randomInt(int min, int max) {
            return (int) (Math.random() * (max - min + 1) + min);
        }
     
    }


    --- Update ---

     
    import java.awt.*;
     
    public class Taxi
        {
     
        private Color colour;
        private int number;
     
        public Taxi(int num)
     
            {
            number = num + 1;
            colour = new Color(randomInt(0, 255), randomInt(0, 255), randomInt(0, 255));
            }
     
        private int randomInt(int min, int max)
     
            {
            return (int) (Math.random() * (max - min + 1) + min);
            }
     
        public void paint(Graphics g, int x, int y)
     
            {   //body
            int[] polyx = {6+x, 59+x, 84+x, 126+x, 151+x, 194+x, 194+x, 6+x};
            int[] polyy = {47+y, 47+y, 27+y, 27+y, 47+y, 47+y, 77+y, 77+y};
            g.setColor(colour);
            g.fillPolygon(polyx, polyy, 8);
     
            //wheels
            g.setColor(Color.BLACK);
            g.fillOval(30+x, 60+y, 30, 30);
            g.setColor(Color.BLACK);
            g.fillOval(140+x, 60+y, 30, 30);
     
            //windscreen
            int[] polya = {59+x, 84+x, 84+x};
            int[] polyb = {47+y, 27+y, 47+y};
            g.setColor(Color.LIGHT_GRAY);
            g.fillPolygon(polya, polyb, 3);
     
            //rear windows
            int[] polyc = {126+x, 151+x, 126+x};
            int[] polyd = {27+y, 47+y, 47+y};
            g.setColor(Color.LIGHT_GRAY);
            g.fillPolygon(polyc, polyd, 3);
     
            //number
            g.setColor(Color.white);
            g.drawString("" + number , 87+x, 65+y);
            }
     
        }


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: How to repaint() a class in a JFrame, with a JTextfield user input

    Quote Originally Posted by DANGEROUSSCION View Post
    Taxi() which draws polygons in the shape of a car, using paint method (Graphics g).
    Note that you should override a JPanel's or JComponent's paintComponent(...) method, not its paint(...) method.
    You've not shown us this class, and so it is hard to know what it might be doing right or wrong.

    TaxiCanvas() which creates the amount of taxis to draw using a for loop.
    Creates how? Using what layout manager?

    The problem, I think is with the following TaxiFrame().
    Are you sure about this? Have you used a debugger or println statements to isolate your error?

    I'm trying to get it use the inputNum from the JTextField to repaint() the Taxi(). But I enter an int and press enter and it displays correctly, but if I hit enter again it doubles the already defined number without redrawing, creating 2 instances of the Taxi(), if I clear the JTextField and use a new int, it adds even more instances of Taxi().

    How can I clear the user input and then enter a new int, so it redraws the Taxi().
    Also, what should I put in the catch (NumberFormatException nfe) section.
    I usually display a JOptionPane informing the user that the number entered was incorrect. I also usually only use the number inside of the try block, *after* the number has been attempted to be parsed. This will prevent me from trying to use the number if inaccurate data has been presented.

    --- Update ---

    Recommendations on first glance of your newly posted code:

    • Override the TaxiCanvas's paintComponent(Graphics g) method, not its paint(Graphics g) method.
    • The first line of this override should be a call to the super's method: super.paintComponent(g). This will help remove any previously drawn images.
    • Don't create your Taxi objects in the paint or paintComponent method but rather in the class's constructor.
    • I prefer extending JPanel in this situation to that of JComponent since JPanel will repaint its background for you.

Similar Threads

  1. [SOLVED] History of previouse input in JTextField
    By learn_java in forum AWT / Java Swing
    Replies: 1
    Last Post: November 7th, 2012, 08:38 AM
  2. [SOLVED] JTextField for Date input ( DD/MM/YY) or (DD : MM : YY)
    By chronoz13 in forum AWT / Java Swing
    Replies: 3
    Last Post: October 10th, 2011, 04:48 AM
  3. Reading user input from the console with the Scanner class
    By JavaPF in forum Java SE API Tutorials
    Replies: 3
    Last Post: September 7th, 2011, 03:09 AM
  4. My JFrame won't repaint correctly please help me out!
    By ocolegrove in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 10th, 2011, 10:04 PM
  5. Reading user input from the console with the Scanner class
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 0
    Last Post: November 11th, 2008, 01:47 PM