hanyatou
hanyatou

Reputation: 11

graphics object are not visible when i called repaint method

Here I have a problem I would like you to help me solve. Thank you to all who wish to do so.

I have objects that inherit from the JComponent class to which I added a MouseListener.

I have a grid that inherits a panel.

I would like to add the objects one by one in the grid so as to have in my grid at least 2 forms similar or different. While adding, I would like this to happen at a given position (the one where we just clicked) while avoiding the JComponents type objects from getting stacked up one another or that their intersection gives something other than the empty set or straight portion (a segment). So to avoid its annoyances I think whenever you add on after having clicked in/on the grid, check if the point obtained is not already inside an object that inherits JComponent and if the number of boxes around is enough. But still it does not work. Even as the object to add does not appear in the grid (the implementation is in the GrilleIHM#mouseClicked method).

I tried to centralize the behavior of objects on click by creating a class just for that instead of having the same piece of code in all my forms (I 8) but without success. so I abandoned that idea.

Being zero in Java, I have advanced so far through the tutorials and forums. But after twenty days I do not advance at all.

I know I demand too much at once but now I no longer find a solution.

Thank you for helping help me.

That's my code:

public class GrilleIHM extends JFrame implements MouseListener {
    private static final long serialVersionUID = 5592120196313024461L;

    private String typeF;
    private Forme22  f1 = new Forme22(20,20);
    private Forme2   f2 = new Forme2(20,20);
    private Forme3   f3 = new Forme3(20,20);
    private Forme3_1 f4 = new Forme3_1(20,20);
    private Forme4   f5 = new Forme4(20,20);
    private Forme5   f6 = new Forme5(20,20);
    private Forme6   f7 = new Forme6(20,20);
    private Former   f8 = new Former(20,20);

    private int n;
    private int m;
    private int o;
    private int p;
    private boolean startmyGame = false;
    private boolean bpause = false;
    private boolean breprendre = false;

    private JButton startGame = new JButton("Commencer");
    private JButton pause = new JButton("Pause");
    private JButton reprendre = new JButton("Redémarrer");
    private Font maFont = new Font("Arial", Font.CENTER_BASELINE, 15);
    private FlowLayout experimentLayout = new FlowLayout();
    private JPanel panelinfo = new JPanel();
    private Grille magrille ;

    private boolean clickgrill;
    private int nbCaseVide;
    private int nbCGrille;

    public GrilleIHM(int nbCX, int nbCY, int nbF, int nbCMax) {
        super();
        this.m = nbCY;
        this.n = nbCX;
        this.o = nbF;
        this.p = nbCMax;
        createAndShowGUI();     
    }

    private  void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Grille IHM ou Agencement");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initComponents(frame.getContentPane()); 
        frame.addMouseListener(this);
        frame.pack();
        frame.setVisible(true);               
    }

    private  void  initComponents(Container pane) { 
         magrille = new Grille(this.n, this.m);
         magrille.addMouseListener(this);       

         //les menu horizotal
         panelinfo.setPreferredSize(new Dimension(400,400));

         // menu vertical
         JPanel panel = new JPanel();
         BoxLayout box = new BoxLayout(panel, BoxLayout.Y_AXIS);
         // pane.addMouseListener(new MyMouseOneJComponents());
         // box.
         panel.setLayout(box);
         panel.setPreferredSize(new Dimension(120, 20));
         panel.setAlignmentX(20);
         startGame.setMaximumSize(
             new Dimension(Integer.MAX_VALUE,
                           startGame.getMinimumSize().height));
         pause.setMaximumSize(
             new Dimension(Integer.MAX_VALUE,
                           pause.getMinimumSize().height));
        reprendre.setMaximumSize(
             new Dimension(Integer.MAX_VALUE,
                           reprendre.getMinimumSize().height));
        reprendre.setFont(maFont);
        pause.setFont(maFont);
        startGame.setFont(maFont);

        startGame.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent evt) {
                 startGameActionPerformed(evt);
             }
        });

        reprendre.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent evt) {
                 reprendreGameActionPerformed(evt);
             }
        });

        pause.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent evt) {
                 pauseGameActionPerformed(evt);
             }
        });

        //reprendre.set
        panel.add(startGame);
        panel.add(reprendre);
        panel.add(pause);

        final JPanel compsToExperiment = new JPanel();
        compsToExperiment.setLayout(experimentLayout);
        experimentLayout.setAlignment(FlowLayout.TRAILING);

        switch (this.p) {
        case 2:
            pane.setComponentOrientation(java.awt.ComponentOrientation.RIGHT_TO_LEFT);
            f2.setPreferredSize(new Dimension(120, 120));

            pane.add(panel, BorderLayout.EAST);
            pane.add(f2, BorderLayout.NORTH); 
            magrille.setPreferredSize(
                new Dimension(20*magrille.getNbCaseX(),
                              20*magrille.getNbCaseY()));

            pane.add(magrille, BorderLayout.CENTER);
            pane.add(panelinfo, BorderLayout.WEST);
            //  p;
            f2.validate();
            f2.repaint();
            panel.validate();
            panel.repaint();
            magrille.validate();
            magrille.repaint();
            break;

        case 3:
            compsToExperiment.add(f2);
            compsToExperiment.add(f3);
            compsToExperiment.add(f4);

            f2.setPreferredSize(new Dimension(120, 120));
            f3.setPreferredSize(new Dimension(120, 120));
            f4.setPreferredSize(new Dimension(120, 120));

            pane.add(panel, BorderLayout.EAST);
            pane.add(compsToExperiment, BorderLayout.NORTH); 

            magrille.setPreferredSize(
                new Dimension(20*magrille.getNbCaseX(), 
                              20*magrille.getNbCaseY()));
            pane.add(magrille, BorderLayout.CENTER);
            pane.add(panelinfo, BorderLayout.WEST);
            //  p;
            f2.validate();
            f2.repaint();
            f3.validate();
            f3.repaint();
            f4.validate();
            f4.repaint();
            panel.validate();
            panel.repaint();
            magrille.validate();
            magrille.repaint();                                    
            break;

        case 4:
        case 5:
        case 6:
            compsToExperiment.add(f2);
            compsToExperiment.add(f3);
            compsToExperiment.add(f4);
            compsToExperiment.add(f1);
            compsToExperiment.add(f5);
            f1.setPreferredSize(new Dimension(120, 120));
            f2.setPreferredSize(new Dimension(120, 120));
            f3.setPreferredSize(new Dimension(120, 120));
            f4.setPreferredSize(new Dimension(120, 120));
            f5.setPreferredSize(new Dimension(120, 120));
            pane.add(panel, BorderLayout.EAST);
            pane.add(compsToExperiment, BorderLayout.NORTH); 

            magrille.setPreferredSize(
                new Dimension(20*magrille.getNbCaseX(), 
                              20*magrille.getNbCaseY()));
            pane.add(magrille, BorderLayout.CENTER);
            pane.add(panelinfo, BorderLayout.WEST);
            //  p;
            f2.validate();
            f2.repaint();
            f3.validate();
            f3.repaint();
            f4.validate();
            f4.repaint();
            f1.validate();
            f1.repaint();
            f5.validate();
            f5.repaint();
            panel.validate();
            panel.repaint();
            magrille.validate();
            magrille.repaint();                   
            break;

        case 7:
            compsToExperiment.add(f2);
            compsToExperiment.add(f3);
            compsToExperiment.add(f4);
            compsToExperiment.add(f1);
            compsToExperiment.add(f5);
            compsToExperiment.add(f8);
            f1.setPreferredSize(new Dimension(120, 120));
            f2.setPreferredSize(new Dimension(120, 120));
            f3.setPreferredSize(new Dimension(120, 120));
            f4.setPreferredSize(new Dimension(120, 120));
            f5.setPreferredSize(new Dimension(120, 120));
            f8.setPreferredSize(new Dimension(120, 120));
            pane.add(panel, BorderLayout.EAST);
            pane.add(compsToExperiment, BorderLayout.NORTH); 

            magrille.setPreferredSize(
                new Dimension(20*magrille.getNbCaseX(),
                              20*magrille.getNbCaseY()));
            pane.add(magrille, BorderLayout.CENTER);
            pane.add(panelinfo, BorderLayout.WEST);
            //  p;
            f2.validate();
            f2.repaint();
            f3.validate();
            f3.repaint();
            f4.validate();
            f4.repaint();
            f1.validate();
            f1.repaint();
            f5.validate();
            f5.repaint();
            f8.validate();
            f8.repaint();
            panel.validate();
            panel.repaint();
            magrille.validate();
            magrille.repaint(); 
            break;

        default:
            compsToExperiment.add(f2);
            compsToExperiment.add(f3);
            compsToExperiment.add(f4);
            compsToExperiment.add(f1);
            compsToExperiment.add(f5);
            compsToExperiment.add(f8);
            compsToExperiment.add(f6);
            compsToExperiment.add(f7);
            f1.setPreferredSize(new Dimension(120, 120));
            f2.setPreferredSize(new Dimension(120, 120));
            f3.setPreferredSize(new Dimension(120, 120));
            f4.setPreferredSize(new Dimension(120, 120));
            f5.setPreferredSize(new Dimension(120, 120));
            f8.setPreferredSize(new Dimension(120, 120));
            f6.setPreferredSize(new Dimension(120, 120));
            f7.setPreferredSize(new Dimension(120, 120));
            pane.add(panel, BorderLayout.EAST);
            pane.add(compsToExperiment, BorderLayout.NORTH); 

            magrille.setPreferredSize(
                new Dimension(20*magrille.getNbCaseX(),
                              20*magrille.getNbCaseY()));
            pane.add(magrille, BorderLayout.CENTER);
            pane.add(panelinfo, BorderLayout.WEST);
            //  p;
            f2.validate();
            f2.repaint();
            f3.validate();
            f3.repaint();
            f4.validate();
            f4.repaint();
            f1.validate();
            f1.repaint();
            f5.validate();
            f5.repaint();
            f8.validate();
            f8.repaint();
            f6.validate();
            f6.repaint();
            f7.validate();
            f7.repaint();
            panel.validate();
            panel.repaint();
            magrille.validate();
            magrille.repaint(); 
            break;
        }

          //les menu horizontal
    }

    public int getO() {
        return o;
    }

    public void setO(int o) {
        this.o = o;
    }

    @Override
    public void mouseClicked(MouseEvent evt) {  
        magrille.setLayout(null);
        int valX=evt.getX();
        int valY=evt.getY();
        System.out.println(valX);
        System.out.println(valY);
        JComponent f11;

        if (f1.getTypeF()!=null  && getO()>=0) {
            typeF=f1.getTypeF();
            f1.setTypeF(null);

            if (f1.isInForme(valX, valY)==false 
             && f2.isInForme(valX, valY)==false 
             && f3.isInForme(valX, valY)==false 
             &&  f4.isInForme(valX, valY)==false  
             && f5.isInForme(valX, valY)==false 
             && f6.isInForme(valX, valY)==false 
             && f7.isInForme(valX, valY)==  false 
             && f8.isInForme(valX, valY)==false) {
                if (magrille.getNbCGrille()> magrille.getNbCaseOccupe()) {
                    System.out.println(" nbVideSuffissant");                
                    f11= new Forme2((int)valX,(int)valY);
                    System.out.println(" ab grille = "+ valX);
                    System.out.println("ord grille = " + valY);
                    System.out.println(" ord création objet");
                    // f11.paint();
                    //f11.validate();       
                    magrille.add(f11);
                    f11.setBounds(valX, valY, 40, 40);
                    f11.validate();
                    f11.repaint();
                    magrille.revalidate();
                    magrille.repaint();
                    this.validate();
                    this.repaint();
                    //validate();
                    //magrille.notify();
                    //repaint();
                    //revalidate();
                    magrille.setNbCaseOccupe(f1.getNbCase());
                    // magrille.repaint();
                    System.out.println(magrille.getNbCaseOccupe());
                    //repaint();
                    setO(getO()- 1);
                    System.out.println(getO());
                }
            }
            System.out.println("click ok");
            ///evt.getComponent().
        }
    }

    public int getNbCGrille() {
        return this.n* this.m;
    }

    public void setNbCGrille(int nbCasX, int nbCasY) {
        this.nbCGrille = nbCasX*nbCasY;
    }

    public int getNbCaseVide() {
        return nbCaseVide;
    }

    public void setNbCaseVide(int nbCaseVide) {
        this.nbCaseVide =getNbCGrille()  - nbCaseVide;
    }

    @Override
    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub
    }

    // on regarde quelle forme a été cliqué puis on initialise sa valeur cliqué a true;
    // (we see what form was clicked on and we initialize his clicked value to true)
    @Override
    public void mousePressed(MouseEvent evt) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stu
    }

    private void pauseGameActionPerformed(ActionEvent evt) {
        // TODO Auto-generated method stub
        bpause=true;
    }

    private void reprendreGameActionPerformed(ActionEvent evt) {
        // TODO Auto-generated method stub
    }

    private void startGameActionPerformed(ActionEvent evt) {
        // TODO Auto-generated method stub
        startmyGame=true;
        if (startmyGame==true) {
            magrille.addMouseListener(this);
        }
        bpause=false;
        breprendre=false;
   }
}

Class Forme22:

public class Forme22 extends  JComponent implements MouseListener {

    private static final long serialVersionUID = -8557188538997741713L;
    private static final int taillC = 20;
    // x et y = coordonée du point cliqué

    private int abs;
    private int ord;
    private double tab[][];
    private Color col;
    private int nbCase=4;
    private String typeF;
    private boolean click=false;

    public Forme22(int abs, int ord) {
        super();
        this.abs = abs;
        this.ord = ord;
        this.col=Color.gray;
        tab= new  double [2][2];
        addMouseListener( (MouseListener) this);
    }

    public void paint (Graphics gr ){ 
        Graphics2D g= (Graphics2D)gr;
        for (int i = 0; i < this.tab[0].length; i++) {
            for (int k=0; k <this.tab.length; k++) {
                g.setColor(col);
                Rectangle2D.Double rect = 
                    new Rectangle2D.Double( this.abs+i*taillC,
                                            this.ord+k*taillC,
                                            taillC,
                                            taillC);
                g.fill(rect);
                g.setColor(Color.black);
                g.draw(rect);
            }
        }
    }

    public boolean isInForme(int valX, int valY){
        return ( (this.abs <= (int)valX)
                && (this.abs+2*taillC >= (int)valX)
                && (this.ord <= (int)valY)
                && (this.ord+2*taillC >= (int)valY) );
    }

    public String getCol() {
        return "gray";
    }
    public void setCol(Color col) {
        this.col = col;
    }

    public int getNbCase() {
        return nbCase;
    }

    public void setNbCase(int nbCase) {
        this.nbCase = nbCase;
    }

    public boolean isClick() {
        return click;
    }

    public void setClick(boolean click) {
        this.click = click;
    }

    public int getAbs() {
        return abs;
    }

    public void setAbs(int abs) {
        this.abs = abs;
    }

    public int getOrd() {
        return ord;
    }

    public void setOrd(int ord) {
        this.ord = ord;
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    // ajout du mouselistener dans les formes au survol des JComposants
    // (Adding of mouselistener in forms on hover on JComponants)
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        //recuperation coordonnée endroits cliquée  
        int x=e.getX();
        int y =e.getY();
        // memeorisation des nouveaux coordonées pour les récupéré depuis la grille en créant un point;
        // (saving new coordinates for gather them from the grid during creating a point)
        Point p=new Point(x, y);
        setTypeF("forme22");
        setClick(true); 
    }

    public String getTypeF() {
        return typeF;
    }

    public void setTypeF(String typeF) {
        this.typeF = typeF;
    }
}

Upvotes: 1

Views: 55

Answers (1)

NatNgs
NatNgs

Reputation: 874

You're code is very difficult to read, try to name attributes with a more significant way in order to view what this variable is or what should it do just reading his name.

I think your problem is hidden somewhere among these problems. Try to refactor your code, and I think the bug will disappear.


Your class is extending JFrame. So you have not to do a new JFrame() !

The line super() in your constructor is exactly the same as the new JFrame() call (so you have in your code to do super("Grille IHM ou Agencement");)

That implies that you will use this instead of frame.


Your switch case is too large. Break it into some methods; for example to obtain something like:

switch(status) {
    case 0:
        if_status_0(what_the_method_need);
        break; 
    case 1:
        if_status_1(what_the_method_need);
        break; 
    default:
        if_default(what_the_method_need);
        //break; << you can avoid the break of default statement in a switch case
} 

You can also refactor your code using methods for code used multiple times, for example:

@Override             // exceptionnally 
public void repaint() // for this method you can use this name

// but for others use like this with private personalized method
private void mySubMethodName() {
    f2.validate();
    f2.repaint();
    f3.validate();
    f3.repaint();
    f4.validate();
    f4.repaint();
    f1.validate();
    f1.repaint();
    f5.validate();
    f5.repaint();
    panel.validate();
    panel.repaint();
    magrille.validate();
    magrille.repaint();
}

Upvotes: 1

Related Questions