Netbeans drawing

ndoyestory Messages postés 52 Date d'inscription   Statut Membre Dernière intervention   -  
ndoyestory Messages postés 52 Date d'inscription   Statut Membre Dernière intervention   -
Bonjour,

je voudrais créer une application pour dessiner un rectangle, un cercle et un ellipse.
le principe est que je voudrais utiliser un combobox de qui gère la couleur de cercle que je veux dessiner par exemple, de ce fait lorsque je clique sur le bouton rectangle je choisi la couleur sur le combobox pour ensuite dessiner sur le panel.
merci
A voir également:

1 réponse

KX Messages postés 16761 Date d'inscription   Statut Modérateur Dernière intervention   3 020
 
Tu ajoutes un listener sur ton combobox, et dès qu'il change de valeur tu appliques sa valeur au composant que tu veux dessiner pour mettre la couleur que tu souhaites... c'est tout !
0
KX Messages postés 16761 Date d'inscription   Statut Modérateur Dernière intervention   3 020
 
Exemple complet (on peut faire plus simple)

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

enum Couleur
{
    Rouge(Color.RED), Vert(Color.GREEN), Bleu(Color.BLUE), Jaune(Color.YELLOW);
    
    private final Color clr;
    
    Couleur(Color color)
    {
        clr = color;
    }
    
    public Color getColor()
    {
        return clr;
    }
}

public class Test 
{
    public static void main(String[] args)
    {
        
        final JComboBox<Couleur> combobox = new JComboBox<Couleur>(Couleur.values());        
        
        final JPanel panel = new JPanel()
        {
            private static final long serialVersionUID = 1;

            @Override
            public void paint(Graphics g)
            {
                int w = getWidth()/5, h = getHeight()/5;
                Color color = ((Couleur) combobox.getSelectedItem()).getColor();
                
                g.setColor(color);
                g.drawRect(w,h,3*w,3*h);
            }
        };
        
        combobox.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent arg0)
            {
                panel.repaint();
            }
        });

        JFrame frame = new JFrame();
        frame.add(combobox,BorderLayout.NORTH);
        frame.add(panel,BorderLayout.CENTER);
        frame.setSize(500,300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
0
ndoyestory Messages postés 52 Date d'inscription   Statut Membre Dernière intervention   1
 
je comprend pas trop bien la structure dont vous avez fait, mais mon code Netbeans est là

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication;

/**
*
* @author Mamadou
*/
public class Paint extends javax.swing.JFrame {

/**
* Creates new form Paint
*/
public Paint() {
initComponents();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox();
jPanel3 = new javax.swing.JPanel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("MON APPLICATION PEINTRE");
jLabel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));

jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton1.setText("RECTANGLE");
jButton1.setBorder(new javax.swing.border.SoftBevelBorder(0));

jButton2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton2.setText("CERCLE");
jButton2.setBorder(new javax.swing.border.SoftBevelBorder(0));

jButton3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton3.setText("POLYGONE");
jButton3.setBorder(new javax.swing.border.SoftBevelBorder(0));

jButton4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton4.setText("ELLIPSE");
jButton4.setBorder(new javax.swing.border.SoftBevelBorder(0));

jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("COULEUR DE LIGNE");
jLabel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "NOIR", "VERT", "JAUNE", "ROUGE", "BLEU" }));

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);

jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("COULEUR DE REMPLISSAGE");
jLabel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "NOIR", "VERT", "JAUNE", "ROUGE", "BLEU" }));

javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);

jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder(3, new java.awt.Color(153, 153, 153), new java.awt.Color(153, 153, 153)));

javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))))
.addContainerGap(49, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);

pack();
}// </editor-fold>

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Paint.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Paint.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Paint.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Paint.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Paint().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
// End of variables declaration
}
0
KX Messages postés 16761 Date d'inscription   Statut Modérateur Dernière intervention   3 020
 
"je comprend pas trop bien la structure dont vous avez fait"
Forcément, NetBeans te fais de jolies fenêtres tout seul, mais ça ne t'apprend rien sur le Java !
Là j'ai fait un petit code à la main, très simple, et tu ne comprends rien... mais j'imagine que tu ne comprenais de toute façon pas le code que te générais NetBeans et c'est pour ça que tu n'y arrives pas.
Si tu veux apprendre à faire de vraies interfaces graphiques, fais le code toi même, sans NetBeans pour te materner, car il a un effet pervers !

Voici comment tu pourrais faire :

Remarque 1 : je n'ai fais que les rectangles et les cercles, en noir et en vert. À toi de faire le reste, je t'ai laissé des pointillés là où il fallait compléter...

Remarque 2 : tu vas forcément voir dans mon code plus ou moins la même "structure" que celle que tu ne comprenais pas tout à l'heure, à toi de regarder dans un cours comment ça marche.

1) ajoutes cette ligne de code tout à la fin du programme (juste avant "// End of variables declaration")

private int shape;
2) ajoutes ces lignes de codes tout au début du programme (juste après "package javaapplication;")

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

3) remplaces ligne 45 (environ), la ligne "jPanel3 = new javax.swing.JPanel();" par tout le code qui suit :

jPanel3 = new javax.swing.JPanel()
{    
    @Override
    public void paint(Graphics g)
    {
        super.paint(g);
        int w = getWidth(), h = getHeight(), m = Math.min(w, h);
        
        switch (jComboBox2.getSelectedIndex())
        {
        case 0 : g.setColor(Color.BLACK); break;
        case 1 : g.setColor(Color.GREEN); break;
        // ...
        }
                
        switch (shape)
        {
        case 1 : g.fillRect(w/5, h/5, 3*w/5, 3*h/5); break;
        case 2 : g.fillOval(w/2-m/2, h/2-m/2, m, m); break;
        // ...
        }
        
        switch (jComboBox1.getSelectedIndex())
        {
        case 0 : g.setColor(Color.BLACK); break;
        case 1 : g.setColor(Color.GREEN); break;
        // ...
        }
        
        switch (shape)
        {
        case 1 : g.drawRect(w/5, h/5, 3*w/5, 3*h/5); break;
        case 2 : g.drawOval(w/2-m/2, h/2-m/2, m, m); break;
        // ...
        }
    }
};

jButton1.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        shape=1;
        jPanel3.repaint();
    }
});

jButton2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        shape=2;
        jPanel3.repaint();
    }
});

// ...

jComboBox1.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        jPanel3.repaint();
    }
});

jComboBox2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        jPanel3.repaint();
    }
});
0
ndoyestory Messages postés 52 Date d'inscription   Statut Membre Dernière intervention   1
 
merci bien pour complément, mais je sais pas si vous avez de compiler
j'ai ajouté le complément avec Notepad ++ mais il génère beaucoup d'erreur en compilant avec le CMD
0
KX Messages postés 16761 Date d'inscription   Statut Modérateur Dernière intervention   3 020
 
Bien sûr que j'ai testé, et si tu mets le code aux endroits que je t'ai indiqué il n'y a aucune erreur.
Voici le fichier que tu devrais obtenir après modification : Paint.java
0