Precedente Indice Successiva

Esempio di Disegno figure e testo - il pannello

  • In questo caso nel panello disegneremo una sola figura alla volta. Il pannello presenterà due metodi chiamati public void eseguiAzione1(); e public void eseguiAzione2(); che rispettivamente, passeranno alla prossima o alla precedente figura.
  • Naturalmente ogni volta che si cambia figura occorre richiedere il ridisegno del pannello. Questo si ottiene invocando il metodo public void repaint();
  • Nel file MyPanelForme.java scriveremo:
    package frameformetest;

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;

    import javax.swing.JPanel;

    public class MyPanelForme extends JPanel {
    private static final int WIDTH=400;
    private static final int HEIGHT=300;
    private static final int NUMFIORME=7;

    private static final long serialVersionUID = 1L;

    private int forma;

    public MyPanelForme() {
    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    setBackground(new Color(0xff, 0xff, 0xcc));
    forma = 0;
    }

    @Override
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    switch(forma) {
    case 0:
    rettangoloVuoto(g);
    break;
    case 1:
    rettangoloPieno(g);
    break;
    case 2:
    tortaVuota(g);
    break;
    case 3:
    tortaPiena(g);
    break;
    case 4:
    poligonoVuoto(g);
    break;
    case 5:
    poligonoPieno(g);
    break;
    case 6:
    testo(g);
    break;
    }
    }

    private void testo(Graphics g) {
    g.drawString("Testo", WIDTH/2, HEIGHT/2);

    }

    private void poligonoPieno(Graphics g) {
    int[] xPoints = {WIDTH/3, 2*WIDTH/3,WIDTH/3 };
    int[] yPoints = {HEIGHT/3, 2*HEIGHT/3, 2*HEIGHT/3 };
    g.fillPolygon(xPoints, yPoints,3);
    }

    private void poligonoVuoto(Graphics g) {
    int[] xPoints = {WIDTH/3, 2*WIDTH/3,WIDTH/3 };
    int[] yPoints = {HEIGHT/3, 2*HEIGHT/3, 2*HEIGHT/3 };
    g.drawPolygon(xPoints, yPoints,3);
    }

    private void tortaPiena(Graphics g) {
    g.fillArc(WIDTH/3, HEIGHT/3, WIDTH/3, HEIGHT/3, 0, 270);
    }

    private void tortaVuota(Graphics g) {
    g.drawArc(WIDTH/3, HEIGHT/3, WIDTH/3, HEIGHT/3, 0, 270);
    }

    private void rettangoloPieno(Graphics g) {
    g.fillRect(WIDTH/3, HEIGHT/3, WIDTH/3, HEIGHT/3);
    }

    private void rettangoloVuoto(Graphics g) {
    g.drawRect(WIDTH/3, HEIGHT/3, WIDTH/3, HEIGHT/3);
    }

    public void eseguiAzione1() {
    if (forma < NUMFIORME - 1) {
    forma++;
    } else {
    forma = 0;
    }
    repaint();
    }

    public void eseguiAzione2() {
    if (forma > 0) {
    forma--;
    } else {
    forma = NUMFIORME - 1;
    }
    repaint();
    }

    }
© Ing. Stefano Salvi - released under FDL licence

Valid XHTML 1.0! Valid CSS!