[英]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.