Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Creating a gridlayout of jlabels and jbuttons in a JPanel

843806Dec 21 2007 — edited Dec 21 2007
The assignment:

"Create a JPanel that contains an 8x8 checkerboard. Make all of the red squares JButtons and be sure to add them to the JPanel. Make all of the black squares JLabels and add them to the JPanel. Don't forget, you must use the add method to attach the JPanel to the JApplet's contentPane but that there is no contentPane for a JPanel. Be sure to set up any interfaces to handle the JButtons. Use a GridLayout to position and size each of the components instead of absolute locations and sizes."

This assignment introduces the JPanel to me for the first time, I have not seen what the JDialog and JFrame are.

What I have:
import java.awt.*;
import javax.swing.*;

/**
 * Class CheckerBoard - write a description of the class here
 * 
 * @author (your name) 
 * @version (a version number)
 */
public class CheckerBoard extends JPanel
{
    JButton redSquare;
    JLabel blackSquare;
    
     /**
     * Called by the browser or applet viewer to inform this JApplet that it
     * has been loaded into the system. It is always called before the first 
     * time that the start method is called.
     */
    public void init()
    {
        JPanel p = new JPanel();
        setLayout(new GridLayout(8,8));
        setSize(512,512);
        
        ImageIcon red = new ImageIcon("GUI-006-RedButton.png");
        ImageIcon black = new ImageIcon("GUI-006-BlackSquare.png");
        
        blackSquare = new JLabel(black);
        blackSquare.setSize(64,64);
        
        redSquare = new JButton(red);
        redSquare.setSize(64,64);
        
        for (int i = 0; i < 64; i++) {
            if ((i % 2) == 1)
                add(blackSquare);
            else
               add(redSquare);
            }
        // this is a workaround for a security conflict with some browsers
        // including some versions of Netscape & Internet Explorer which do 
        // not allow access to the AWT system event queue which JApplets do 
        // on startup to check access. May not be necessary with your browser. 
        JRootPane rootPane = this.getRootPane();    
        rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
    }
}
After successfully compiling it when I try to run it there appears to be nothing to run. I've tried messing around with content panes but I'm not sure if I need to add one for this assignment at all.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 18 2008
Added on Dec 21 2007
4 comments
609 views