Dessiner une grille de rectangles dans swing

Résolu
begueradj Messages postés 273 Date d'inscription dimanche 4 octobre 2009 Statut Membre Dernière intervention 24 juin 2014 - 1 déc. 2011 à 09:05
cs_Julien39 Messages postés 6414 Date d'inscription mardi 8 mars 2005 Statut Modérateur Dernière intervention 29 juillet 2020 - 2 déc. 2011 à 07:55
Bonjour,

J'ai une matrice qui ne contient que des 0 et des 1.
J'aimerais dessiner une grille de rectangles qui a les dimensions de ma matrice tout en colorant le rectangle correspondant à 1 dans la matrice par le noir et le rectangle correspondant à 0 dans ma matrice par le blanc.

Pourriez-vous me donner un petit code qui le fait ?

Merci pour toute aide

9 réponses

cs_Julien39 Messages postés 6414 Date d'inscription mardi 8 mars 2005 Statut Modérateur Dernière intervention 29 juillet 2020 371
1 déc. 2011 à 14:11
Dernière chose, je te conseille d'appeler ta méthode initUI dans le constructeur de DrawWelcomeWindow.

Ensuite pour ton exception, c'est une erreur lors du parcours de la matrice, à un moment données, les bornes sont dépassées. Ce que je t'avais donné était un exemple, je n'avais pas testé, ca te montrait juste le principe.

Je ne sais pas comment sont enregistrées les lignes et les colonnes dans le tableau (ie quel indice correspond aux lignes) tu devrais peut être essayer d'inverser if(lamatrice[j][i]==1) dans la méthode paintComponent. Sinon, sait un System.out.println(i+" ; "+j); avant le if et tu verras quel indice pose problème.
3
cs_Julien39 Messages postés 6414 Date d'inscription mardi 8 mars 2005 Statut Modérateur Dernière intervention 29 juillet 2020 371
1 déc. 2011 à 09:24
Bonjour,

Normalement les demandes de codes sont interdites par le règlement. Je te donne néanmoins un code qui te permettra de commencer, tu n'as qu'à l'adapter un peu et ca va fonctionner
public class PanelMatrice extends JPanel {

//Ta matrice de 0 et de 1
private Matrice matrice;

public PanelMatrice (Matrice matrice){
this.matrice=matrice;
}

@Override
public void paintComponent(Graphics g){
int largeur=getWidth()/matrice.getNombreCarreauxLargeur();
int hauteur=getHeight()/matrice.getNombreCarreauxHauteur();
for(int i=0; i<matrice.getTailleLargeur(); i++){
for(int j=0; j<matrice.getTailleHauteur; j++){
if(matrice.get(i, j)==0){
g.setColor(Color.WHITE);
}
else{
g.setColor(Color.BLACK);
}
g.fillRect(i*largeur, j*hauteur, largeur, hauteur);
}
}
}

}
0
begueradj Messages postés 273 Date d'inscription dimanche 4 octobre 2009 Statut Membre Dernière intervention 24 juin 2014 9
1 déc. 2011 à 09:37
Merci beaucoup Julien
je vais tester ton code
C'est très gentil de ta part
J'en ai fait un mais je ne sais pas paramétrer la couleur selon 1 ou 0
Merci beaucoup
0
cs_Julien39 Messages postés 6414 Date d'inscription mardi 8 mars 2005 Statut Modérateur Dernière intervention 29 juillet 2020 371
1 déc. 2011 à 10:38
Si tu veux tu peux me montrer ton code, je te dirai comment t'en sortir.
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
begueradj Messages postés 273 Date d'inscription dimanche 4 octobre 2009 Statut Membre Dernière intervention 24 juin 2014 9
1 déc. 2011 à 11:36
Merci

Voilà, j'ai adopté ta solution à mon code, et là, il ne me signale aucune erreur, par contre rien ne s'affiche.

Je te donnne le code de la classe où j'ai implémenté ta solution qui me semble cohérente:
package aiproject;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.util.Random;


public class DrawWelcomeWindow extends JLabel{
protected JFrame frame;
protected DrawLabyrinthFromMatrix DessinLab;
protected JMenuBar jmBar;

protected JMenu jmHelp;
protected JMenuItem jmiAbout;
protected JMenu jmFile;
protected JMenuItem jmiExit;
protected JPanel jpanel;
StoreFileDataIntoIntegerMatrix sfm= new StoreFileDataIntoIntegerMatrix();
protected int lescolonnes;
protected int leslignes;
protected int[][] lamatrice;
protected int[][] thematrix;
protected int hauteur=20;
protected int largeur=20;
protected int x;
protected int y;
protected int[] moncul;
//private static final Random random = new Random();
int[][]matricedetravail;



public DrawWelcomeWindow(int[][] givenmatrix){
this.matricedetravail=givenmatrix;
}
/*
 *draw my user interface
 * */
@Override
public  void paintComponent(Graphics g){
frame=new JFrame("Projet IA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setLayout(new GridLayout(leslignes, lescolonnes));
sfm.storeIntoArray();
sfm.storeAsIntegersIntoMatrix();
lescolonnes=sfm.getColumnsNb();
leslignes=sfm.getRowsNb();
lamatrice=sfm.getLabyrinthMatrix();
int a=20;
int b=20;

for(int i=0;i<a;i++){
for(int j=0;j<b;j++){
if(lamatrice[i][j]==1){
g.setColor(Color.BLUE);
}else{
g.setColor(Color.DARK_GRAY);
}
g.fillRect(i*largeur, j*hauteur, largeur, hauteur);
}

}


//DrawLabyrinthe label=new DrawLabyrinthe(lamatrice);
DrawWelcomeWindow label=new DrawWelcomeWindow(lamatrice);
frame.add(label);


jmBar=new JMenuBar();

ImageIcon iconExit=new ImageIcon(getClass().getResource("exit.jpeg"));
ImageIcon iconAbout=new ImageIcon(getClass().getResource("help.png"));


jmFile=new JMenu("File");
jmFile.setMnemonic('F');
jmHelp=new JMenu("Help");
jmHelp.setMnemonic('H');

jmiExit=new JMenuItem("Exit",iconExit);
jmiExit.setMnemonic('E');
jmiAbout=new JMenuItem("About",iconAbout);
jmiAbout.setMnemonic('A');


jmFile.add(jmiExit);
jmHelp.add(jmiAbout);
jmBar.add(jmFile);
jmBar.add(jmHelp);		


frame.setJMenuBar(jmBar);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

jmiExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});	

jmiAbout.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null,"Billal BEGUERADJ & Mohammed EL BARBORI Master CRYPTIS 1ère Année","                            Projet IA 2011/2012",JOptionPane.PLAIN_MESSAGE);
}
});





}/*END OF initUI() */
}//END OF my class


Et je l'ai appelé dans le main comme suit:

package aiproject;

import java.io.FileNotFoundException;

public class Labyrinthe{
public static void main(String[]args) throws FileNotFoundException{
//ReadMyFile rmf=new ReadMyFile();
StoreFileDataIntoIntegerMatrix storeit=new StoreFileDataIntoIntegerMatrix();
storeit.storeIntoArray();
storeit.storeAsIntegersIntoMatrix();
int[][]exercice=storeit.getLabyrinthMatrix();
DrawWelcomeWindow dww=new DrawWelcomeWindow(exercice);

//storeit.afficherMatrice();



}
}


Merci
0
cs_Julien39 Messages postés 6414 Date d'inscription mardi 8 mars 2005 Statut Modérateur Dernière intervention 29 juillet 2020 371
1 déc. 2011 à 11:43
Hou, quelle horreur !

Désolé mais, tu utilises vraiment mal la méthode paintComponent de ton JLabel.

Déjà, ca ne sert à rient d'utiliser un JLabel pour redéfinir paintComponent, prend plutot un JPanel.

Ensuite, dans paintComponent, tu ne dois écrire que ce qui te permet de déssiner ta fenêtre. Tu ne dois pas faire de fraime.add() par exemple.

Te devrais te servir du morceau de code que je t'ai donné pour améliorer le tien (au niveau conception) et tu pourrais déjà bien simplifier ce que tu as fait.

Qu'est ce qui ne fonctionne pas au juste dans cette classe ?
0
begueradj Messages postés 273 Date d'inscription dimanche 4 octobre 2009 Statut Membre Dernière intervention 24 juin 2014 9
1 déc. 2011 à 11:56
Merci.

J'ai rectifié en suivant tes indications comme suit:
package aiproject;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.util.Random;


public class DrawWelcomeWindow extends JPanel{
protected JFrame frame;
protected DrawLabyrinthFromMatrix DessinLab;
protected JMenuBar jmBar;

protected JMenu jmHelp;
protected JMenuItem jmiAbout;
protected JMenu jmFile;
protected JMenuItem jmiExit;
protected JPanel jpanel;
StoreFileDataIntoIntegerMatrix sfm= new StoreFileDataIntoIntegerMatrix();
protected int lescolonnes;
protected int leslignes;
protected int[][] lamatrice;
protected int[][] thematrix;
protected int hauteur=20;
protected int largeur=20;
protected int x;
protected int y;
protected int[] moncul;
//private static final Random random = new Random();
int[][]matricedetravail;
int a=20;
int b=20;



public DrawWelcomeWindow(int[][] givenmatrix){
//frame.setLayout(new GridLayout(leslignes, lescolonnes));
sfm.storeIntoArray();
sfm.storeAsIntegersIntoMatrix();
lescolonnes=sfm.getColumnsNb();
leslignes=sfm.getRowsNb();
lamatrice=sfm.getLabyrinthMatrix();

this.matricedetravail=givenmatrix;
}
/*
 *draw my user interface
 * */
@Override
public  void paintComponent(Graphics g){

for(int i=0;i<lescolonnes;i++){
for(int j=0;j<leslignes;j++){
if(lamatrice[i][j]==1){
g.setColor(Color.BLUE);
}else{
g.setColor(Color.DARK_GRAY);
}
g.fillRect(i*largeur, j*hauteur, largeur, hauteur);
}

}	


}/*END OF paintComponent */

public void initUI(){
frame=new JFrame("Projet IA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//DrawLabyrinthe label=new DrawLabyrinthe(lamatrice);
DrawWelcomeWindow label=new DrawWelcomeWindow(lamatrice);
frame.add(label);


jmBar=new JMenuBar();

ImageIcon iconExit=new ImageIcon(getClass().getResource("exit.jpeg"));
ImageIcon iconAbout=new ImageIcon(getClass().getResource("help.png"));


jmFile=new JMenu("File");
jmFile.setMnemonic('F');
jmHelp=new JMenu("Help");
jmHelp.setMnemonic('H');

jmiExit=new JMenuItem("Exit",iconExit);
jmiExit.setMnemonic('E');
jmiAbout=new JMenuItem("About",iconAbout);
jmiAbout.setMnemonic('A');


jmFile.add(jmiExit);
jmHelp.add(jmiAbout);
jmBar.add(jmFile);
jmBar.add(jmHelp);		


frame.setJMenuBar(jmBar);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

jmiExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});	

jmiAbout.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null,"Billal BEGUERADJ & Mohammed EL BARBORI Master CRYPTIS 1ère Année","                            Projet IA 2011/2012",JOptionPane.PLAIN_MESSAGE);
}
});

}
}//END OF my class



Et j'ai appelé comme ça dans le main:
package aiproject;

import java.io.FileNotFoundException;

public class Labyrinthe{
public static void main(String[]args) throws FileNotFoundException{
//ReadMyFile rmf=new ReadMyFile();
StoreFileDataIntoIntegerMatrix storeit=new StoreFileDataIntoIntegerMatrix();
storeit.storeIntoArray();
storeit.storeAsIntegersIntoMatrix();
int[][]exercice=storeit.getLabyrinthMatrix();
DrawWelcomeWindow dww=new DrawWelcomeWindow(exercice);
dww.initUI();

//storeit.afficherMatrice();



}
}


La fenêtre s'affiche à peine et le compilateur m'a signalé ces erreurs:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 8
at aiproject.DrawWelcomeWindow.paintComponent(DrawWelcomeWindow.java:69)
at javax.swing.JComponent.paint(JComponent.java:1029)
at javax.swing.JComponent.paintChildren(JComponent.java:866)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JComponent.paintChildren(JComponent.java:866)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:581)
at javax.swing.JComponent.paintChildren(JComponent.java:866)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5145)
at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:302)
at javax.swing.RepaintManager.paint(RepaintManager.java:1145)
at javax.swing.JComponent.paint(JComponent.java:1015)
at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:39)
at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:78)
at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:115)
at java.awt.Container.paint(Container.java:1844)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:751)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:696)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:676)
at javax.swing.RepaintManager.access$700(RepaintManager.java:57)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1550)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:226)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:647)
at java.awt.EventQueue.access$000(EventQueue.java:96)
at java.awt.EventQueue$1.run(EventQueue.java:608)
at java.awt.EventQueue$1.run(EventQueue.java:606)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:617)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)
0
begueradj Messages postés 273 Date d'inscription dimanche 4 octobre 2009 Statut Membre Dernière intervention 24 juin 2014 9
1 déc. 2011 à 17:50
Merci beaucoup Mr.Julien; tu avais bien fait de m'indiquer que le problème était au niveau des indices qui étaient hors limites.

J'ai vérifié les i et les j, j'ai déroulé l'algorithme que tu m'as donné pas à pas, et là j'ai deviné qu'il fallait inverser ces indices à l'affichage au niveau de g.fillRect() comme suit:

public  void paintComponent(Graphics g){
System.out.println(lescolonnes);
System.out.println(leslignes);
for(int i=0;i<leslignes;i++){
x1=x1+largeur;
for(int j=0;j<lescolonnes;j++){
if(lamatrice[i][j]==1){
g.setColor(Color.BLUE);
}else if(lamatrice[i][j]==0){
g.setColor(Color.DARK_GRAY);
}else{
g.setColor(Color.RED);
}
g.fillRect(j*largeur, i*hauteur, largeur, hauteur);
}

}	


}/*END OF paintComponent */



Mon code marche très bien, je peux continuer.
Merci mille fois
0
cs_Julien39 Messages postés 6414 Date d'inscription mardi 8 mars 2005 Statut Modérateur Dernière intervention 29 juillet 2020 371
2 déc. 2011 à 07:55
De rien. Bon courage pour la suite.
0
Rejoignez-nous