Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用按键操作在面板中显示图像_Java_Swing_Jbutton - Fatal编程技术网

Java 如何使用按键操作在面板中显示图像

Java 如何使用按键操作在面板中显示图像,java,swing,jbutton,Java,Swing,Jbutton,我想通过按下按钮在面板上显示图像。我创建了一些代码 JButton btnNewButton = new JButton("next"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(i<files1.length){ BufferedImage

我想通过按下按钮在面板上显示图像。我创建了一些代码

JButton btnNewButton = new JButton("next");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if(i<files1.length){
                BufferedImage bi;
                try {
                    bi = ImageIO.read(new File(""+files1[i]));
                    System.out.println(files1[i]);
                    JLabel label = new JLabel(new ImageIcon(bi));
                    panel_1.add(label);
                    panel_1.repaint();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            else
                System.out.println("end of picture");
            i++;
        }
    });
JButton btnNewButton=新JButton(“下一步”);
addActionListener(新ActionListener(){
已执行的公共无效操作(操作事件arg0){

如果(i我的Java不是最好的,但显然我会说:

if(button.isPressed()) {
    Panel.visible;
}

我不知道确切的方法。这更像是一个建议。

您只给出了处于非工作状态的部分代码。请尝试包含所有相关代码(在本例中,包括面板和我的定义)或条带,以显示不工作的点。对我来说,这很有效:

public class Test {

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        final JLabel label = new JLabel();
        JButton button = new JButton("next");

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                BufferedImage bi = null;
                try {
                    bi = ImageIO.read(new File("pathtofile"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                label.setIcon(new ImageIcon(bi));
            }
        });

        frame.setContentPane(new JPanel());
        frame.getContentPane().add(button);
        frame.getContentPane().add(label);
        frame.pack();
        frame.setVisible(true);
    }
}

但是,考虑JLabor不是为了显示LavaGrand风格的图像。 但点击按钮后图像不会显示

看起来您缺少revalidate()。将组件添加到可见GUI时的基本代码是:

panel.add(....);
panel.revalidate(); // to invoke the layout manager
panel.repaint();

你想达到什么目的?我看到你一直在添加更多的标签。这是你真正想要的吗?还是你想获得幻灯片放映效果。多一些细节会有很大帮助。