1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener{
BufferedImage image=null;
JPanel panneau=null;
JButton blanc=new JButton("Tracer une ligne blanche");
JButton noir=new JButton("Tracer une ligne noire");
Test(){
noir.setPreferredSize(new Dimension(200,50));
blanc.setPreferredSize(new Dimension(200,50));
image=new BufferedImage(100,100,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0,100,100);
panneau=new JPanel()
{ public void paint(Graphics g){
super.paint(g);
g.drawImage(image,0,0,this);
}
};
panneau.setPreferredSize(new Dimension(100,100));
getContentPane().setLayout(new BorderLayout());
getContentPane().add(noir,BorderLayout.NORTH);
getContentPane().add(blanc,BorderLayout.SOUTH);
getContentPane().add(panneau,BorderLayout.CENTER);
noir.addActionListener(this);
blanc.addActionListener(this);
blanc.setActionCommand("blanc");
noir.setActionCommand("noir");
this.pack();
this.setTitle("Ceci est un test");
this.setVisible(true);
}
public void actionPerformed(ActionEvent e){
Graphics2D g2d=(Graphics2D)(image.getGraphics());
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Graphics g=panneau.getGraphics();
String cmd=e.getActionCommand();
if (cmd.equals("blanc")){
g2d.setColor(Color.WHITE);
}
else {
g2d.setColor(Color.BLACK);
}
g2d.drawLine(0,0,100,100);
g.drawImage(image,0,0,this);
}
protected void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) System.exit(0);
}
static public void main(String[] args){
new Test();
}
} |
Partager