Torna indietro   Hardware Upgrade Forum > Software > Programmazione

Tre giorni in Finlandia con OnePlus Watch 2 Nordic Blue. La nostra prova a temperature estreme
Tre giorni in Finlandia con OnePlus Watch 2 Nordic Blue. La nostra prova a temperature estreme
Siamo volati a Helsinki, in Finlandia, per testare a fondo il nuovo OnePlus Watch 2 Nordic Blue Edition. L'orologio ci ha convinti durante gli i test invernali ad Helsinki, grazie al design raffinato, alle prestazioni impeccabili, alla resistenza agli ambienti estremi e all'ottima autonomia garantita dalla modalità intelligente.
Lenovo Factory Tour: siamo entrati nella fabbrica ungherese che produce PC, storage e server
Lenovo Factory Tour: siamo entrati nella fabbrica ungherese che produce PC, storage e server
Edge9 ha visitato lo stabilimento produttivo di Lenovo nei pressi di Budapest in Ungheria, che serve tutta la zona EMEA per i prodotti “business”: PC, storage e server. Un impianto all’avanguardia, con altissimi tassi di efficienza ma anche una grande attenzione alle condizioni lavorative dei dipendenti e alla sostenibilità ambientale
Acer Nitro V 15, alla prova il notebook gaming essenziale con RTX 4050 Laptop
Acer Nitro V 15, alla prova il notebook gaming essenziale con RTX 4050 Laptop
Acer Nitro V 15 è un notebook gaming che punta sul rapporto prezzo-prestazioni per garantire a chi ha un budget intorno o persino inferiore ai 1000€ di giocare abbastanza bene in Full HD grazie alla RTX 4050 Laptop di NVIDIA e la compatibilità con il DLSS 3.
Tutti gli articoli Tutte le news

Vai al Forum
Rispondi
 
Strumenti
Old 01-02-2011, 14:53   #1
Matrixbob
Senior Member
 
L'Avatar di Matrixbob
 
Iscritto dal: Jul 2001
Messaggi: 9945
[JAVA] Posso compilare ed eseguire questa applet fuori dal browser?

Transmission versus Propagation Delay

Codice:
///////////////////////////////////////
//LineSimApllet
//written by David Grangier, Institut Eurecom, France
//david.grangier@eurecom.fr
///////////////////////////////////////

package linesim;
//imports
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.applet.*;
import java.util.*;

//Applet Class
public class LineSimApplet extends Applet {
  //buttons
  Button start=new Button ("Start");
  Button stop=new Button ("Reset");
  //features lists
  MyChoice length=new MyChoice(new String[] {"10 km","100 km","1000 km"},new double[] {10E3,100E3,1E6},3);
  MyChoice rate=new MyChoice(new String[] {"512 kps","1 Mbps","10 Mbps","100 Mbps"},new double[] {512E3,1E6,10E6,100E6},2);
  MyChoice size=new MyChoice(new String[] {"100 Bytes","500 Bytes","1 kBytes"},new double[] {8E2,4E3,8E3},1);
  //to simulate time
  Thread timerThread;
  TickTask timerTask;
  boolean simulationRunning=false;
  //communication line
  Line myLine;

  public void init() {
    try {
      setBackground(Color.white);
      add(new Label ("Length",Label.RIGHT));
      add(length);
      add(new Label("Rate",Label.RIGHT));
      add(rate);
      add(new Label("Packet size",Label.RIGHT));
      add(size);
      //start
      start.addActionListener(
        new ActionListener()
        {
          public void actionPerformed (ActionEvent event)
          {
            launchSim();
          }
        });
      add(start);
      //stop
      Button stop=new Button ("Reset");
      stop.addActionListener(
        new ActionListener()
        {
          public void actionPerformed (ActionEvent event)
          {
            stopSim();
            //clear line
            myLine.sendTime(0);
            //redraw cleared line
            LineSimApplet.this.repaint();
          }
        });
      add(stop);
      //line
      myLine= new Line(40,50,450,10);
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }

  public void paint (Graphics g)
  {
    update(g); // eliminate flashing : update is overriden
  }

  public void update (Graphics g)
  { //work on a offscreen image

    Dimension offDimension = getSize();
    Image offImage = createImage(offDimension.width, offDimension.height);
    Graphics offGraphics = offImage.getGraphics();
    myLine.drawLine(offGraphics);

    //sender
    offGraphics.setColor(Color.blue);
    offGraphics.fillRect(10,40,30,30);
    offGraphics.setColor(Color.black);
    offGraphics.drawString("Sender",5,90);
    offGraphics.drawRect(10,40,30,30);

    //receiver
    offGraphics.setColor(Color.blue);
    offGraphics.fillRect(490,40,30,30);
    offGraphics.setColor(Color.black);
    offGraphics.drawString("Receiver",485,90);
    offGraphics.drawRect(490,40,30,30);

    offGraphics.drawString("Propagation speed : 2.8 x 10^8 m/sec",175,105);
    //display offscreen image
    g.drawImage(offImage, 0, 0, this);
  }

  private void launchSim()
  {
    setupEnabled(false);
    //setup line
    myLine.setup(length.getVal(), rate.getVal() );
    myLine.emitPacket(size.getVal(),0);
    //setup timer
    timerTask=new TickTask(1E-5,myLine.totalTime());
    timerThread=new Thread(timerTask);
    //start simulation
    simulationRunning=true;
    timerThread.start();
  }

  private void stopSim()
  {
    timerTask.endNow();
    simulationRunning=false;
    setupEnabled(true);
  }

  public void setupEnabled(boolean value)
  {
    start.setEnabled(value);
    length.setEnabled(value);
    rate.setEnabled(value);
    size.setEnabled(value);
  }

  //my choice
  class MyChoice extends Choice
  {
    private double vals[];

    public MyChoice(String items[], double values[],int defaultValue)
    {
      for (int i=0; i<items.length;i++) {super.addItem(items[i]);}
      vals=values;
      select(defaultValue-1);
    }

    public double getVal() {return  vals[super.getSelectedIndex()];}
  }
  //tickTask
  class TickTask implements Runnable
  {
    private double counter;
    private double length;
    private double tick;

    public TickTask(double t,double l)
    {
      length=l;
      tick=t;
      counter=0;
    }

    public void run()
    {
      while (LineSimApplet.this.simulationRunning)
      {
        counter+=tick;
        LineSimApplet.this.myLine.sendTime(counter);
        LineSimApplet.this.repaint();
        if (counter>=length)
        {
          LineSimApplet.this.myLine.clearPackets();
          LineSimApplet.this.timerThread.suspend();
        }
        try  {LineSimApplet.this.timerThread.sleep(50);} catch (Exception e) { }
      }
    }

    public void endNow() {
      length=counter;
    }
  }
}

//Line class
class Line
{
  //graphic variables
  private int gX;
  private int gY;
  private int gWidth;
  private int gHeight;
  //characteristic variables
  final double celerity = 2.8E+8;
  private double length;
  private double rate;
  //simulation variables
  private double time;
  private Packet myPacket;

  public Line(int x, int y, int w, int h)
  {
    //graphic init
    gX=x;
    gY=y;
    gWidth=w;
    gHeight=h;
  }

  public void setup(double l, double r)
  {
    length=l;
    rate=r;
  }

  void sendTime(double now)
  {
    time=now; //update time
    removeReceivedPackets(now);
  }

  void emitPacket(double s, double eT)
  {
    myPacket= new Packet(s,eT);
  }

  private void removeReceivedPackets(double now)
  {
    if (!(myPacket==null))
    {
      if ( now>myPacket.emissionTime+(myPacket.size/rate)+length*celerity )
      {
          clearPackets();
      }
    }
  }

  public void clearPackets()
  {
    myPacket=null;
  }

  public double totalTime()
  {
    double emmissionTime=(myPacket.size/rate);
    double onLineTime=(length/celerity);
    return (emmissionTime+onLineTime);
  }

  public void drawLine(Graphics g)
  {
    g.setColor(Color.white);
    g.fillRect(gX,gY+1,gWidth,gHeight-2);
    g.setColor(Color.black);
    g.drawRect(gX,gY,gWidth,gHeight);
    g.setColor(Color.red);
    g.drawString(timeToString(time),gX+gWidth/2-10,gY+gHeight+15);
    drawPackets(g);
  }

  private void drawPackets(Graphics g)
  {
    if (!(myPacket==null))
    {
      double xfirst;
      double xlast;
      //compute time units
      xfirst=time-myPacket.emissionTime;
      xlast=xfirst-(myPacket.size/rate);
      //compute position
      xfirst=xfirst*celerity*gWidth/length;
      xlast=xlast*celerity*gWidth/length;
      if (xlast<0) {xlast=0;}
      if (xfirst>gWidth ) {xfirst=gWidth;}
      //draw
      g.setColor(Color.red);
      g.fillRect(gX+(int)(xlast),gY+1,(int)(xfirst-xlast),gHeight-2);
    }
  }

  static private String timeToString(double now)
  {
    String res=Double.toString(now*1000);
    int dot=res.indexOf('.');
    String deci=res.substring(dot+1)+"000";
    deci=deci.substring(0,3);
    String inte=res.substring(0,dot);
    return inte+"."+deci+" ms";
  }
}

class Packet
{
  double size;
  double emissionTime;

  Packet(double s, double eT)
  {
    size=s;
    emissionTime=eT;
  }
}
__________________
Aiuta la ricerca col tuo PC: >>Calcolo distribuito BOINC.Italy: unisciti anche tu<<
Più largo è il sorriso, più affilato è il coltello.
Matrixbob è offline   Rispondi citando il messaggio o parte di esso
Old 01-02-2011, 14:57   #2
Matrixbob
Senior Member
 
L'Avatar di Matrixbob
 
Iscritto dal: Jul 2001
Messaggi: 9945
Forse splittando le classi del file sorgente e usando AppletViewer potrei riuscire, dico questo perchè ho visto che manca un metodo d'ingresso main?
__________________
Aiuta la ricerca col tuo PC: >>Calcolo distribuito BOINC.Italy: unisciti anche tu<<
Più largo è il sorriso, più affilato è il coltello.

Ultima modifica di Matrixbob : 01-02-2011 alle 14:59.
Matrixbob è offline   Rispondi citando il messaggio o parte di esso
Old 02-02-2011, 12:15   #3
Matrixbob
Senior Member
 
L'Avatar di Matrixbob
 
Iscritto dal: Jul 2001
Messaggi: 9945
up
__________________
Aiuta la ricerca col tuo PC: >>Calcolo distribuito BOINC.Italy: unisciti anche tu<<
Più largo è il sorriso, più affilato è il coltello.
Matrixbob è offline   Rispondi citando il messaggio o parte di esso
Old 02-02-2011, 14:02   #4
PGI-Bis
Senior Member
 
L'Avatar di PGI-Bis
 
Iscritto dal: Nov 2004
Città: Tra Verona e Mantova
Messaggi: 4553
L'applet in questione non usa i metodi di connessione al browser quindi puoi tranquillamente considerarlo come un qualsiasi componente awt, con l'unica particolarità del ciclo vitale. Vale a dire che se scrivi:

Applet applet = new LineSimApplet();
Frame frame = new Frame();
frame.add(applet);
applet.init();
applet.start();
frame.setSize(800, 600);
frame.setVisible(true);

Hai la tua applet in finestra. Un test completo apparentemente funzionante è:

Codice:
import java.awt.*;
import java.awt.event.*;

public class Main {

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
		
			public void run() {
				final LineSimApplet applet = new LineSimApplet();
				applet.init();
				final Frame frame = new Frame("Wrapper");
				frame.add(applet);
				frame.addWindowListener(new WindowAdapter() {
					
					public void windowOpened(WindowEvent e) {
						applet.start();
					}
					
					public void windowClosing(WindowEvent e) {
						applet.stop();
						applet.destroy();
						frame.dispose();
						Thread killer = new Thread() {
							public void run() {
								try {
									Thread.sleep(2000);
									System.exit(0);
								} catch(Exception ex) {}
							}
						};
						killer.setDaemon(true);
						killer.start();
					}
				});
				frame.pack();
				frame.setSize(frame.getWidth(), 600);
				frame.setVisible(true);
			}	
		});
	}
}
PGI-Bis è offline   Rispondi citando il messaggio o parte di esso
Old 10-02-2011, 15:53   #5
Matrixbob
Senior Member
 
L'Avatar di Matrixbob
 
Iscritto dal: Jul 2001
Messaggi: 9945
Mi da errore:
Codice:
Main.java:10: cannot find symbol
symbol: class LineSimApplet
				final LineSimApplet applet = new LineSimApplet();
				      ^
Main.java:10: cannot find symbol
symbol: class LineSimApplet
				final LineSimApplet applet = new LineSimApplet();
				                                 ^
2 errors
Ma devo splittare tutte le classi ognuna in un file come JavaDoc insegna?
Dico questo perchè quel file che ho postato è un file omnicomprensivo.
__________________
Aiuta la ricerca col tuo PC: >>Calcolo distribuito BOINC.Italy: unisciti anche tu<<
Più largo è il sorriso, più affilato è il coltello.

Ultima modifica di Matrixbob : 10-02-2011 alle 16:03.
Matrixbob è offline   Rispondi citando il messaggio o parte di esso
Old 10-02-2011, 16:24   #6
PGI-Bis
Senior Member
 
L'Avatar di PGI-Bis
 
Iscritto dal: Nov 2004
Città: Tra Verona e Mantova
Messaggi: 4553
50 frustate per l'uso del termine "splittare", ridotte a 25 per "omnicomprensivo".


Non è necessario separare i tipi top level dichiarati nell'unità di compilazione LineSimApplet.java - la lingua permette l'esistenza di più tipi top level nella stessa unità di compilazione purchè uno solo tra essi sia pubblico.

Aggiungi tra gli import di "Main.java":

import linesim.LineSimApplet

Oppure imposta il package di Main a "linesim". O rimuovi il package da LineSimApplet. Puoi anche impacchettare tutto in una sola unità di compilazione, senza package.

Codice:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Main {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                final LineSimApplet applet = new LineSimApplet();
                applet.init();
                final Frame frame = new Frame("Wrapper");
                frame.add(applet);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowOpened(WindowEvent e) {
                        applet.start();
                    }

                    public void windowClosing(WindowEvent e) {
                        applet.stop();
                        applet.destroy();
                        frame.dispose();
                        Thread killer = new Thread() {

                            public void run() {
                                try {
                                    Thread.sleep(2000);
                                    System.exit(0);
                                } catch (Exception ex) {
                                }
                            }
                        };
                        killer.setDaemon(true);
                        killer.start();
                    }
                });
                frame.pack();
                frame.setSize(frame.getWidth(), 600);
                frame.setVisible(true);
            }
        });
    }
}

class LineSimApplet extends Applet {
    //buttons

    Button start = new Button("Start");
    Button stop = new Button("Reset");
    //features lists
    MyChoice length = new MyChoice(new String[]{"10 km", "100 km", "1000 km"}, new double[]{10E3, 100E3, 1E6}, 3);
    MyChoice rate = new MyChoice(new String[]{"512 kps", "1 Mbps", "10 Mbps", "100 Mbps"}, new double[]{512E3, 1E6, 10E6, 100E6}, 2);
    MyChoice size = new MyChoice(new String[]{"100 Bytes", "500 Bytes", "1 kBytes"}, new double[]{8E2, 4E3, 8E3}, 1);
    //to simulate time
    Thread timerThread;
    TickTask timerTask;
    boolean simulationRunning = false;
    //communication line
    Line myLine;

    public void init() {
        try {
            setBackground(Color.white);
            add(new Label("Length", Label.RIGHT));
            add(length);
            add(new Label("Rate", Label.RIGHT));
            add(rate);
            add(new Label("Packet size", Label.RIGHT));
            add(size);
            //start
            start.addActionListener(
                    new ActionListener() {

                        public void actionPerformed(ActionEvent event) {
                            launchSim();
                        }
                    });
            add(start);
            //stop
            Button stop = new Button("Reset");
            stop.addActionListener(
                    new ActionListener() {

                        public void actionPerformed(ActionEvent event) {
                            stopSim();
                            //clear line
                            myLine.sendTime(0);
                            //redraw cleared line
                            LineSimApplet.this.repaint();
                        }
                    });
            add(stop);
            //line
            myLine = new Line(40, 50, 450, 10);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void paint(Graphics g) {
        update(g); // eliminate flashing : update is overriden
    }

    public void update(Graphics g) { //work on a offscreen image

        Dimension offDimension = getSize();
        Image offImage = createImage(offDimension.width, offDimension.height);
        Graphics offGraphics = offImage.getGraphics();
        myLine.drawLine(offGraphics);

        //sender
        offGraphics.setColor(Color.blue);
        offGraphics.fillRect(10, 40, 30, 30);
        offGraphics.setColor(Color.black);
        offGraphics.drawString("Sender", 5, 90);
        offGraphics.drawRect(10, 40, 30, 30);

        //receiver
        offGraphics.setColor(Color.blue);
        offGraphics.fillRect(490, 40, 30, 30);
        offGraphics.setColor(Color.black);
        offGraphics.drawString("Receiver", 485, 90);
        offGraphics.drawRect(490, 40, 30, 30);

        offGraphics.drawString("Propagation speed : 2.8 x 10^8 m/sec", 175, 105);
        //display offscreen image
        g.drawImage(offImage, 0, 0, this);
    }

    private void launchSim() {
        setupEnabled(false);
        //setup line
        myLine.setup(length.getVal(), rate.getVal());
        myLine.emitPacket(size.getVal(), 0);
        //setup timer
        timerTask = new TickTask(1E-5, myLine.totalTime());
        timerThread = new Thread(timerTask);
        //start simulation
        simulationRunning = true;
        timerThread.start();
    }

    private void stopSim() {
        timerTask.endNow();
        simulationRunning = false;
        setupEnabled(true);
    }

    public void setupEnabled(boolean value) {
        start.setEnabled(value);
        length.setEnabled(value);
        rate.setEnabled(value);
        size.setEnabled(value);
    }

    //my choice
    class MyChoice extends Choice {

        private double vals[];

        public MyChoice(String items[], double values[], int defaultValue) {
            for (int i = 0; i < items.length; i++) {
                super.addItem(items[i]);
            }
            vals = values;
            select(defaultValue - 1);
        }

        public double getVal() {
            return vals[super.getSelectedIndex()];
        }
    }
    //tickTask

    class TickTask implements Runnable {

        private double counter;
        private double length;
        private double tick;

        public TickTask(double t, double l) {
            length = l;
            tick = t;
            counter = 0;
        }

        public void run() {
            while (LineSimApplet.this.simulationRunning) {
                counter += tick;
                LineSimApplet.this.myLine.sendTime(counter);
                LineSimApplet.this.repaint();
                if (counter >= length) {
                    LineSimApplet.this.myLine.clearPackets();
                    LineSimApplet.this.timerThread.suspend();
                }
                try {
                    LineSimApplet.this.timerThread.sleep(50);
                } catch (Exception e) {
                }
            }
        }

        public void endNow() {
            length = counter;
        }
    }
}

//Line class
class Line {
    //graphic variables

    private int gX;
    private int gY;
    private int gWidth;
    private int gHeight;
    //characteristic variables
    final double celerity = 2.8E+8;
    private double length;
    private double rate;
    //simulation variables
    private double time;
    private Packet myPacket;

    public Line(int x, int y, int w, int h) {
        //graphic init
        gX = x;
        gY = y;
        gWidth = w;
        gHeight = h;
    }

    public void setup(double l, double r) {
        length = l;
        rate = r;
    }

    void sendTime(double now) {
        time = now; //update time
        removeReceivedPackets(now);
    }

    void emitPacket(double s, double eT) {
        myPacket = new Packet(s, eT);
    }

    private void removeReceivedPackets(double now) {
        if (!(myPacket == null)) {
            if (now > myPacket.emissionTime + (myPacket.size / rate) + length * celerity) {
                clearPackets();
            }
        }
    }

    public void clearPackets() {
        myPacket = null;
    }

    public double totalTime() {
        double emmissionTime = (myPacket.size / rate);
        double onLineTime = (length / celerity);
        return (emmissionTime + onLineTime);
    }

    public void drawLine(Graphics g) {
        g.setColor(Color.white);
        g.fillRect(gX, gY + 1, gWidth, gHeight - 2);
        g.setColor(Color.black);
        g.drawRect(gX, gY, gWidth, gHeight);
        g.setColor(Color.red);
        g.drawString(timeToString(time), gX + gWidth / 2 - 10, gY + gHeight + 15);
        drawPackets(g);
    }

    private void drawPackets(Graphics g) {
        if (!(myPacket == null)) {
            double xfirst;
            double xlast;
            //compute time units
            xfirst = time - myPacket.emissionTime;
            xlast = xfirst - (myPacket.size / rate);
            //compute position
            xfirst = xfirst * celerity * gWidth / length;
            xlast = xlast * celerity * gWidth / length;
            if (xlast < 0) {
                xlast = 0;
            }
            if (xfirst > gWidth) {
                xfirst = gWidth;
            }
            //draw
            g.setColor(Color.red);
            g.fillRect(gX + (int) (xlast), gY + 1, (int) (xfirst - xlast), gHeight - 2);
        }
    }

    static private String timeToString(double now) {
        String res = Double.toString(now * 1000);
        int dot = res.indexOf('.');
        String deci = res.substring(dot + 1) + "000";
        deci = deci.substring(0, 3);
        String inte = res.substring(0, dot);
        return inte + "." + deci + " ms";
    }
}

class Packet {

    double size;
    double emissionTime;

    Packet(double s, double eT) {
        size = s;
        emissionTime = eT;
    }
}
Ovviamente al solo fine di provare il programma: in un contesto reale un sorgente del genere merita all'autore lo strappo delle unghie.
PGI-Bis è offline   Rispondi citando il messaggio o parte di esso
Old 17-02-2011, 15:23   #7
Matrixbob
Senior Member
 
L'Avatar di Matrixbob
 
Iscritto dal: Jul 2001
Messaggi: 9945
edit: problemi di linea
__________________
Aiuta la ricerca col tuo PC: >>Calcolo distribuito BOINC.Italy: unisciti anche tu<<
Più largo è il sorriso, più affilato è il coltello.

Ultima modifica di Matrixbob : 17-02-2011 alle 16:15.
Matrixbob è offline   Rispondi citando il messaggio o parte di esso
Old 17-02-2011, 15:30   #8
Matrixbob
Senior Member
 
L'Avatar di Matrixbob
 
Iscritto dal: Jul 2001
Messaggi: 9945
Quote:
Originariamente inviato da PGI-Bis Guarda i messaggi
50 frustate per l'uso del termine "splittare", ridotte a 25 per "omnicomprensivo".


Non è necessario separare i tipi top level dichiarati nell'unità di compilazione LineSimApplet.java - la lingua permette l'esistenza di più tipi top level nella stessa unità di compilazione purchè uno solo tra essi sia pubblico.

Aggiungi tra gli import di "Main.java":

import linesim.LineSimApplet

Oppure imposta il package di Main a "linesim". O rimuovi il package da LineSimApplet. Puoi anche impacchettare tutto in una sola unità di compilazione, senza package.

Codice:
package linesim;

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class UsaLineSim {

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {

			public void run() {
				final LineSimApplet applet = new LineSimApplet();
				applet.init();
				final Frame frame = new Frame("Wrapper");
				frame.add(applet);
				frame.addWindowListener(new WindowAdapter() {

					public void windowOpened(WindowEvent e) {
						applet.start();
					}

					public void windowClosing(WindowEvent e) {
						applet.stop();
						applet.destroy();
						frame.dispose();
						Thread killer = new Thread() {

							public void run() {
								try {
									Thread.sleep(2000);
									System.exit(0);
								} catch (Exception ex) {
								}
							}
						};
						killer.setDaemon(true);
						killer.start();
					}
				});
				frame.pack();
				frame.setSize(frame.getWidth(), 600);
				frame.setVisible(true);
			}
		});
	}
}

class LineSimApplet extends Applet {
	// buttons

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Button start = new Button("Start");
	Button stop = new Button("Reset");
	// features lists
	MyChoice length = new MyChoice(
			new String[] { "10 km", "100 km", "1000 km" }, new double[] { 10E3,
					100E3, 1E6 }, 3);
	MyChoice rate = new MyChoice(new String[] { "512 kps", "1 Mbps", "10 Mbps",
			"100 Mbps" }, new double[] { 512E3, 1E6, 10E6, 100E6 }, 2);
	MyChoice size = new MyChoice(new String[] { "100 Bytes", "500 Bytes",
			"1 kBytes" }, new double[] { 8E2, 4E3, 8E3 }, 1);
	// to simulate time
	Thread timerThread;
	TickTask timerTask;
	boolean simulationRunning = false;
	// communication line
	Line myLine;

	public void init() {
		try {
			setBackground(Color.white);
			add(new Label("Length", Label.RIGHT));
			add(length);
			add(new Label("Rate", Label.RIGHT));
			add(rate);
			add(new Label("Packet size", Label.RIGHT));
			add(size);
			// start
			start.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent event) {
					launchSim();
				}
			});
			add(start);
			// stop
			Button stop = new Button("Reset");
			stop.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent event) {
					stopSim();
					// clear line
					myLine.sendTime(0);
					// redraw cleared line
					LineSimApplet.this.repaint();
				}
			});
			add(stop);
			// line
			myLine = new Line(40, 50, 450, 10);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void paint(Graphics g) {
		update(g); // eliminate flashing : update is overriden
	}

	public void update(Graphics g) { // work on a offscreen image

		Dimension offDimension = getSize();
		Image offImage = createImage(offDimension.width, offDimension.height);
		Graphics offGraphics = offImage.getGraphics();
		myLine.drawLine(offGraphics);

		// sender
		offGraphics.setColor(Color.blue);
		offGraphics.fillRect(10, 40, 30, 30);
		offGraphics.setColor(Color.black);
		offGraphics.drawString("Sender", 5, 90);
		offGraphics.drawRect(10, 40, 30, 30);

		// receiver
		offGraphics.setColor(Color.blue);
		offGraphics.fillRect(490, 40, 30, 30);
		offGraphics.setColor(Color.black);
		offGraphics.drawString("Receiver", 485, 90);
		offGraphics.drawRect(490, 40, 30, 30);

		offGraphics
				.drawString("Propagation speed : 2.8 x 10^8 m/sec", 175, 105);
		// display offscreen image
		g.drawImage(offImage, 0, 0, this);
	}

	private void launchSim() {
		setupEnabled(false);
		// setup line
		myLine.setup(length.getVal(), rate.getVal());
		myLine.emitPacket(size.getVal(), 0);
		// setup timer
		timerTask = new TickTask(1E-5, myLine.totalTime());
		timerThread = new Thread(timerTask);
		// start simulation
		simulationRunning = true;
		timerThread.start();
	}

	private void stopSim() {
		timerTask.endNow();
		simulationRunning = false;
		setupEnabled(true);
	}

	public void setupEnabled(boolean value) {
		start.setEnabled(value);
		length.setEnabled(value);
		rate.setEnabled(value);
		size.setEnabled(value);
	}

	// my choice
	class MyChoice extends Choice {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private double vals[];

		public MyChoice(String items[], double values[], int defaultValue) {
			for (int i = 0; i < items.length; i++) {
				super.addItem(items[i]);
			}
			vals = values;
			select(defaultValue - 1);
		}

		public double getVal() {
			return vals[super.getSelectedIndex()];
		}
	}

	// tickTask

	class TickTask implements Runnable {

		private double counter;
		private double length;
		private double tick;

		public TickTask(double t, double l) {
			length = l;
			tick = t;
			counter = 0;
		}

		@SuppressWarnings( { "deprecation", "static-access" })
		public void run() {
			while (LineSimApplet.this.simulationRunning) {
				counter += tick;
				LineSimApplet.this.myLine.sendTime(counter);
				LineSimApplet.this.repaint();
				if (counter >= length) {
					LineSimApplet.this.myLine.clearPackets();
					LineSimApplet.this.timerThread.suspend();
				}
				try {
					LineSimApplet.this.timerThread.sleep(50);
				} catch (Exception e) {
				}
			}
		}

		public void endNow() {
			length = counter;
		}
	}
}

// Line class
class Line {
	// graphic variables

	private int gX;
	private int gY;
	private int gWidth;
	private int gHeight;
	// characteristic variables
	final double celerity = 2.8E+8;
	private double length;
	private double rate;
	// simulation variables
	private double time;
	private Packet myPacket;

	public Line(int x, int y, int w, int h) {
		// graphic init
		gX = x;
		gY = y;
		gWidth = w;
		gHeight = h;
	}

	public void setup(double l, double r) {
		length = l;
		rate = r;
	}

	void sendTime(double now) {
		time = now; // update time
		removeReceivedPackets(now);
	}

	void emitPacket(double s, double eT) {
		myPacket = new Packet(s, eT);
	}

	private void removeReceivedPackets(double now) {
		if (!(myPacket == null)) {
			if (now > myPacket.emissionTime + (myPacket.size / rate) + length
					* celerity) {
				clearPackets();
			}
		}
	}

	public void clearPackets() {
		myPacket = null;
	}

	public double totalTime() {
		double emmissionTime = (myPacket.size / rate);
		double onLineTime = (length / celerity);
		return (emmissionTime + onLineTime);
	}

	public void drawLine(Graphics g) {
		g.setColor(Color.white);
		g.fillRect(gX, gY + 1, gWidth, gHeight - 2);
		g.setColor(Color.black);
		g.drawRect(gX, gY, gWidth, gHeight);
		g.setColor(Color.red);
		g.drawString(timeToString(time), gX + gWidth / 2 - 10, gY + gHeight
				+ 15);
		drawPackets(g);
	}

	private void drawPackets(Graphics g) {
		if (!(myPacket == null)) {
			double xfirst;
			double xlast;
			// compute time units
			xfirst = time - myPacket.emissionTime;
			xlast = xfirst - (myPacket.size / rate);
			// compute position
			xfirst = xfirst * celerity * gWidth / length;
			xlast = xlast * celerity * gWidth / length;
			if (xlast < 0) {
				xlast = 0;
			}
			if (xfirst > gWidth) {
				xfirst = gWidth;
			}
			// draw
			g.setColor(Color.red);
			g.fillRect(gX + (int) (xlast), gY + 1, (int) (xfirst - xlast),
					gHeight - 2);
		}
	}

	static private String timeToString(double now) {
		String res = Double.toString(now * 1000);
		int dot = res.indexOf('.');
		String deci = res.substring(dot + 1) + "000";
		deci = deci.substring(0, 3);
		String inte = res.substring(0, dot);
		return inte + "." + deci + " ms";
	}
}

class Packet {

	double size;
	double emissionTime;

	Packet(double s, double eT) {
		size = s;
		emissionTime = eT;
	}
}
Ovviamente al solo fine di provare il programma: in un contesto reale un sorgente del genere merita all'autore lo strappo delle unghie.
Cavolo funziona!
Perchè meriterebbe lo strappo delle unghie il programmatore autore?
__________________
Aiuta la ricerca col tuo PC: >>Calcolo distribuito BOINC.Italy: unisciti anche tu<<
Più largo è il sorriso, più affilato è il coltello.

Ultima modifica di Matrixbob : 17-02-2011 alle 16:15.
Matrixbob è offline   Rispondi citando il messaggio o parte di esso
Old 17-02-2011, 15:36   #9
PGI-Bis
Senior Member
 
L'Avatar di PGI-Bis
 
Iscritto dal: Nov 2004
Città: Tra Verona e Mantova
Messaggi: 4553
Lo strappo deriva da una violazione del bon-ton e da un problema di specifiche.

Convenzionalmente - e in java le convenzioni sono materia quasi religiosa - le unità di compilazione contengono sempre solo un tipo top-level (cioè una classe, interfaccia o enumerativo non contenuto in un altro tipo).

Il problema tecnico sta nella mancanza del package perchè le specifiche dichiarano che l'assenza di una dichiarazione di package rende il tipo dichiarato membro di un package liberamente decidibile dalla concreta implementazione della piattaforma java, non necessariamente sempre lo stesso. Sebbene l'implementazione di Sun-Oracle preveda un package ad hoc, che è sempre quello dal 1600 a.C., nulla vieta, ad esempio, che un'implementazione a fronte di due tipi aventi lo stesso nome appartenenti al package "innominato" vengano infilati in spazi dei nomi diversi.

In sostanza, quando omettiamo la dichiarazione di package facciamo affidamento ad una convenzione di un'implementazione di Java e non della piattaforma Java in senso stretto.
PGI-Bis è offline   Rispondi citando il messaggio o parte di esso
Old 17-02-2011, 16:41   #10
Matrixbob
Senior Member
 
L'Avatar di Matrixbob
 
Iscritto dal: Jul 2001
Messaggi: 9945
Se vedi sopra ho modificato come mi consigliava Eclipse il codice.
Ma Java non vuole 1 classe 1 file scusa?
Come hai fatto a produrre quel main?
__________________
Aiuta la ricerca col tuo PC: >>Calcolo distribuito BOINC.Italy: unisciti anche tu<<
Più largo è il sorriso, più affilato è il coltello.
Matrixbob è offline   Rispondi citando il messaggio o parte di esso
Old 17-02-2011, 17:00   #11
PGI-Bis
Senior Member
 
L'Avatar di PGI-Bis
 
Iscritto dal: Nov 2004
Città: Tra Verona e Mantova
Messaggi: 4553
No, puoi dichiarare quanti tipi vuoi, purche uno solo tra quelli non contenuti in altri tipi sia pubblico. Cioè puoi tranquillamente dire:

Codice:
//Pippo.java
class Giovannone {}

class Main {}

class Cocoricò {}
Oppure:

Codice:
//Pippo.java
public class Pippo {}

class Giovannone {}
class Main {}
class Cocoricò {}
"Tranquillamente" dal punto di vista meccanico. Poi c'è la convenzione un file, un tipo con lo stesso nome del file, che è nel dna del programmatore java e viene sempre rispettata. Ma è una convenzione.
PGI-Bis è offline   Rispondi citando il messaggio o parte di esso
 Rispondi


Tre giorni in Finlandia con OnePlus Watch 2 Nordic Blue. La nostra prova a temperature estreme Tre giorni in Finlandia con OnePlus Watch 2 Nord...
Lenovo Factory Tour: siamo entrati nella fabbrica ungherese che produce PC, storage e server Lenovo Factory Tour: siamo entrati nella fabbric...
Acer Nitro V 15, alla prova il notebook gaming essenziale con RTX 4050 Laptop Acer Nitro V 15, alla prova il notebook gaming e...
Stellar Blade: l'action RPG di Shift Up sfoggia uno stile (quasi) unico su PS5 - Recensione Stellar Blade: l'action RPG di Shift Up sfoggia ...
Recensione Zenfone 11 Ultra: il flagship ASUS ritorna a essere un 'padellone' Recensione Zenfone 11 Ultra: il flagship ASUS ri...
La Cina ha lanciato la missione Chang'e-...
In Cina è stata varata una nave portacon...
Laowa espande gli innesti: arrivano le o...
Amazfit Bip 5 Unity arriva in Italia! Pr...
La Commissione UE accusa: "SAIC, Ge...
4 NAS con prezzi in caduta libera su Ama...
Micron pronta con i moduli RDIMM DDR5 da...
Helldivers 2 su Steam: bisognerà ...
La XPeng G6 ora è disponibile anc...
Google, ecco quanto paga per rimanere il...
AMD si è ormai lasciata la vulner...
2 modelli di SAMSUNG Galaxy S24 Ultra 12...
Amazon Gaming Week: le offerte sulle sch...
NVIDIA rende più facile giocare con GeFo...
Partita a tre per Paramount: dopo Skydan...
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: 15:37.


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