2017-12-01 39 views
0

スウィングで画像を選択し、画像の右半分をクリックして次の画像に移動し、左に移動する画像ブラウザを作成しようとしています半分は前のものに移動します。スウィングでクリック可能な画像を作成する

私はMouseListenersでこれをやろうとしましたが、pack();を使用しない限りMouseClickedは登録されませんでしたが、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(); 
} 

追加するための簡単な方法はありますJScrollPaneまたはJLabelのMouseListenerを使用して、GUIに表示されるイメージが、コンポーネントを叩くことなくユーザーのクリックを登録するようにします。

+1

がインスタンスフィールドとして 'JLabel'の単一のインスタンスを作成します。 'MouseListener'を追加してください。 – MadProgrammer

+1

ラベルの新しいインスタンスを作成するのではなく、 'JLabel'の' icon'プロパティを変更してください。私には不愉快に聞こえる。画像を表示するにはラベルを使いますが、マウスやキーボードの起動に応答できるように(「<' and '>」などのテキストを使用して)いずれかの側にボタンを配置します。 –

答えて

0

ありがとう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(); 
} 
+0

ラベルがすでにGUIに追加されている場合、そのメソッドの最後の2行のコードは不要です。それで1行しか残っていなければ、メソッドにはあまり意味がないようです。 –

関連する問題