Recreate a Jpanel

911 views Asked by At

I've been trying to add a drawing to an existing JPanel in a JForm. This JForm is created in Netbeans (with the 'add jform' option). In that form, i've placed a JPanel. In the source code i want to change the JPanel, so a drawing appears. I've been trying this, but it will not work... Is it possible to do it this way (if true, wat i've been doing wrong?)...

jPanel3 = new JPanel() {
     @Override
     public void paintComponent( Graphics g ) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;

        Line2D line = new Line2D.Double(10, 10, 120, 120);
        g2.setColor(Color.blue);
        g2.setStroke(new BasicStroke(10));
        g2.draw(line);
     }
};

Regards, Joppe

(sorry for my bad English... I don't speak English as first language...)

EDIT: some code:

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

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JPanel;

/**
 *
 * @author Joppe
 */
public class JavaTest extends javax.swing.JFrame {

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

    jPanel3 = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel3.addContainerListener(new java.awt.event.ContainerAdapter() {
        public void componentAdded(java.awt.event.ContainerEvent evt) {
            jPanel3ComponentAdded(evt);
        }
    });

    javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 380, Short.MAX_VALUE)
    );
    jPanel3Layout.setVerticalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 278, 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()
            .addContainerGap()
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );

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

private void jPanel3ComponentAdded(java.awt.event.ContainerEvent evt) {                                       
    jPanel3 = new JPanel() {
        @Override
        public void paintComponent( Graphics g ) {
           super.paintComponent(g);
           Graphics2D g2 = (Graphics2D)g;

           Line2D line = new Line2D.Double(10, 10, 120, 120);
           g2.setColor(Color.blue);
           g2.setStroke(new BasicStroke(10));
           g2.draw(line);
        }

        @Override 
        public Dimension getPreferredSize() { 
            return new Dimension(250,200); 
        }
    };
}                                      

/**
 * @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(JavaTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(JavaTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(JavaTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(JavaTest.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 JavaTest().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JPanel jPanel3;
// End of variables declaration                   
}
2

There are 2 answers

4
camickr On

When you do custom painting you also need to override the getPreferredSize() of the panel to retrun the size of the custom painting, otherwise the size is assumed to be (0, 0) so there is nothing to paint. You should also override the minimum/maximums sizes as well.

Read the section from the Swing tutorial on Custom Painting for more information and examples.

If you need more help then post a proper SSCCE that demonstrates the problem.

Edit:

jPanel3 = new javax.swing.JPanel();

The above line of code creates an empty panel. Later there is code that adds that panel to the frame, but there is nothing to display in that panel.

jPanel3.addContainerListener(new java.awt.event.ContainerAdapter() {
    public void componentAdded(java.awt.event.ContainerEvent evt) {
        jPanel3ComponentAdded(evt);
    }
});

Not sure what the point of this code is. The event should be fired when you add a component to jPanel3. I don't see:

jPanel3.add(....);

anywhere in your code so this event should never be fired. If this event does get fired then the code executed is:

jPanel3 = new JPanel() {
    @Override
    public void paintComponent( Graphics g ) {
        ...

Well this code doesn't do anything. All it does is created a component and change the variable jPanel3 to reference this component. However, the component is NOT added to the GUI anywhere so you will never see the custom painting.

Your problem is with the IDE. My recommendation is to forget about the IDE and learn how to create a GUI manually. I already gave you a link to the Swing tutorial on "Custom Painting" which does this. It is better to spend time learning Java, then it is to learn an IDE. Once you understand how Java works you will probably be able to understand the IDE better.

Anyway, I can't advise you on how to use the IDE because I have never used one.

0
kiheru On
private void jPanel3ComponentAdded(java.awt.event.ContainerEvent evt) {                                       
    jPanel3 = new JPanel() {
    ...

Changing jPanel3 after it has been already added does not help - the panel that was added to the container is a normal JPanel, not the one with the custom painting. For a trivial case you could simply make jPanel3 the content pane, but that does not work for more complex layout, which is likely the case when you use a GUI builder.

Instead:

  1. Choose the location where you want to have the custom component. For your sample it would be jPanel3.
  2. Set the layout manager of jPanel3 to something that is more manageable than GroupLayout when using manually, for example FlowLayout (you can still use GroupLayout, if you insist, but it's a bit complicated). This can be done using the form designer.
  3. In code, add your custom painting panel to jPanel3:

    JPanel customPanel = new JPanel() {
        @Override
        protected void paintComponent( Graphics g ) {
           super.paintComponent(g);
           ...
        }
    
        @Override 
        public Dimension getPreferredSize() { 
            return new Dimension(250,200); 
        }
    };
    jPanel3.add(customPanel);
    

The sample also needs a pack() call after that, because the one in initComponents() is done before the custom panel is added.

Another way: The form designer you are using also supports custom components, and that may well be your preferred way to insert them. For netbeans, you can find the instructions here.