开发者

build an image viewer with card layout?

开发者 https://www.devze.com 2023-01-12 08:20 出处:网络
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 w开发者_开发百科ith so far. it runs but i dont understand implementing images into thi

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 w开发者_开发百科ith 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();
 }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消