A - Général

Modulo avec des nombres négatifs

20 % 3 = 220 % -3 = 2-20 % 3 = -2-20 % -3 = -2

Modulo avec des nombres négatifs

Méthode-2.6-2.32.32.6 0
(int) …-2-222 0
Math.floor(…)-3.0-3.02.02.0 0.0
Math.ceil(…)-2.0-2.03.03.0 0.0
Math.round(…)-3-223 0
Math.rint(…)-3.0-2.02.03.0 0.0

La classe Math

Math.PI Math.abs(...) Math.max(... , ...) Math.min(... , ...)

Math.round(...) // double → long; float → int

double Math.sqrt(...)

Math.pow(..., ...)

Math.random()


Les valeurs aléatoires

// int, dans [a..b]
i = (int) (Math.random()*(b-a+1))+a;
// double, dans [a..b[
d = Math.random()*(b-a)+a; 
// double, dans ]a..b]
d = -Math.random()*(-b+a)+a;
// réel, dans [a..b], a,b entiers, maximum 2 unités derrière la virgule
d = ((int) (Math.random()*(b*100-a*100+1))+a*100)/100.0; 
// réel, dans [a..b[, a,b entiers, maximum 2 unités derrière la virgule
d = ((int) ((Math.random()*(b-a))+a)*100)/100.0; 
// entier, dans [a..b], >0 et multiple de c
i = ((int) (Math.random()*(b/c-(a+c-1)/c+1))+(a+c-1)/c)*c; 
// entier, dans [a..b], a,b et i tous les trois multiples de c
i = ((int) (Math.random()*(b/c-a/c+1))+a/c)*c; 
// exécuter au hasard une action parmi deux
if (Math.random()<0.5) ...; else ...;

B - Listes

Voir cette page.

C - Graphics

1. Bases

import java.awt.Color;

import java.awt.Graphics;


Graphics g = drawPanel.getGraphics(); // pour dessiner sur un Panel choisi

public void paintComponent(Graphics g) { ... } // pour dessiner dans le drawPanel

// Exemples des 8 méthodes

g.getColor();

g.setColor(Color.RED);

g.drawLine(x1, y1, x2, y2);

g.drawRect(x, y, width, height);

g.fillRect(x, y, width, height);

g.drawOval(x, y, width, height);

g.fillOval(x, y, width, height);

g.drawString(s, x, y);

2. Exemples

    // vider le DrawPanel 
    public void paintComponent(Graphics g) {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, getWidth(), getHeight());
        ...

    // position aléatoire sur drawPanel
    int x1 = (int) (Math.random()*drawPanel.getWidth());
    int y1 = (int) (Math.random()*drawPanel.getHeight());

3. Color

    // couleur aléatoire
    g.setColor(new Color((int) (Math.random()*256),(int) (Math.random()*256),(int) (Math.random()*256)));

    // saisir couleur dans fenêtre de dialogue (pas sur programme de l'examen)
    Color newColor = JColorChooser.showDialog(this,"Choix d'une couleur", Color.BLACK);

4. Géométrie

    // rectangle défini par les coordonnées (x1,y1) et (x2,y2) de deux coins opposés du rectangle
    g.drawRect(Math.min(x1,x2),Math.min(y1,y2),Math.abs(x1-x2),Math.abs(y1-y2));
    // rectangle défini par deux points (du type Point) données from et to
    g.drawRect(Math.min(from.x,to.x),Math.min(from.y,to.y),Math.abs(from.x-to.x),Math.abs(from.y-to.y));

    // calculer la distance entre deux points p1 et p2
    int dist = (int) Math.round(Math.sqrt(Math.pow(p2.x-p1.x, 2) + Math.pow(p2.y-p1.y, 2)));
	
    // est-ce qu'un point (x,y) se trouve dans un rectangle défini par deux coins opposés (x1,y1) et (x2,y2)
    if (x>=Math.min(x1,x2) && x<=Math.max(x1,x2) && y>=Math.min(y1,y2) && y<=Math.max(y1,y2)) ...

    // dessiner un cercle défini par 2 points : son centre (cx,cy) et un point quelquonque sur le bord (bx,by)
    int radius = (int) Math.round(Math.sqrt(Math.pow(cx-bx,2) + Math.pow(cy-by,2)));
    g.drawOval(cx-radius, cy-radius, radius+radius, radius+radius);
	
    // dessiner un polygone fermé à partir d'une ArrayList<Point>
    if (plist.size()==0) return;
    Point p1=plist.get(plist.size()-1); // p1 est le point précédent et au début c'est le dernier point 
    for (int i=0;i<plist.size();i++ ) {
        Point p2=plist.get(i); // p2 est le point actuel
        g.drawLine(p1.x, p1.y, p2.x, p2.y);
        p1 = p2;
    }	

5. Grilles

    // cw : cellWidth, gw : gridWidth, mxgw : maximalGridWidth
    // ch : cellHeight, gh : gridHeight, mxgh : maximalGridHeight
	// rows : nombre de lignes, cols : nombre de colonnes
    
    // dessin d'une grille avec des cellules carrées de taille fixe, sans offset
    public void drawFixGrid(Graphics g, int rows, int cols, int size) {
        g.setColor(Color.BLACK);
        for (int i=0;i<=rows;i++)
            g.drawLine(0, i*size, cols*size, i*size);
        for (int i=0;i<==cols;i++)
            g.drawLine(i*size, 0, i*size, rows*size);
    }
    // dessin d'une grille avec des cellules carrées de taille fixe, avec offset (oX,oY)
    public void drawFixGridOffset(Graphics g, int oX, int oY, int rows, int cols, int size) {
        g.setColor(Color.BLACK);
        for (int i=0;i<==rows;i++)
            g.drawLine(oX, oY+i*size, oX+cols*size, oY+i*size);
        for (int i=0;i<==cols;i++)
            g.drawLine(oX+i*size, oY, oX+i*size, oY+rows*size);
    }
    // Dessin d'une grille d'une taille totale fixe.
    // Les lignes et colonnes peuvent varier en taille.
    public void drawVarGrid(Graphics g, int rows, int cols, int gw, int gh) {
        g.setColor(Color.RED);
        for (int i=0;i<==rows;i++)
            g.drawLine(0, i*gh/rows, gw-1, i*gh/rows);
        for (int i=0;i<==cols;i++)
            g.drawLine(i*gw/cols, 0, i*gw/cols, gh-1);
    }
    // Dessin d'une grille d'une taille maximale donnée. 
    // Les cellules rectangulaires ont toutes la même taille.
    // la taille de la grille peut être plus petite que la taille maximale.
    public void drawVarGrid2(Graphics g, int rows, int cols, int mxgw, int mxgh) {
        g.setColor(Color.GREEN);
        int cw = mxgw/cols;
        int ch = mxgh/rows;
        int gw = cw*cols;
        int gh = ch*rows;
        for (int i=0;i<==rows;i++)
            g.drawLine(0, i*ch, gw-1, i*ch);
        for (int i=0;i<==cols;i++)
            g.drawLine(i*cw, 0, i*cw, gh-1);
    }

5. Spécial fenêtres

// centrer la fiche, à placer après initComponents()

   setLocationRelativeTo(null);

// message box

   javax.swing.JOptionPane.showMessageDialog(null,"message");

D - MouseEvents

Le point rendu par evt.getPoint() donne un nouveau point :

    p1 = evt.getPoint();
    p2 = evt.getPoint();
    if (p1==p2) … // donne false

Les boutons

   if (evt.getButton()==MouseEvent.BUTTON1) ... // bouton gauche
   if (evt.getButton()==MouseEvent.BUTTON2) ... // bouton du milieu
   if (evt.getButton()==MouseEvent.BUTTON3) ... // bouton droit
Pour connaître le bouton lors de l'événement "Dragged" :
  • Ajouter un attribut au début du MainFrame : int button;
  • Dans méthode MousePressed : button = evt.getButton();
  • Dans méthode MouseDragged : utiliser button au lieu de evt.getButton()
    if (button==MouseEvent.BUTTON1) ... etc.

E - Timer

import javax.swing.Timer;


private Timer timer;


timer = new Timer( 500 , stepButton.getActionListeners()[0] );

stepButton.setVisible(false);

timer.start();


timer.stop();

if (timer.isRunning()) …

setDelay(1000);


F - How To

JAR

Distribuer :

  1. Créer classe dans UniMozer
  2. Ouvrir dans NetBeans
  3. Clean and Build
  4. Récupérer le fichier jar dans le dossier dist

Intégrer dans NetBeans :

  1. clic droit sur projet
  2. propriétés => Libraries
  3. Add JAR/Folder

Applet

Programmation :

  1. Créer Java Form JFrame MainFarme
  2. Créer Java Form JPanel MainPanel
  3. Programmer dans MainPanel
  4. Clean and Build
  5. Glisser MainPanel sur MainFrame
  6. Créer Java Class MainApplet avec CODE1
  7. Clean and Build Main Project
  8. Copier dossier dist sur serveur
  9. Créer fichier applet.html avec CODE2
  10. Remplacer Applet.jar, Titre et dimensions dans applet.hml

CODE1 :

import javax.swing.JApplet;
import javax.swing.UIManager;
public class MainApplet extends JApplet {
@Override
public void init() {
try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); this.getContentPane().add(new MainPanel()); }
catch (Exception ex) {} } }

CODE2 :

<html><head><title>Titre de votre application</title></head>
<body><applet archive="Applet.jar,lib/swing-layout-1.0.4.jar" code="MainApplet"
width="680" height="500"></applet></body></html> 

WebStart

Distribuer :

  1. Créer Projet dans NetBeans
  2. Propriétés => Web Start
  3. Cocher : enable Web start, Allow Offline, Self-signed
  4. Choisir : codebase=Userd defined et indiquer le dossier de base
  5. Clean and Build
  6. Dans dossier dist : éditer le fichier jnlp si on l'a renommé
  7. Uploaded le contenu du dossier dist

G - Structure de base MVC

A l'aide d'un exemple : TrucGUI.



[rrjavabdc]