Java 使用卡片布局构建图像查看器?
我让程序运行标签,但我不能让它使用图像。我是个初学者,到目前为止我只能想到这些。它可以运行,但我不理解如何在代码中实现图像Java 使用卡片布局构建图像查看器?,java,image,layout,cardlayout,Java,Image,Layout,Cardlayout,我让程序运行标签,但我不能让它使用图像。我是个初学者,到目前为止我只能想到这些。它可以运行,但我不理解如何在代码中实现图像 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CardLayoutExample extends JFrame implements KeyListener { private Container pane = getContentPane(); pri
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();
}
}
要使用JLabel设置映像,请在构造函数中传入一个图标对象,或者在类上调用setIcon方法
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*");
仅供参考,您没有正确地将项目添加到CardLayout中。切换窗格时,系统在作为窗格标识符传入的字符串上执行“==”(而不是.equals)。您很快就会在测试中看到这个问题。解决此问题的最简单方法是创建表示每个窗格的静态最终字符串,并将其用作标识符。要使用JLabel设置图像,请在构造函数中传递图标对象,或在类上调用setIcon方法
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*");
仅供参考,您没有正确地将项目添加到CardLayout中。切换窗格时,系统在作为窗格标识符传入的字符串上执行“==”(而不是.equals)。您很快就会在测试中看到这个问题。最简单的方法是创建表示每个窗格的静态最终字符串,并将其用作标识符