Torna indietro   Hardware Upgrade Forum > Software > Programmazione

Ecovacs Goat O1200 LiDAR Pro: la prova del robot tagliaerba con tagliabordi integrato
Ecovacs Goat O1200 LiDAR Pro: la prova del robot tagliaerba con tagliabordi integrato
Nuova frontiera per i robot tagliaerba, con Ecovacs GOAT O1200 LiDAR Pro che riconosce l'ambiente in maniera perfetta, grazie a due sensori LiDAR, e dopo la falciatura può anche rifinire il bordo con il tagliabordi a filo integrato
Recensione Samsung Galaxy S26+: sfida l'Ultra, ma ha senso di esistere?
Recensione Samsung Galaxy S26+: sfida l'Ultra, ma ha senso di esistere?
Equilibrio e potenza definiscono il Samsung Galaxy S26+, un flagship che sfida la variante Ultra e la fascia alta del mercato con il primo processore mobile a 2nm. Pur mantenendo l'hardware fotografico precedente, lo smartphone brilla per un display QHD+ da 6,7 pollici d'eccellenza, privo però del trattamento antiriflesso dell'Ultra, e per prestazioni molto elevate. Completano il quadro la ricarica wireless a 20W e, soprattutto, un supporto software settennale
Zeekr X e 7X provate: prezzi, autonomia fino a 615 km e ricarica in 13 minuti
Zeekr X e 7X provate: prezzi, autonomia fino a 615 km e ricarica in 13 minuti
Zeekr sbarca ufficialmente in Italia con tre modelli elettrici premium, X, 7X e 001, distribuiti da Jameel Motors su una rete di 52 punti vendita già attivi. La Zeekr X parte da 39.900 euro, la 7X da 54.100: piattaforma a 800V, chip Snapdragon di ultima generazione, ricarica ultraveloce e un'autonomia dichiarata fino a 615 km WLTP. Le prime consegne sono previste a metà aprile
Tutti gli articoli Tutte le news

Vai al Forum
Rispondi
 
Strumenti
Old 15-04-2007, 13:44   #1
mariade
Senior Member
 
L'Avatar di mariade
 
Iscritto dal: Jun 2005
Città: Swords, Dublino
Messaggi: 642
java: aiuto per un compito

ciao ragazzi,

volevo che deste attenzione al codice che ho scritto per dirmi dove sbaglio perche' non riesco a capirlo.

Vi preciso prima di tutto l'errore:


C:\java\java3>javac Polygon.java
Polygon.java:35: cannot find symbol
symbol : method drawPolygon(int,int,int)
location: class java.awt.Graphics
g.drawPolygon(getUpperLeftX(),getUpperLeftY(), getPointCt());
^
1 error


Di seguito I codici che mi servono correggere:

Codice:
import java.awt.*; 
import javax.swing.*;
import java.io.Serializable;

public abstract class MyShape implements Serializable {
private int x1, x2, y1, y2;
private int pointCt = 0;
private int XYValues[] = new int[500];

private Color color=Color.WHITE;

public MyShape () {setX1(0); setY1(0); setX2(0); setY2(0);}
public MyShape (int val1, int val2, int val3, int val4) { setX1(val1); setY1(val2); setX2(val3); setY2(val4);}

public MyShape (int val1, int val2, int val3, int val4, int pointCt) { setX1(val1); setY1(val2); setX2(val3);setY2(val4); setPointCt(pointCt);}

public MyShape (int val1, int val2, int val3, int val4, Color col) { setX1(val1); setY1(val2); setX2(val3);setY2(val4); setColor(col);}


public MyShape (int vals[]) {setX1(vals[0]); setY1(vals[1]); setX2(vals[2]); setY2(vals[3]); }

public MyShape (int vals[], int pointCt) {setX1(vals[0]); setY1(vals[1]); setX2(vals[2]); setY2(vals[3]); setPointCt(pointCt); }

public MyShape (int vals[], Color col) {setX1(vals[0]); setY1(vals[1]); setX2(vals[2]); setY2(vals[3]);setColor(col); }

public void setX1(int val) {x1 = ( val >= 0 ? val : 0 );} 
public void setX2(int val) {x2 = ( val >= 0 ? val : 0 );}
public void setY1(int val) {y1 = ( val >= 0 ? val : 0 );} 
public void setY2(int val) {y2 = ( val >= 0 ? val : 0 );}
public void setPointCt(int pointCt) {pointCt = ( pointCt >= 0 ? pointCt : 0 );} 


public void setColor(Color col) {this.color = col;}
public Color getColor() {return color;}
public int getX1() {return x1;} 
public int getX2() {return x2;}
public int getY1() {return y1;} 
public int getY2() {return y2;}
public int getPointCt() {return pointCt;}
public abstract void draw (Graphics g);

}
Codice:
import java.awt.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import static java.lang.Math.*;


public class Polygon extends MyShape {

private int pointCt = 0;

public Polygon () {super();}

public Polygon (int x1, int y1, int x2, int y2) {super(x1,y1,x2,y2); }

public Polygon (int val1, int val2, int val3, int val4, int pointCt) {super(val1,val2,val3,val4,pointCt); }

public Polygon (int val1, int val2, int val3, int val4, Color col) {super(val1,val2,val3,val4,col); }
public Polygon (int val[]) {super(val);}

public Polygon (int val[],int pointCt) {super(val,pointCt);}


public Polygon (int val[],Color col) {super(val,col);}


public int getUpperLeftX() { return Math.min(getX1(), getX2()); }
public int getUpperLeftY() { return Math.min(getY1(), getY2()); }

public void draw (Graphics g) { 


    g.setColor(getColor());

     g.drawPolygon(getUpperLeftX(),getUpperLeftY(), getPointCt());
 } 

 }
Codice:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.EOFException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.util.NoSuchElementException;

public class ShapeDrawJFrame extends JFrame {	

private final int SHAPETYPES=6;	        
private int shapeType=0;	       
private String shapeTypes[]= {"Line","Oval", "Rectangle", "FilledOval", "FilledRectangle", "Polygon"};	
private int numShapes=0;	        
private int XYValues[] = new int[500];
private int pointCt = 0;   	
private MyShape[] shapes = new MyShape[100];     	              	
private JComboBox shapesComboBox;	
private JComboBox colorChoice;	        
private Container container;	       
private JPanel lowerRow;
private JPanel upperRow;
private JButton undoButton;  
private JLabel label;     
private Graphics dragGraphics;               
private Color dragColor;
private int startAngle;
private int arcAngle;
private ObjectOutputStream output;
private ObjectInputStream input;              

private final static int                            
BLACK = 0,                      
RED = 1,            // Some constants to make                           
GREEN = 2,          // the code more readable.                            
BLUE = 3,           // These numbers code for                          
CYAN = 4,           // the different drawing colors.                       
MAGENTA = 5,                        
YELLOW = 6,                            
ORANGE = 7,
PINK = 8,
GRAY = 9;
		
 private boolean beingDragged;
  private JButton save, load;  
  private JTextField fileName;

public ShapeDrawJFrame() {

super("Draw Shapes");		

// addMouseListener(handler);
//     addMouseMotionListener(handler);		
container = getContentPane();		
container.setBackground(new Color(255,255,255));
                           

lowerRow = new JPanel();
label = new JLabel("You have select the type of shape to draw:");
lowerRow.add(label);
		
shapesComboBox = new JComboBox(shapeTypes);		
shapesComboBox.setSelectedIndex(0);		
lowerRow.add(shapesComboBox); 
              
colorChoice = new JComboBox();				
colorChoice.addItem("Black");               
colorChoice.addItem("Red");               
colorChoice.addItem("Green");               
colorChoice.addItem("Blue");               
colorChoice.addItem("Cyan");               
colorChoice.addItem("Magenta");                
colorChoice.addItem("Yellow");                
colorChoice.addItem("Orange");
colorChoice.addItem("Pink"); 
colorChoice.addItem("Gray");              
colorChoice.setBackground(Color.white);                
lowerRow.add(colorChoice);            	



undoButton = new JButton("UNDO");
lowerRow.add(undoButton); 
			

container.add(lowerRow, BorderLayout.SOUTH); 

MouseHandler handler= new MouseHandler();
     addMouseListener(handler);
     addMouseMotionListener(handler);     


     upperRow = new JPanel();
     save = new JButton( "  Save " );
     upperRow.add(save);
     save.addActionListener(

         new ActionListener() 
         {
            public void actionPerformed( ActionEvent event )
            {
              openOutputFile();
              writeShapes();
              closeFile();


            } 
       } 
      ); 


     load = new JButton( "  Load " );
      upperRow.add(load);
     load.addActionListener(

         new ActionListener() 
         {
            public void actionPerformed( ActionEvent event )
            {
              openInputFile();
              readShapes();
              closeFile();
              repaint();

            } 
       } 
      );  

      fileName=new JTextField(15);
      upperRow.add(fileName); 

container.add(upperRow, BorderLayout.NORTH);
		
setSize(600,600); 	
setVisible( true );	

}

public void paint( Graphics g) {		
super.paint(g);		
for (int sp=0;sp< shapes.length ; sp++) {			
if(shapes[sp]!=null) {                               

//g.setColor(dragColor);			

shapes[sp].draw(g);	  }
  } 
 }		

public void createShape(int index) {		

numShapes++;		

switch (index) {			
case 0: shapes[numShapes] = new Line(XYValues,getCurrentColor()); break;			
case 1: shapes[numShapes] = new Oval(XYValues,getCurrentColor()); break;			
case 2: shapes[numShapes] = new Rectangle(XYValues,getCurrentColor()); break; 
case 3: shapes[numShapes] = new FilledOval(XYValues,getCurrentColor()); break;
case 4: shapes[numShapes] = new FilledRectangle(XYValues,getCurrentColor()); break;

        }	
}        

private Color getCurrentColor() {              
// Check the colorChoice menu to find the currently               
// selected color, and return the appropriate color              
// object.        

int currentColor = colorChoice.getSelectedIndex();         
Color colorPlot=new Color(0,0,0);

 switch (currentColor) {           

case 0:  
colorPlot=Color.BLACK;  
break;                 

case 1:                 
colorPlot=Color.RED;  
break;                      

case 2:              
colorPlot=Color.GREEN;  
break; 

case 3:                
colorPlot=Color.BLUE;  
break; 

case 4:             
colorPlot=Color.CYAN;   
break;  

case 5:               
colorPlot=Color.MAGENTA;   
break;  

case 6:               
colorPlot=Color.YELLOW;   
break; 

case 7:               
colorPlot=Color.ORANGE;   
break;

case 8:               
colorPlot=Color.PINK;   
break;

case 9:               
colorPlot=Color.GRAY;   
break;

default:               
colorPlot=Color.BLACK;      
break; }  

return colorPlot;

}




private class MouseHandler implements MouseMotionListener, MouseListener{	

public void mousePressed (MouseEvent event) {           			

XYValues[0] = event.getX();			
XYValues[1] = event.getY();                                                      

//dragGraphics = container.getGraphics();                               
//dragColor = getCurrentColor();                               
//dragGraphics.setColor(dragColor);    

  }		


public void mouseDragged(MouseEvent event)
     {
       XYValues[2]=event.getX();
       XYValues[3]=event.getY();    


       createShape(shapesComboBox.getSelectedIndex());
       numShapes--;

       repaint();

     }

public void mouseReleased (MouseEvent event) {			

XYValues[2] = event.getX();			
XYValues[3] = event.getY();                       
createShape(shapesComboBox.getSelectedIndex());                      

repaint( );        
     }


public void mouseEntered(MouseEvent event){}


     public void mouseClicked(MouseEvent event){}


     public void mouseExited(MouseEvent event){}     


     public void mouseMoved(MouseEvent event){}


  }
  

  public void openOutputFile()
  {
   
    
    try
    {
      output = new ObjectOutputStream(new FileOutputStream(fileName.getText()));
      
    }
    catch (IOException ioException )
    {
	System.err.println("error output opening file");

    }

  }


  public void openInputFile()
  {
   
    
    try
    {
      input = new ObjectInputStream(new FileInputStream(fileName.getText()));
      
    }
    catch (IOException ioException )
    {
	System.err.println("error input opening file");

    }

  }


  public void closeFile()
  {
    try
    {

      if(input != null)
         input.close();
      if(output != null)
         output.close();
    
    }
    catch (IOException ioException )
    {
	System.err.println("error closing file");
        System.exit(1);

    }

  }




  public void writeShapes()
  {
     for(int sp=0; sp<shapes.length;sp++)
     {
       try
       {
        if(shapes[sp]!=null)
        {
          output.writeObject(shapes[sp]);
        }
                    
       }
       catch (IOException ioException)
       {
         System.err.println("error writing to file");
         return;
       }   
       catch (NoSuchElementException elementException)
       {
         System.err.println("Invalid Input. Please try again");

       } 


     }

    }     


  public void readShapes()
  {

     for(int i=0;i<numShapes;i++) shapes[i]= null;
     numShapes =0;

     try
     {
        while(true)
        {
           shapes[numShapes] =  (MyShape) input.readObject();
           numShapes++;
        }
      }
      catch (EOFException endOfFileException)
      {
        return;

      } 
      catch (ClassNotFoundException classNotFoundException)
      {
        System.err.println("unable to create object");

      } 
      catch (IOException ioException)
      {
        System.err.println("error during read from file");
      } 

  }

 }
qui il codice main:
Codice:
import javax.swing.JFrame;

public class ShapeDraw

{

//execute application
public static void main(String args[]) {

ShapeDrawJFrame shapeDrawJFrame = new ShapeDrawJFrame();
shapeDrawJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

shapeDrawJFrame.setVisible( true );
}}
Volevo aggiungere che java ho cominciato adesso a studiarlo!
Vi prego qualche dritta!Grazie a tutti!

Ultima modifica di mariade : 15-04-2007 alle 14:09.
mariade è offline   Rispondi citando il messaggio o parte di esso
Old 15-04-2007, 14:41   #2
MEMon
Senior Member
 
Iscritto dal: Dec 2002
Messaggi: 3359
Ciao, il metodo drawPolygon(int[] xPoints, int[] yPoints, int nPoints) ammette come vedi tre argomenti, il primo è un array dei punti per le x, il secondo un array per le y e il terzo semplice int che indica quanti punti vuoi.
Te usi 3 int invece.
MEMon è offline   Rispondi citando il messaggio o parte di esso
Old 15-04-2007, 14:55   #3
mariade
Senior Member
 
L'Avatar di mariade
 
Iscritto dal: Jun 2005
Città: Swords, Dublino
Messaggi: 642
Quote:
Originariamente inviato da MEMon Guarda i messaggi
Ciao, il metodo drawPolygon(int[] xPoints, int[] yPoints, int nPoints) ammette come vedi tre argomenti, il primo è un array dei punti per le x, il secondo un array per le y e il terzo semplice int che indica quanti punti vuoi.
Te usi 3 int invece.
Grazie per la risposta.

Questo lo sapevo, il punto e' questo: ho bisogno di disegnare i poligoni con array non precisi. L'applicazione e' di disegno appunto e nel compito si chiede di creare la classe poligono come sotto classe di MyShape che e' la superclasse. Immaginavo di aver sbagliato a scrivere il codice poligono, ma non ho idea di come inserire un array che non abbia dei punti ben specificati.
mariade è offline   Rispondi citando il messaggio o parte di esso
Old 15-04-2007, 14:59   #4
MEMon
Senior Member
 
Iscritto dal: Dec 2002
Messaggi: 3359
Ma cosa intendi con array non precisi?
Un poligono è una figura definita...se non sai da che punti è definita come fai a disegnarlo?

Magari prova a spiegarti meglio, perchè se ho capito bene non hai le idee molte chiare, ma forse ho capito male.
MEMon è offline   Rispondi citando il messaggio o parte di esso
Old 15-04-2007, 15:11   #5
mariade
Senior Member
 
L'Avatar di mariade
 
Iscritto dal: Jun 2005
Città: Swords, Dublino
Messaggi: 642
Quote:
Originariamente inviato da MEMon Guarda i messaggi
Ma cosa intendi con array non precisi?
Un poligono è una figura definita...se non sai da che punti è definita come fai a disegnarlo?

Magari prova a spiegarti meglio, perchè se ho capito bene non hai le idee molte chiare, ma forse ho capito male.
Cioe' io devo aver la possibilita' di disegnare un poligono a piacer mio, cioe' se io premo col mouse un un punto dell'applicazione quello sara' il primo vertice del poligono, il secondo mi fara' una linea, col terzo disegnero' un altro lato fino a che posso disegnare la forma che io avevo in mente.
Spero di esser stata piu' chiara.

Ti posto il codice (gira ma non e' completo) cosi' se hai la possibilita' di farlo girare avrai le idee piu' chiare:

Codice:
import java.awt.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import static java.lang.Math.*;


public class Polygon extends MyShape {

private int pointCt = 0;

public Polygon () {super();}

public Polygon (int x1, int y1, int x2, int y2) {super(x1,y1,x2,y2); }

public Polygon (int val1, int val2, int val3, int val4, int pointCt) {super(val1,val2,val3,val4,pointCt); }

public Polygon (int val1, int val2, int val3, int val4, Color col) {super(val1,val2,val3,val4,col); }
public Polygon (int val[]) {super(val);}

public Polygon (int val[],int pointCt) {super(val,pointCt);}


public Polygon (int val[],Color col) {super(val,col);}



public void draw (Graphics g) { 

   int xValues[] = {100};
   int yValues[] = {200};


    g.setColor(getColor());

     g.drawPolygon(xValues, yValues,pointCt);
 } 

 
}
Codice:
import java.awt.Graphics;

public class Line extends MyShape {

public Line () {super();}

public Line (int x1, int y1, int x2, int y2) {super(x1,y1,x2,y2); }

public Line (int val1, int val2, int val3, int val4, Color col) {super(val1,val2,val3,val4,col); }
public Line (int val[]) {super(val);}

public Line (int val[],Color col) {super(val,col);}
public void draw (Graphics g) {  

g.setColor(getColor());  
g.drawLine(getX1(),getY1(),getX2(), getY2());  } 

}
Codice:
import java.awt.*; 
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;

public class FilledRectangle extends BoundedShape {

public FilledRectangle () {super();}
public FilledRectangle (int val1, int val2, int val3, int val4) {super(val1,val2,val3,val4);}
public FilledRectangle (int val1, int val2, int val3, int val4, Color col) {super(val1,val2,val3,val4, col);}
public FilledRectangle (int val[]) {super(val);}
public FilledRectangle (int val[], Color col) {super(val, col);}

public void draw (Graphics g) {

g.setColor(getColor()); 

g.fillRect(getUpperLeftX(),getUpperLeftY(),getWidth(),getHeight());  }  }
Codice:
import java.awt.Color;
import java.awt.Graphics;

public class FilledOval extends BoundedShape {

public FilledOval () {super();}
public FilledOval (int val1, int val2, int val3, int val4) {super(val1,val2,val3,val4);}

public FilledOval (int val1, int val2, int val3, int val4, Color col) {super(val1,val2,val3,val4,col);}
public FilledOval (int val[]) {super(val);}
public FilledOval (int val[], Color col) {super(val,col);}
public void draw (Graphics g) {

g.setColor(getColor()); 

g.fillOval(getUpperLeftX(),getUpperLeftY(),getWidth(),getHeight());}

  }
Codice:
import java.awt.*; 
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;

public class Oval extends BoundedShape {

public Oval () {super();}
public Oval (int val1, int val2, int val3, int val4) {super(val1,val2,val3,val4);}

public Oval (int val1, int val2, int val3, int val4, Color col) {super(val1,val2,val3,val4,col);}
public Oval (int val[]) {super(val);}
public Oval (int val[], Color col) {super(val,col);}
public void draw (Graphics g) {

g.setColor(getColor()); 

g.drawOval(getUpperLeftX(),getUpperLeftY(),getWidth(),getHeight());}

}
Codice:
import java.awt.*; 
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;

public class Rectangle extends BoundedShape {


public Rectangle () {super();}
public Rectangle (int val1, int val2, int val3, int val4) {super(val1,val2,val3,val4);}
public Rectangle (int val1, int val2, int val3, int val4, Color col) {super(val1,val2,val3,val4, col);}
public Rectangle (int val[]) {super(val);}
public Rectangle (int val[], Color col) {super(val, col);}
public void draw (Graphics g) {

g.setColor(getColor()); 
g.drawRect(getUpperLeftX(),getUpperLeftY(),getWidth(),getHeight());}


}
Codice:
import java.awt.*; 
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;

public class FilledRectangle extends BoundedShape {

public FilledRectangle () {super();}
public FilledRectangle (int val1, int val2, int val3, int val4) {super(val1,val2,val3,val4);}
public FilledRectangle (int val1, int val2, int val3, int val4, Color col) {super(val1,val2,val3,val4, col);}
public FilledRectangle (int val[]) {super(val);}
public FilledRectangle (int val[], Color col) {super(val, col);}

public void draw (Graphics g) {

g.setColor(getColor()); 

g.fillRect(getUpperLeftX(),getUpperLeftY(),getWidth(),getHeight());  }  }
Codice:
import java.awt.*; 
import javax.swing.*;
import java.awt.Color;

import static java.lang.Math.*;

public abstract class BoundedShape extends MyShape {

public BoundedShape () {super();}

public BoundedShape (int val1, int val2, int val3, int val4) {super(val1,val2,val3,val4);}

public BoundedShape (int val1, int val2, int val3, int val4, Color col) {super(val1,val2,val3,val4, col);}
public BoundedShape (int val[]) {super(val); }
public BoundedShape (int val[], Color col) {super(val, col); }

public int getUpperLeftX() { return Math.min(getX1(), getX2()); }
public int getUpperLeftY() { return Math.min(getY1(), getY2()); }
public int getWidth() {int w=Math.abs(getX1() - getX2());
return w;}
public int getHeight() {int h=Math.abs(getY1() - getY2());
return h;}

}
Codice:
import java.awt.*; 
import javax.swing.*;
import java.io.Serializable;

public abstract class MyShape implements Serializable {
private int x1, x2, y1, y2;
private int pointCt = 0;
private int XYValues[] = new int[500];

private Color color=Color.WHITE;

public MyShape () {setX1(0); setY1(0); setX2(0); setY2(0);}
public MyShape (int val1, int val2, int val3, int val4) { setX1(val1); setY1(val2); setX2(val3); setY2(val4);}

public MyShape (int val1, int val2, int val3, int val4, int pointCt) { setX1(val1); setY1(val2); setX2(val3);setY2(val4); setPointCt(pointCt);}

public MyShape (int val1, int val2, int val3, int val4, Color col) { setX1(val1); setY1(val2); setX2(val3);setY2(val4); setColor(col);}


public MyShape (int vals[]) {setX1(vals[0]); setY1(vals[1]); setX2(vals[2]); setY2(vals[3]); }

public MyShape (int vals[], int pointCt) {setX1(vals[0]); setY1(vals[1]); setX2(vals[2]); setY2(vals[3]); setPointCt(pointCt); }

public MyShape (int vals[], Color col) {setX1(vals[0]); setY1(vals[1]); setX2(vals[2]); setY2(vals[3]);setColor(col); }

public void setX1(int val) {x1 = ( val >= 0 ? val : 0 );} 
public void setX2(int val) {x2 = ( val >= 0 ? val : 0 );}
public void setY1(int val) {y1 = ( val >= 0 ? val : 0 );} 
public void setY2(int val) {y2 = ( val >= 0 ? val : 0 );}
public void setPointCt(int pointCt) {pointCt = ( pointCt >= 0 ? pointCt : 0 );} 


public void setColor(Color col) {this.color = col;}
public Color getColor() {return color;}
public int getX1() {return x1;} 
public int getX2() {return x2;}
public int getY1() {return y1;} 
public int getY2() {return y2;}
public int getPointCt() {return pointCt;}
public abstract void draw (Graphics g);

}
Codice:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.EOFException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.util.NoSuchElementException;

public class ShapeDrawJFrame extends JFrame {	

private final int SHAPETYPES=6;	        
private int shapeType=0;	       
private String shapeTypes[]= {"Line","Oval", "Rectangle", "FilledOval", "FilledRectangle", "Polygon"};	
private int numShapes=0;	        
private int XYValues[] = new int[4];
private int xValues[] = {};
private int yValues[] = {};
private int pointCt = 0;   	
private MyShape[] shapes = new MyShape[100];     	              	
private JComboBox shapesComboBox;	
private JComboBox colorChoice;	        
private Container container;	       
private JPanel lowerRow;
private JPanel upperRow;
private JButton undoButton;  
private JLabel label;     
private Graphics dragGraphics;               
private Color dragColor;
private int startAngle;
private int arcAngle;
private ObjectOutputStream output;
private ObjectInputStream input;              

private final static int                            
BLACK = 0,                      
RED = 1,            // Some constants to make                           
GREEN = 2,          // the code more readable.                            
BLUE = 3,           // These numbers code for                          
CYAN = 4,           // the different drawing colors.                       
MAGENTA = 5,                        
YELLOW = 6,                            
ORANGE = 7,
PINK = 8,
GRAY = 9;
		
 private boolean beingDragged;
  private JButton save, load;  
  private JTextField fileName;

public ShapeDrawJFrame() {

super("Draw Shapes");		

// addMouseListener(handler);
//     addMouseMotionListener(handler);		
container = getContentPane();		
container.setBackground(new Color(255,255,255));
                           

lowerRow = new JPanel();
label = new JLabel("You have select the type of shape to draw:");
lowerRow.add(label);
		
shapesComboBox = new JComboBox(shapeTypes);		
shapesComboBox.setSelectedIndex(0);		
lowerRow.add(shapesComboBox); 
              
colorChoice = new JComboBox();				
colorChoice.addItem("Black");               
colorChoice.addItem("Red");               
colorChoice.addItem("Green");               
colorChoice.addItem("Blue");               
colorChoice.addItem("Cyan");               
colorChoice.addItem("Magenta");                
colorChoice.addItem("Yellow");                
colorChoice.addItem("Orange");
colorChoice.addItem("Pink"); 
colorChoice.addItem("Gray");              
colorChoice.setBackground(Color.white);                
lowerRow.add(colorChoice);            	



undoButton = new JButton("UNDO");
lowerRow.add(undoButton); 
			

container.add(lowerRow, BorderLayout.SOUTH); 

MouseHandler handler= new MouseHandler();
     addMouseListener(handler);
     addMouseMotionListener(handler);     


     upperRow = new JPanel();
     save = new JButton( "  Save " );
     upperRow.add(save);
     save.addActionListener(

         new ActionListener() 
         {
            public void actionPerformed( ActionEvent event )
            {
              openOutputFile();
              writeShapes();
              closeFile();


            } 
       } 
      ); 


     load = new JButton( "  Load " );
      upperRow.add(load);
     load.addActionListener(

         new ActionListener() 
         {
            public void actionPerformed( ActionEvent event )
            {
              openInputFile();
              readShapes();
              closeFile();
              repaint();

            } 
       } 
      );  

      fileName=new JTextField(15);
      upperRow.add(fileName); 

container.add(upperRow, BorderLayout.NORTH);
		
setSize(600,600); 	
setVisible( true );	

}

public void paint( Graphics g) {		
super.paint(g);		
for (int sp=0;sp< shapes.length ; sp++) {			
if(shapes[sp]!=null) {                               

//g.setColor(dragColor);			

shapes[sp].draw(g);	  }
  } 
 }		

public void createShape(int index) {		

numShapes++;		

switch (index) {			
case 0: shapes[numShapes] = new Line(XYValues,getCurrentColor()); break;			
case 1: shapes[numShapes] = new Oval(XYValues,getCurrentColor()); break;			
case 2: shapes[numShapes] = new Rectangle(XYValues,getCurrentColor()); break; 
case 3: shapes[numShapes] = new FilledOval(XYValues,getCurrentColor()); break;
case 4: shapes[numShapes] = new FilledRectangle(XYValues,getCurrentColor()); break;
case 5: shapes[numShapes] = new Polygon(XYValues,getCurrentColor()); break;
        }	
}        

private Color getCurrentColor() {              
// Check the colorChoice menu to find the currently               
// selected color, and return the appropriate color              
// object.        

int currentColor = colorChoice.getSelectedIndex();         
Color colorPlot=new Color(0,0,0);

 switch (currentColor) {           

case 0:  
colorPlot=Color.BLACK;  
break;                 

case 1:                 
colorPlot=Color.RED;  
break;                      

case 2:              
colorPlot=Color.GREEN;  
break; 

case 3:                
colorPlot=Color.BLUE;  
break; 

case 4:             
colorPlot=Color.CYAN;   
break;  

case 5:               
colorPlot=Color.MAGENTA;   
break;  

case 6:               
colorPlot=Color.YELLOW;   
break; 

case 7:               
colorPlot=Color.ORANGE;   
break;

case 8:               
colorPlot=Color.PINK;   
break;

case 9:               
colorPlot=Color.GRAY;   
break;

default:               
colorPlot=Color.BLACK;      
break; }  

return colorPlot;

}




private class MouseHandler implements MouseMotionListener, MouseListener{	

public void mousePressed (MouseEvent event) {           			

XYValues[0] = event.getX();			
XYValues[1] = event.getY();
                                                     

//dragGraphics = container.getGraphics();                               
//dragColor = getCurrentColor();                               
//dragGraphics.setColor(dragColor);    

  }		


public void mouseDragged(MouseEvent event)
     {
       XYValues[2]=event.getX();
       XYValues[3]=event.getY(); 
         


       createShape(shapesComboBox.getSelectedIndex());
       numShapes--;

       repaint();

     }

public void mouseReleased (MouseEvent event) {			

XYValues[2] = event.getX();			
XYValues[3] = event.getY(); 
                    
createShape(shapesComboBox.getSelectedIndex());                      

repaint( );        
     }


public void mouseEntered(MouseEvent event){}


     public void mouseClicked(MouseEvent event){}


     public void mouseExited(MouseEvent event){}     


     public void mouseMoved(MouseEvent event){}


  }
  

  public void openOutputFile()
  {
   
    
    try
    {
      output = new ObjectOutputStream(new FileOutputStream(fileName.getText()));
      
    }
    catch (IOException ioException )
    {
	System.err.println("error output opening file");

    }

  }


  public void openInputFile()
  {
   
    
    try
    {
      input = new ObjectInputStream(new FileInputStream(fileName.getText()));
      
    }
    catch (IOException ioException )
    {
	System.err.println("error input opening file");

    }

  }


  public void closeFile()
  {
    try
    {

      if(input != null)
         input.close();
      if(output != null)
         output.close();
    
    }
    catch (IOException ioException )
    {
	System.err.println("error closing file");
        System.exit(1);

    }

  }




  public void writeShapes()
  {
     for(int sp=0; sp<shapes.length;sp++)
     {
       try
       {
        if(shapes[sp]!=null)
        {
          output.writeObject(shapes[sp]);
        }
                    
       }
       catch (IOException ioException)
       {
         System.err.println("error writing to file");
         return;
       }   
       catch (NoSuchElementException elementException)
       {
         System.err.println("Invalid Input. Please try again");

       } 


     }

    }     


  public void readShapes()
  {

     for(int i=0;i<numShapes;i++) shapes[i]= null;
     numShapes =0;

     try
     {
        while(true)
        {
           shapes[numShapes] =  (MyShape) input.readObject();
           numShapes++;
        }
      }
      catch (EOFException endOfFileException)
      {
        return;

      } 
      catch (ClassNotFoundException classNotFoundException)
      {
        System.err.println("unable to create object");

      } 
      catch (IOException ioException)
      {
        System.err.println("error during read from file");
      } 

  }

 }
Codice:
import javax.swing.JFrame;

public class ShapeDraw

{

//execute application
public static void main(String args[]) {

ShapeDrawJFrame shapeDrawJFrame = new ShapeDrawJFrame();
shapeDrawJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

shapeDrawJFrame.setVisible( true );
}}
grazie ancora.
mariade è offline   Rispondi citando il messaggio o parte di esso
Old 15-04-2007, 15:21   #6
MEMon
Senior Member
 
Iscritto dal: Dec 2002
Messaggi: 3359
Non mi metto a guardare il codice ora, comunque ora ho capito.
Per quello che vuoi fare credo che puoi fare a meno del metodo drawPolygon visto che ti basta disegnare una serie di linee.
Per fare l'effetto che intendi te dovresti usare il metodo drawLine(int x1, int y1, int x2, int y2) per ogni coppia di punti che individui.

Qualche idea su come fare:
Utilizzi due array, uno per le X e uno per le Y, dove di volta in volta salvi il punto individuato dal mouse, ogni due punti(una linee è una coppia di punti infatti) disegni una linea prendendo gli ultimi due valori di ogni array, infatti avrai ad esempio dopo che hai selezionato due punti
Array di X: 50 , 70
Array di Y: 20 , 30
Prendi fuori i due punti che sono A(50 , 20) e B(70 , 30) e li utilizzi nel metodo g.drawLine(int x1, int y1, int x2, int y2).

Volendo invece degli array puoi utilizzare 4 variabili temporanee, ma meglio con gli array se magari ci vuoi fare altro dopo con questi punti.
Oppure utilizzare un array di punti.

Ultima modifica di MEMon : 15-04-2007 alle 15:28.
MEMon è offline   Rispondi citando il messaggio o parte di esso
Old 15-04-2007, 15:25   #7
MEMon
Senior Member
 
Iscritto dal: Dec 2002
Messaggi: 3359
Però così non diventa un vero e proprio poligono, ma una serie di linee, e decidi te quando "chiuderlo", se vuoi creare un vero e proprio poligono, fai sempre come prima ma quando decidi che il poligono è finito cancelli le linee che hai disegnato(basta che disegni un rettangolo del colore dello sfondo grande abbastanza da coprire le linee) e disegni il poligono vero e proprio utilizzando gli array che hai creato.
In questo modo è a tutti gli effetti un poligono vero e proprio.

ps.Se utilizzi solo linee puoi anche fare una cosa stile matita di paint.
pss.puoi dare il comando di chiusure col tasto destro del mouse.

Ultima modifica di MEMon : 15-04-2007 alle 15:31.
MEMon è offline   Rispondi citando il messaggio o parte di esso
Old 15-04-2007, 15:30   #8
mariade
Senior Member
 
L'Avatar di mariade
 
Iscritto dal: Jun 2005
Città: Swords, Dublino
Messaggi: 642
grazie per la risposta, spero di riuscirci.
se qualcuno ha altre idee....????
mariade è offline   Rispondi citando il messaggio o parte di esso
 Rispondi


Ecovacs Goat O1200 LiDAR Pro: la prova del robot tagliaerba con tagliabordi integrato Ecovacs Goat O1200 LiDAR Pro: la prova del robot...
Recensione Samsung Galaxy S26+: sfida l'Ultra, ma ha senso di esistere? Recensione Samsung Galaxy S26+: sfida l'Ultra, m...
Zeekr X e 7X provate: prezzi, autonomia fino a 615 km e ricarica in 13 minuti Zeekr X e 7X provate: prezzi, autonomia fino a 6...
Marathon: arriva il Fortnite hardcore Marathon: arriva il Fortnite hardcore
HP Imagine 2026: abbiamo visto HP IQ all’opera, ecco cosa può (e non può) fare HP Imagine 2026: abbiamo visto HP IQ all’opera, ...
Le 10 migliori offerte Amazon di Pasqua:...
Nuove fotografie dagli astronauti di Art...
La toilette della capsula Orion Integrit...
GeForce NOW: ecco tutte le novità in arr...
Il Realme 16 5G debutta sul mercato glob...
HONOR svela tre nuovi tablet: il più int...
Tineco Floor One S9 Master: aspira e pul...
Vivo X300 Ultra, il lancio globale è ini...
Offerte robot aspirapolvere Amazon: ECOV...
L'AI genera codice in 8 minuti e i senio...
Ring Intercom Audio a 44,99€ su Amazon: ...
Apple iPhone 16 crolla a 689€: ecco perc...
Google Pixel 9 a 449,90€ con caricatore ...
Ecco la top 7 delle offerte Amazon, aggi...
Ex ingegnere ammette il sabotaggio: migl...
Chromium
GPU-Z
OCCT
LibreOffice Portable
Opera One Portable
Opera One 106
CCleaner Portable
CCleaner Standard
Cpu-Z
Driver NVIDIA GeForce 546.65 WHQL
SmartFTP
Trillian
Google Chrome Portable
Google Chrome 120
VirtualBox
Tutti gli articoli Tutte le news Tutti i download

Strumenti

Regole
Non Puoi aprire nuove discussioni
Non Puoi rispondere ai messaggi
Non Puoi allegare file
Non Puoi modificare i tuoi messaggi

Il codice vB è On
Le Faccine sono On
Il codice [IMG] è On
Il codice HTML è Off
Vai al Forum


Tutti gli orari sono GMT +1. Ora sono le: 17:40.


Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Served by www3v