繁体   English   中英

使用Swing创建可点击的图像

[英]Create a clickable image with Swing

我正在尝试在Swing中创建一个图像浏览器,该浏览器将允许用户选择一个图像,然后单击图像的右半部分前进到下一个图像,然后单击左半部移动到上一个图像。

我尝试使用MouseListeners进行此操作,但是除非使用pack();否则MouseClicked不会注册pack(); ,但这导致我的图片消失,除非将UI拖出。

这是用于显示图像的代码:

class ImageFrame extends JFrame
{
    private final JFileChooser chooser;
    private BufferedImage image = null;
    int WIDTH = 1080; int HEIGHT = 620;

    // ==========================================
    // constructor

    public ImageFrame (int width, int height)
    {
        // --------------------------------------
        // setup the frame's attributes
        this.setTitle("Image-P3 Player");
        this.setSize( width,height );

        // add a menu to the frame
        addMenu();

        // --------------------------------------
        // setup the file chooser dialog

        chooser = new JFileChooser();
        chooser.setCurrentDirectory( new File( ".") );
    }
    addMouseListener( new MouseAdapter()
        {
        public void mouseClicked( MouseEvent e){
            System.out.println("Mouse clicked!");
            if(e.getButton() == 1){
                int x = e.getX();
                System.out.println("X: "+x);
                if(x>540){
                    System.out.println("Next image!");
                }
                else{
                    System.out.println("Previous image!");
                }
            }
        }
    } );

然后有一个JMenu导致了这一系列方法:

private void open()
{
    File file = getFile();
    if( file != null)
    {
        displayFile( file );
    }
}

private File getFile()
{
    File file = null;

    if ( chooser.showOpenDialog( this ) == JFileChooser.APPROVE_OPTION )
    {
        file = chooser.getSelectedFile();
    }

    return file;
}

private void displayFile( File file )
{
//some code to resize the image to the JFrame's dimensions
}

// ------------------------------------------
// Display Buffered Image

public void displayBufferedImage( ImageIcon image )
{
    this.setContentPane( new JScrollPane( new JLabel( image  ) ) );

    this.validate();
}

是否有一种简单的方法可以将MouseListener添加到JScrollPane或JLabel,以便GUI中显示的图像将注册用户单击,而不会导致组件混乱。

感谢MadProgrammer,它成功了。 我在顶部用其他变量初始化和实例化了JLabel:

JLabel label = new JLabel();

然后在我的displayBufferedImage方法中的JLabel上使用.setIcon(ImageIcon icon)

public void displayBufferedImage( ImageIcon image )
{
    label.setIcon(image);
    this.setContentPane( new JScrollPane( label ) );

    this.validate();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM