import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.GeneralPath;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class sampleFrame extends JFrame implements ActionListener{
private JButton drawButton=new JButton("Draw");
private samplePanel plot;
private int nbCurve=0;
public static void main(String[] args)
{
sampleFrame f = new sampleFrame();
f.createGUI();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setSize(300,200);
f.setLocation(50,50);
f.setVisible(true);
}
public void createGUI()//Pour initialise l'interface graphique
{
drawButton.addActionListener(this);
drawButton.setActionCommand("drawButton");
this.setLayout(new BorderLayout());
plot = new samplePanel();
this.getContentPane().add(plot,BorderLayout.CENTER);
this.getContentPane().add(drawButton,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
if ("drawButton".equals(e.getActionCommand())) {
nbCurve++;
//plot.generalPaths.removeAllElements();
plot.drawCurves(nbCurve);
plot.repaint();
System.out.println("nbCurve="+nbCurve);
}
}
}
class samplePanel extends JPanel
{
public Vector generalPaths = new Vector(); //Vecteur qui va contenir les courbes
GeneralPath path; //Represente chaque courbes
private int nbCurve=0;
protected void paintComponent(Graphics g) //Pour dessiner le fond du composant et les courbes
{
g.clearRect(0,0,300,200);
Graphics2D g2 = (Graphics2D)g;
super.paintComponent(g);
setBackground(Color.WHITE); //Couleur de fond du composant
System.out.println("paintComponent");
if(!generalPaths.isEmpty())
{
for(int i=0; i<nbCurve; i++)
{
if(i==0) g2.setPaint(Color.RED);
else if(i==1) g2.setPaint(Color.BLUE);
else if(i==2) g2.setPaint(Color.BLACK);
else if(i==3) g2.setPaint(Color.GREEN);
else if(i==4) g2.setPaint(Color.MAGENTA);
else if(i==5) g2.setPaint(Color.YELLOW);
System.out.println("Current curve number="+i);
g2.draw((GeneralPath) generalPaths.elementAt(i));
}
}
}
public void drawCurves(int nbCurve) //Pour dessiner les courbes
{
this.nbCurve=nbCurve;
for(int i=0; i<nbCurve; i++)
{
path = new GeneralPath();
path.moveTo(50+10*nbCurve,nbCurve+20);
path.lineTo(100+nbCurve,nbCurve+100);
generalPaths.addElement(path);
}
}
}
Partager