Tonno22
Tonno22

Reputation: 165

Trying to draw on Jpanel within GUI

enter image description here

I'm currently doing an exercise where we make a welcome to target sign, so at the top it'll say welcome to target, then there will be the Target logo, when you click on the target logo it turns blue.

How can I draw on the JPanel? I need to draw three different circles, and fill them? I have a frame TargetLogoUI, and 2 panels, a TargetMessagePanel, and a TargetLogoPanel.

I think I have the message panel correct, and just need to do the logo panel.

Here are my three different classes.

TargetLogoUI

public class TargetLogoUI extends javax.swing.JFrame {

/**
 * Creates new form TargetLogoUI
 */
public TargetLogoUI() {
    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() {

    targetMessagePanel1 = new TargetMessagePanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,     layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(targetMessagePanel1, javax.swing.GroupLayout.PREFERRED_SIZE,     699, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(targetMessagePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 369, Short.MAX_VALUE))
    );

    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 http://download.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(TargetLogoUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(TargetLogoUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(TargetLogoUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(TargetLogoUI.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 TargetLogoUI().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private TargetMessagePanel targetMessagePanel1;
// End of variables declaration                   
}

TargetMessagePanel

import java.awt.Font;
import javax.swing.JComponent;



public class TargetMessagePanel extends javax.swing.JPanel {





/**
 * Creates new form TargetMessagePanel
 */
public TargetMessagePanel() {

    Font f = new Font("Helvetica", Font.BOLD,72);
    Font JComponent = null;
    setFont(JComponent);
    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() {

    jPanel1 = new javax.swing.JPanel();
    jTextField1 = new javax.swing.JTextField();

    jPanel1.setToolTipText("Welcome to Target");

    jTextField1.setBackground(new java.awt.Color(204, 204, 204));
    jTextField1.setFont(new java.awt.Font("Lucida Sans", 1, 72)); // NOI18N
    jTextField1.setText("Welcome to Target");
    jTextField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );
}// </editor-fold>                        

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
}                                           

// Variables declaration - do not modify                     
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration                   
}

TargetLogoPanel

public class TargetLogoPanel extends javax.swing.JPanel {

/**
 * Creates new form TargetLogoPanel
 */
public TargetLogoPanel() {
    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() {

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 700, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
}// </editor-fold>                        
// Variables declaration - do not modify                     
// End of variables declaration                   
}

Upvotes: 0

Views: 370

Answers (2)

Braj
Braj

Reputation: 46871

You have to override paintComponent(Graphics g) method for drawing on JPanel.

Note: you can change the position and size of circle by using below code:

new Ellipse2D.Double(xcoord, ycoord, width, height)

Here is the sample code:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.geom.Ellipse2D;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;

final MyCustomJPanel panel = new MyCustomJPanel();
panel.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        panel.setTarget(true);
        panel.repaint();
    }
});

class MyCustomJPanel extends JPanel {
    private boolean isTarget;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;

        Color c = null;
        if (isTarget) {
            c = Color.BLUE;
        } else {
            c = Color.RED;
        }

        g2.setColor(c);
        g2.fill(new Ellipse2D.Double(50, 50, 150, 150));

        g2.setColor(Color.WHITE);
        g2.fill(new Ellipse2D.Double(75, 75, 100, 100));

        g2.setColor(c);
        g2.fill(new Ellipse2D.Double(100, 100, 50, 50));
    }

    public boolean isTarget() {
        return isTarget;
    }

    public void setTarget(boolean isTarget) {
        this.isTarget = isTarget;
    }

}

Upvotes: 0

camickr
camickr

Reputation: 324197

and just need to do the logo panel.

Read the section from the Swing tutorial on Custom Painting. Basically you need to override the paintComponent() method to do your custom painting.

I would start by drawing the largest oval. Change the color and draw the next smallest oval and so on. The red/blue color would be set by using the setForeground(...) method. Then in the painting code you can use the getForeground() method to get the color.

When you click on the panel you then change the foreground color and invoke repaint() on the panel.

Upvotes: 1

Related Questions