codice:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Libro extends JPanel {
private final int facciate = 100;
private final int righePerPagina = 10;
private final int delay = 10;
private int facciataCorrente;
private int x,y;
private final String riga = "Ciao mamma guarda come mi diverto";
private Timer timer;
private boolean aspetta , destra;
public Libro (){
setPreferredSize (new Dimension (500 , 500));
facciataCorrente = 0;
x = 50;
aspetta = false;
timer = new Timer (delay , new ActionListener () {
public void actionPerformed (ActionEvent ae) {
if (destra) {
if (x > 50) {
x--;
paintImmediately (50 , 100 , 400 , 300);
}else {
aspetta = false;
timer.stop ();
facciataCorrente++;
paintImmediately (50 , 100 , 400 , 300);
}
}else {
if (x < 450) {
x++;
paintImmediately (50 , 100 , 400 , 300);
}else {
aspetta = false;
timer.stop ();
facciataCorrente--;
paintImmediately (50 , 100 , 400 , 300);
}
}
}
});
addKeyListener (new KeyAdapter () {
public void keyPressed (KeyEvent ke) {
if (ke.getKeyCode () == KeyEvent.VK_LEFT && facciataCorrente > 0 && !aspetta) {
System.out.println ("ENTRATO");
x = 50;
destra = false;
aspetta = true;
timer.start ();
}else if (ke.getKeyCode () == KeyEvent.VK_RIGHT && facciataCorrente < facciate && !aspetta) {
System.out.println ("ENTRATO1");
x = 450;
destra = true;
aspetta = true;
timer.start ();
}
}
});
}
public void paintComponent (Graphics g) {
super.paintComponent (g);
g.setColor (Color.BLACK);
//COPERTINA
g.fillRect (45,95,205,310);
g.fillRect (250,95,205,310);
g.setFont (g.getFont ().deriveFont (10f));
if (facciataCorrente > 0) {
if (facciataCorrente == 1 && aspetta && !destra) {
}else {
g.drawRect (50,100,200,300);
g.setColor(Color.WHITE);
g.fillRect (50,100,200,300);
g.setColor (Color.BLACK);
for (int i=0;i<righePerPagina;i++) {
g.drawString (riga , 55 , 110 + i * (290 / righePerPagina));
}
//g.drawString (String.valueOf (facciataCorrente * 2) ,55 , 395);
}
}
if (facciataCorrente < facciate) {
if (facciataCorrente == facciate - 1 && aspetta && destra) {
}else {
g.setColor (Color.BLACK);
g.drawRect (250,100,200,300);
g.setColor(Color.WHITE);
g.fillRect (250,100,200,300);
g.setColor (Color.BLACK);
for (int i=0;i<righePerPagina;i++) {
g.drawString (riga , 255 , 110 + i * (290 / righePerPagina));
}
//g.drawString (String.valueOf (facciataCorrente * 2 + 1) ,445 , 395);
}
}
if (aspetta) {
g.setColor (Color.BLACK);
g.drawRect (x < 250 ? x : 250,100,Math.abs (250 - x),300);
g.setColor(Color.WHITE);
g.fillRect (x < 250 ? x : 250,100,Math.abs (250 - x),300);
}
}
public static void main (String [] args) {
final Libro l = new Libro ();
JFrame f = new JFrame ();
f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
f.getContentPane ().add (l);
l.requestFocusInWindow ();
f.addWindowFocusListener (new WindowFocusListener () {
public void windowGainedFocus (WindowEvent we) {
l.requestFocusInWindow ();
}
public void windowLostFocus (WindowEvent we) {}
});
f.pack ();
f.setVisible (true);
}
}