swing - How can I draw lines, rectangles, and circles in my Java paint program? -
i'm working on paint program 1 of classes , i'm stuck. part of code (separated 3 java classes). when click on button "ligne", want able draw line in white rectangle. sorry french comments.
//cree une fenetre public class question { public static void main(string[] args) { paint_gui test2 = new paint_gui(); } }
import java.awt.*; import javax.swing.*; //class contenant le code pour dessiner public class paint_dessin extends jpanel { public void paintcomponent(graphics g) { super.paintcomponent(g); setbackground(color.white); g.setcolor(color.black); } public void tracerligne() { system.out.println("ligne"); } }
import javax.swing.*; import java.awt.event.*; import java.awt.*; public class paint_gui extends jframe { //panels contenant tout les bouton de mon interface private jpanel panelbtn; //bar d'outil btn private jbutton btntracerligne; //object paint_dessin private paint_dessin espacedessin = new paint_dessin(); public paint_gui() { final int window_width = 650; final int window_height = 450; setsize (window_width, window_height); settitle("paint v.2.0"); setdefaultcloseoperation(jframe.exit_on_close); setlayout(new borderlayout()); // appeler la methode qui construit la barre de btn. buildpanelbtn(); add(panelbtn, borderlayout.north); add(espacedessin, borderlayout.center); // afficher la fenetre. setvisible(true); } private void buildpanelbtn() { btntracerligne = new jbutton("ligne"); btntracerligne.addactionlistener(new lignelistener()); // creer le panel. panelbtn = new jpanel(); // ajouter les composantes au label panelbtn.add(btntracerligne); } private class lignelistener implements actionlistener { public void actionperformed(actionevent e) { espacedessin.tracerligne(); } }
you're current code has problem in you're creating new paint_dessin in lignelistener class's actionperformed method, , while object created same class paint_dessin object displayed in jframe, different object , calling methods on have absolutely no effect on paint_dessin displayed. need declare private paint_dessin variable once in paint_gui class, class field, initialize variable either @ declaration or in paint_gui constructor, , display object in gui , call methods on gui in listener class. e.g.,
public class paint_gui extends jframe { private jpanel panelbtn; private jbutton btntracerligne; private paint_dessin espacedessin = new paint_dessin(); public paint_gui() { final int window_width = 650; //... code deleted sake of brevity // paint_dessin espacedessin = new paint_dessin(); add(espacedessin, borderlayout.center); // afficher la fenetre. setvisible(true); } private void buildpanelbtn() { // .... } private class lignelistener implements actionlistener { public void actionperformed(actionevent e) { // paint_dessin tracerligne = new paint_dessin(); // tracerligne.tracerligne(); espacedessin.tracerligne(); // call method on same object! } }
Comments
Post a Comment