views:

17

answers:

1

i got the program to run with labels but i cant get it to use images. im a beginner and this is all i can come up with so far. it runs but i dont understand implementing images into this code.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CardLayoutExample extends JFrame implements KeyListener

{

 private Container pane = getContentPane();
 private CardLayout layout = new CardLayout();

 public CardLayoutExample()
 {
  pane.setLayout(layout);

  pane.add(new JLabel("hey",  SwingConstants.CENTER), "hey");
  pane.add(new JLabel("what",  SwingConstants.CENTER), "what");
  pane.add(new JLabel("is",  SwingConstants.CENTER), "is");
  pane.add(new JLabel("your",  SwingConstants.CENTER), "your");
  pane.add(new JLabel("first",  SwingConstants.CENTER), "first");
  pane.add(new JLabel("name",  SwingConstants.CENTER), "name");

  addKeyListener(this);

  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setTitle("CardLayout Example");
  setSize(410,310);
  setVisible(true);

 }

 public void keyTyped(KeyEvent event)
 {
  layout.next(pane);
 }

 public void keyPressed(KeyEvent event){}
 public void keyReleased(KeyEvent event){}

 public static void main(String args[])
 {
  CardLayoutExample top = new CardLayoutExample();
 }
}
+1  A: 

To set an image with a JLabel, pass in an Icon object in the constructor, or call the setIcon method on your class.

Icon icon1 = new ImageIcon("path to image filename");
JLabel label1 = new JLabel("message 1", icon1, SwingConstants.CENTER);
pane.add(label1, "*You need a static final string here - see below*");


FYI, you are not adding items to your CardLayout correctly. When switching panes, the system does an "==" (not a .equals) on the string you pass in as the identifier of the pane. You'll see this problem soon in your testing. The easiest way around this is to create static final strings that represent each pane and use that as identifiers.

Starkey