Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java.awt help

Options
  • 21-02-2008 1:54am
    #1
    Registered Users Posts: 6,889 ✭✭✭


    I've an assignment to do for college, which involves plotting the course taken by a drunken sailor on his walk back to the boat. I have all the coordinates I need for the drawLine(int, int, int, int) constructor, but it appears this cant be used within a block of code...
    sailor[i] = new CrewMember();
    			CrewMember.initialise(sailor[i]);
    			do{
                                int a, b, c, d;
                                a = sailor[i].getX();
                                b = sailor[i].getY();
                                sailor[i].takeStep();
                                c = sailor[i].getX();
                                d = sailor[i].getY(); // I want to drawLine here
                                sailor[i].evaluate();
    			}while(sailor[i].moveable());
    

    Any and all feedback much apreciated.


Comments

  • Closed Accounts Posts: 1,444 ✭✭✭Cantab.


    obl wrote: »
    I've an assignment to do for college, which involves plotting the course taken by a drunken sailor on his walk back to the boat. I have all the coordinates I need for the drawLine(int, int, int, int) constructor, but it appears this cant be used within a block of code...
    sailor[i] = new CrewMember();
    			CrewMember.initialise(sailor[i]);
    			do{
                                int a, b, c, d;
                                a = sailor[i].getX();
                                b = sailor[i].getY();
                                sailor[i].takeStep();
                                c = sailor[i].getX();
                                d = sailor[i].getY(); // I want to drawLine here
                                sailor[i].evaluate();
    			}while(sailor[i].moveable());
    

    Any and all feedback much apreciated.

    What college is this? Java awt?! Tut, tut. Awt was deprecated ages ago. Ask your lecturer why you're using deprecated classes and see what he says.


  • Registered Users Posts: 413 ✭✭ianhobo


    His college is irrelevant to his problem.

    And as far as I know, AWT is far from deprecated! Heres the Java 6 docs for AWT, it makes no mention of awt being deprecated

    AWT still has many many relevant uses over swing. Swing allows Java to be further platform independent, but at a potential cost, particularly outside of the scope of powerful desktop computers. Java has other uses too.

    Maybe AWT alternatives are next weeks class!

    And to the original poster, what sort of graphics interface are you using? some more code might help


  • Registered Users Posts: 981 ✭✭✭fasty


    drawLine(int, int, int, int) isn't a contructor, it's a method belonging to Graphics which seems to represent a graphics context for drawing.

    If I remember correctly, for drawing in Java you have a class that extends Canvas and override it's Paint function which takes an instance of a Graphics object as a parameter and you use that to do the drawing.
    public class MyCanvas extends Canvas {
     
         public void paint(Graphics g) {
             // paint stuff here
         }
     }
    

    Can you post more code?


  • Registered Users Posts: 6,889 ✭✭✭tolosenc


    Here's the entire .java file. We won't be taught this as it's only an introduction course,this is if we're arsed to go and figure it out ourselves. Prize for the best one too!
    package Assignment4;
    public class UI extends javax.swing.JFrame {
        public UI() {
            initComponents();
        }                      
        private void initComponents() {
    
            jLabel1 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Assignment 4");
            setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
            setResizable(false);
    
            jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Assignment4/GUIbg1.jpg"))); 
    
            jButton1.setText("Go!");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jLabel2.setText("Back on boat: ");
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jButton1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel3))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
    
            pack();
        }                       
        
        
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            final int CREW_MEMBERS = 50;
    		CrewMember[] sailor = new CrewMember[CREW_MEMBERS];
    		int backOnShip = 0;
    
    		for(int i = 0; i < CREW_MEMBERS; i++){
    			sailor[i] = new CrewMember();
    			CrewMember.initialise(sailor[i]);
    			do{
                                int a, b, c, d;
                                a = sailor[i].getX();
                                b = sailor[i].getY();
                                sailor[i].takeStep();
                                c = sailor[i].getX();
                                d = sailor[i].getY();
                                sailor[i].evaluate();
    			}while(sailor[i].moveable());
    
    			if(sailor[i].successful())
    				backOnShip++;
    		}
                    
                    jLabel3.setText(Integer.toString(backOnShip));
                    
    		if(backOnShip > 34)
    			System.out.println(backOnShip + " made it! The ship was able to sail!");
    		else
    			System.out.println("Only " + backOnShip + " made it back to the boat... The ship is stuck in Whiskey for ever...");
        }                                        
         public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new UI().setVisible(true);
                }
            });
        }
                       
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
                   
        
    }
    
    


  • Registered Users Posts: 1,984 ✭✭✭lynchie


    obl wrote: »
    Here's the entire .java file. We won't be taught this as it's only an introduction course,this is if we're arsed to go and figure it out ourselves. Prize for the best one too!
    package Assignment4;
    public class UI extends javax.swing.JFrame {
        public UI() {
            initComponents();
        }                      
        private void initComponents() {
    
            jLabel1 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Assignment 4");
            setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
            setResizable(false);
    
            jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Assignment4/GUIbg1.jpg"))); 
    
            jButton1.setText("Go!");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jLabel2.setText("Back on boat: ");
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jButton1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel3))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
    
            pack();
        }                       
        
        
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            final int CREW_MEMBERS = 50;
    		CrewMember[] sailor = new CrewMember[CREW_MEMBERS];
    		int backOnShip = 0;
    
    		for(int i = 0; i < CREW_MEMBERS; i++){
    			sailor[i] = new CrewMember();
    			CrewMember.initialise(sailor[i]);
    			do{
                                int a, b, c, d;
                                a = sailor[i].getX();
                                b = sailor[i].getY();
                                sailor[i].takeStep();
                                c = sailor[i].getX();
                                d = sailor[i].getY();
                                sailor[i].evaluate();
    			}while(sailor[i].moveable());
    
    			if(sailor[i].successful())
    				backOnShip++;
    		}
                    
                    jLabel3.setText(Integer.toString(backOnShip));
                    
    		if(backOnShip > 34)
    			System.out.println(backOnShip + " made it! The ship was able to sail!");
    		else
    			System.out.println("Only " + backOnShip + " made it back to the boat... The ship is stuck in Whiskey for ever...");
        }                                        
         public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new UI().setVisible(true);
                }
            });
        }
                       
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
                   
        
    }
    
    

    Override the paint() method and call drawLine in there.


  • Advertisement
  • Registered Users Posts: 4,188 ✭✭✭pH


    This is not that easy for a novice - basically you need to choose one of 2 approaches.

    1 Create a custom component with a paint method that's capable or rendering all the steps in its paint method. This means that as you process all the drunken steps you'll need to store them somehow so they can be rendered (many times) in the component's paint method.

    2 Find/Write a generic plotting component that allows you to call methods like drawline and circle but which will automatically add these to some storage and continue to draw them each time repaint is called. - does anyone know an off the shelf component that does this?

    Either way you'll need to add a new component to the frame, overriding the frame's paint method when the frame has items on it is not the right approach.

    Also if you want to see the plots develop as you run you'll need to introduce a separate thread - even if this is going to run quite quickly it's not a good idea to put long running loops/application logic on the main Swing thread.
    http://en.wikipedia.org/wiki/SwingWorker


  • Registered Users Posts: 4,188 ✭✭✭pH


    Boring Friday ...

    Here's a rough and ready component that you can paint onto (using the standard graphics 2D commands and it remembers everything that's been drawn on it.
    package Assignment4;
    
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    
    class PaintComponent extends JPanel {
        
        private BufferedImage buffer = null;
           
        public PaintComponent() {
            setPreferredSize(new Dimension(200, 200));
            setBackground(Color.white);        
        }
                
        @Override public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;  
            g2.drawImage(getBuffer(), null, 0, 0);
        }
        
        public BufferedImage getBuffer() {
            
            if (buffer == null) { // Create a new one if needed
                int w = this.getWidth();
                int h = this.getHeight();
                buffer = (BufferedImage)this.createImage(w, h);
                Graphics2D gc = buffer.createGraphics();
                
                gc.setColor(Color.WHITE);
                gc.fillRect(0, 0, w, h); // fill in background
            }
            
            return buffer;
        }
    }
    


    to use it:
    Create one
    private PaintComponent p = new PaintComponent();

    Set it up and add it to the container
    p.setSize(200,200);
    .addComponent(jLabel3)
    .addComponent(p))


    Then use its custom getBuffer() and draw onto it:

    Graphics2D g = (Graphics2D)p.getBuffer().getGraphics();
    g.setColor( co );
    g.setStroke(new BasicStroke(2));
    g.drawLine(a * 10,b* 10 ,c* 10 ,d * 10);

    Here's a rough and ready of it added to your existing code
    package Assignment4;
    
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.util.concurrent.ExecutionException;
    import javax.swing.SwingWorker;
    public class UI extends javax.swing.JFrame {
        
        private PaintComponent p = new PaintComponent();
        public UI() {
            initComponents();
        }
        
        private void initComponents() {
            
            jLabel1 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            //PaintComponent p = new PaintComponent();
            p.setSize(200,200);
            
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Assignment 4");
            setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
            setResizable(false);
            
            //jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Assignment4/GUIbg1.jpg")));
            
            jButton1.setText("Go!");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
            
            jLabel2.setText("Back on boat: ");
            
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                    .addComponent(jButton1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel3)
                    .addComponent(p))
                    );
            layout.setVerticalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(p))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    );
            
            pack();
        }
        
        
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            processWalks();
        }
        
        private void processWalks() {
            final int CREW_MEMBERS = 10;
            int backOnShip = 0;
            
            for(int i = 0; i < CREW_MEMBERS; i++){
                WalkWorker ww = new WalkWorker();
                ww.execute();
                try {
                    CrewMember sailor = ww.get();
                    if ( sailor.successful() )
                        backOnShip++;
                    
                } catch (Exception ignore) { } 
            }
            
            jLabel3.setText(Integer.toString(backOnShip));
            
            if(backOnShip > 34)
                System.out.println(backOnShip + " made it! The ship was able to sail!");
            else
                System.out.println("Only " + backOnShip + " made it back to the boat... The ship is stuck in Whiskey for ever...");
        }
        
        
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new UI().setVisible(true);
                }
            });
        }
        
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        
        class WalkWorker extends SwingWorker<CrewMember, Object> {
            @Override public CrewMember doInBackground() {
                CrewMember sailor = new CrewMember();
                CrewMember.initialise(sailor);
                int steps = 0;
                Color co = Color.getHSBColor((float)Math.random(), (float)Math.random(), (float)Math.random()) ;
                do{
                    int a, b, c, d;
                    a = sailor.getX();
                    b = sailor.getY();
                    sailor.takeStep();
                    c = sailor.getX();
                    d = sailor.getY();
                    if (a == c && b == d)
                        continue;
                    Graphics2D g = (Graphics2D)p.getBuffer().getGraphics();
                    g.setColor( co );
                    g.setStroke(new BasicStroke(2));
                    g.drawLine(a * 10,b* 10 ,c* 10 ,d * 10);
                } while( sailor.moveable() && steps++ < 500);
                            
                return sailor;
            }
            
            @Override protected void done() {
                try {
                    p.repaint();
                } catch (Exception ignore) { }
            }
        }    
    }
    


  • Registered Users Posts: 6,889 ✭✭✭tolosenc


    Thanks for that pH.

    In execution of your code, it returns that none made it to the ship and doesn't draw anything for me. Did it work for you?


  • Registered Users Posts: 4,188 ✭✭✭pH


    Yes it worked for me - though I had to hack together my own version of CrewMember as you hadn't posted your implementation of that class.

    I suggest adding a println after sailor.takeStep() and print its x and y coordinates - see if the sailors are attempting to stagger home drunk :)

    the code that I tested presumes the sailors are walking randomly on a 20x20 grid (ie 0 <= x or y < 20)


  • Registered Users Posts: 6,889 ✭✭✭tolosenc


    public class CrewMember {
    	private int xCount, yCount, location;
    	private boolean disabled = false, initialised = false, successful = false;
    
    	public CrewMember(){}
    
    	public static void initialise(CrewMember c){
    		if(!c.initialised){
    			c.xCount = 4;
    			c.yCount = 2;
    			c.location = 1;
    			c.initialised = true;
    		}
    	}
    
    	private void disable(){
    		this.xCount = 0;
    		this.yCount = 0;
    		this.disabled = true;
    	}
    
    	private void forward(){
    		this.yCount++;
    	}
    
    	private void back(){
    		this.yCount--;
    	}
    
    	private void left(){
    		this.xCount--;
    	}
    
    	private void right(){
    		this.xCount++;
    	}
    
    	public void takeStep(){
    		double d = Math.random();
    		d = d * 10;
    		int i = (int)d;
    
    		if(moveable()){
    			if(i == 0 || i == 1 || i == 2 || i == 3 || i == 5  || i == 6 || i == 9){
    				this.forward();
    			}
    
    			if(i == 4){
    				this.back();
    			}
    
    			if(i == 7){
    				this.left();
    			}
    
    			if(i == 8){
    				this.right();
    			}
    		}
    	}
    
    	public boolean moveable(){
    		return !disabled;
    	}
    
    	public void evaluate(){
    		if(this.yCount == 1){
    			this.location = 3;
    			this.disable();
    		}else{
    			if(this.yCount == 22){
    				this.location = 4;
    				this.successful = true;
    				this.disable();
    			}else{
    				if(this.xCount == 1 || this.xCount == 7){
    					this.location = 2;
    					this.disable();
    				}
    			}
    		}
    	}
    	
    	public int getX(){
    		return this.xCount;
    	}
    	
    	public int getY(){
    		return this.yCount;
    	}
    
    	public int getLocation(){
    		return this.location;
    	}
    
    	public boolean successful(){
    		if(this.disabled){
    			if(this.successful)
    				return true;
    			else
    				return false;
    		}else{
    			return false;
    		}
    	}
    }
    

    the dock is 20X5, falling off the two long sides and one of the short sides is a fail, with the fourth side being the dock.


  • Advertisement
  • Registered Users Posts: 4,188 ✭✭✭pH


    With my code exactly as pasted and your CrewMember class I get a plot but no sailors make it home ... the problem is that the evaluate() method is never being called by my UI class - add a call to it after takestep() in the main loop (or even better - within then takestep() method in CrewMember.


  • Registered Users Posts: 6,889 ✭✭✭tolosenc


    Any way to make it pause temprarilt between steps? Thread.sleep() just pauses the whole thing and then draws the whole path...


  • Registered Users Posts: 4,188 ✭✭✭pH


    Yes but it will need a bit of a rewrite.

    The Walkworker inner class is a SwingWorker, basically this is split into 2 parts - the first part (doInBackground) runs in its own thread (and shouldn't update swing components) and then the done() method runs (and is allowed update swing components).

    You will need a swingworker that doesn't iterate through all a sailor's steps but makes only one step then paints the component - you will need to move the main loop for each sailor outside of the swingworker. Then you can add a delay for each step.


Advertisement