Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Java - drawing images to a JPanel

Status
Not open for further replies.

atsea

Technical User
Feb 27, 2005
51
JP
I have experience using PHP, Perl and JavaScript, and am now planning to teach myself Java...

I have decided to work with the NetBeans 5.0 IDE, and have completed many tutorials most of which were simple applications that accept command line arguments. Recently I have moved to learning GUI development with NetBeans 5. I have been able to create forms without much of a problem but have hit a wall when it comes to displaying/manipulating graphics.

Currently I am working toward an intricate "Towers of Hanoi" game, I'm sure most programmers are familiar with...I chose this not(exclusivly) for its recursive solution but to familiarize myself with drawing shapes and event handling.

I'm having trouble getting this one started...

I think the main problem is with the code NetBeans automatically generates when developing a GUI interface.

To start, I have created the layout using NB5 GUI builder and have been able to apply listeners and handlers to many different components...

What I can't figure out is how to add images to my JPanel. Can anyone show me how to do this? I just would like to have a couple Rectangles (3d would be nice) that appear on the JPanel (gameSheet), that should get the ball rolling. Once I have that I can worry about adding some event handlers to make them draggable.

Any help would be greatly appreciated.

Below is the basic code the NB generates when using the GUI builder.

Code:
/*
 * hanoiWin.java
 *
 * Created on 2006/08/28, 17:14
 */

package my.tower;


import javax.swing.JLabel;
import javax.swing.JPanel;


public class hanoiWin extends javax.swing.JFrame {
    
    /** Creates new form hanoiWin */
    public hanoiWin() {
        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. 
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
  
    }// </editor-fold>
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new hanoiWin().setVisible(true);
            }
        });

    }
    
    
    // Variables declaration - do not modify
    private javax.swing.JPanel dataPanel;
    private javax.swing.JPanel gameSheet;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JPanel setupPanel;
    // End of variables declaration
    
}

atsea
 
Hope this can help you a bit.
Code:
import java.awt.BorderLayout;
import java.awt.Graphics;

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

public class ImageFrame extends JFrame {

	private static final long serialVersionUID = 1L;

	private JPanel jContentPane = null;

	/**
	 * This is the default constructor
	 */
	public ImageFrame() {
		super();
		initialize();
	}

	public void paint(Graphics g){
		g.drawRect(20,20, 50, 50);
		g.fillRect(30, 60, 40, 20);
		
	}
	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(300, 200);
		this.setContentPane(getJContentPane());
		this.setTitle("JFrame");
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
		}
		return jContentPane;
	}

}

Chinese Java Faq Forum
 
wangdong,

Thanks for the quick reply...

Actually I have been able to accomplish a few classes similar to yours that print out various shapes. The whole problem began after I used NetBeans GUI builder.

Specifically, in the GUI builder, I added a JPanel and named it gameSheet.
NB generated all the code, i.e...
Code:
private void initComponents() {
...
...
...
gameSheet = new javax.swing.JPanel();
...
...
...
}

private javax.swing.JPanel gameSheet;

All I am trying to do is add rectangles to "gameSheet".

Any Suggestions?

atsea
 
it would be the same. I have tried to add an extra JPanel.
just copy the following code, and run it from NetBeans.
Code:
import java.awt.BorderLayout;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.GridBagLayout;

public class ImageFrame extends JFrame {

	private static final long serialVersionUID = 1L;

	private JPanel jContentPane = null;

	private JPanel jPanel = null;

	/**
	 * This is the default constructor
	 */
	public ImageFrame() {
		super();
		initialize();
	}

	public void paint(Graphics g){
		g.drawRect(20,20, 50, 50);
		g.fillRect(30, 60, 40, 20);
		
	}
	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(300, 200);
		this.setContentPane(getJContentPane());
		this.setTitle("JFrame");
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getJPanel(), BorderLayout.CENTER);
		}
		return jContentPane;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			jPanel = new JPanel();
			jPanel.setLayout(new BorderLayout());
		}
		return jPanel;
	}

}

Chinese Java Faq Forum
 
wangdong,

Thanks for taking the time to look into my issue.

You'll have to forgive me, as mentioned, I just started getting into GUI design.
I will cut and paste your code into my netBeans and give it a try, but I do not think it will produce the results I am after (i.e. 1. there is no main method 2. it is not using the NetBeans generated code, etc)

I have been able to create single JPanels and draw to them using your method:
constructing a JPanel and creating a paint() method to override the same method in the Container Class...

My problem is trying to accomplish something similar but using the code that is generated by the NetBeans GUI builder. I can create/add the components fine, I just cant figure out how to draw to them.

In the code I provided in my previous post (minus a large section that NB assures me no editing is requierd...if you think this will help I can post it) generates:
JFrame with 3 JPanels...
2 JPanels will act as forms (accept/display info via textbox, buttons, etc)
1 JPanel (gameSheet) will handle the display.


For example:

I could add an event that changes the BackgroundColor of "gameSheet" if the user clicks on the JPanel "gameSheet".
Code:
    private void gameSheetMousePressed(java.awt.event.MouseEvent evt) {

                gameSheet.setBackground(Color.black);
        
    }

no problem...but I still don't know how to draw specifially to "gameSheet".

Ideally I am hoping for somthing like
Code:
"gameSheet.paint(shape);"
but I don't think thats going to happen.

Any more suggestions?

Playing around with your code now.

Thanks,

atsea
 
Here is the entire code...

Trying to figure out how to add/draw shapes to gameSheet.


Code:
package my.hanoi;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

import javax.swing.JLabel;
import javax.swing.JPanel;




public class hanoiWin extends javax.swing.JFrame {
    
    /** Creates new form hanoiWin */
    public hanoiWin() {
        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.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
        setupPanel = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        dataPanel = new javax.swing.JPanel();
        gameSheet = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setupPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Setup"));
        jTextField1.setToolTipText("Enter the # of Disks");
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        jLabel1.setText("# of Disks:");

        org.jdesktop.layout.GroupLayout setupPanelLayout = new org.jdesktop.layout.GroupLayout(setupPanel);
        setupPanel.setLayout(setupPanelLayout);
        setupPanelLayout.setHorizontalGroup(
            setupPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(setupPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 35, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(43, Short.MAX_VALUE))
        );
        setupPanelLayout.setVerticalGroup(
            setupPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(setupPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(setupPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(276, Short.MAX_VALUE))
        );

        dataPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Data Center"));
        org.jdesktop.layout.GroupLayout dataPanelLayout = new org.jdesktop.layout.GroupLayout(dataPanel);
        dataPanel.setLayout(dataPanelLayout);
        dataPanelLayout.setHorizontalGroup(
            dataPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 707, Short.MAX_VALUE)
        );
        dataPanelLayout.setVerticalGroup(
            dataPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 198, Short.MAX_VALUE)
        );

        gameSheet.setBackground(Color.ORANGE);
        gameSheet.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                gameSheetMousePressed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout gameSheetLayout = new org.jdesktop.layout.GroupLayout(gameSheet);
        gameSheet.setLayout(gameSheetLayout);
        gameSheetLayout.setHorizontalGroup(
            gameSheetLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 550, Short.MAX_VALUE)
        );
        gameSheetLayout.setVerticalGroup(
            gameSheetLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 333, Short.MAX_VALUE)
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(dataPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(gameSheet, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(setupPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(gameSheet, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(setupPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(dataPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        pack();
    }// </editor-fold>

    private void gameSheetMousePressed(java.awt.event.MouseEvent evt) {

                gameSheet.setBackground(Color.black);
        
    }
    
    /**
     *eventually this field will hold the number of rectangles to draw
     *this event will dynamically generate the rectangles as the # is typed
     *currently this is here to test
     */
    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {                                        
        

        
    }                                       
    
  
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new hanoiWin().setVisible(true);
            }
        });
        
    }
    
    
    
    // Variables declaration - do not modify
    private javax.swing.JPanel dataPanel;
    private javax.swing.JPanel gameSheet;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JPanel setupPanel;
    // End of variables declaration
    
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top