如何单击图片然后将该图片显示在新的JFrame中?

时间:2015-04-21 23:59:30

标签: java swing

我有一个JFrame开头有12张不同的图片。我想点击一个,然后在新的JFrame中,显示相同的图片。在我的代码中,衬衫是我的JFrame,包含12张图片,我希望点击的图片出现在名为sizes的新JFrame中。我创建了一个名为select的JLabel类型的ArrayList。这是我的代码:

final JFrame shirts = new JFrame("T-shirts");

          JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3));

          for (int i = 1; i < 13; i++) {
            l = new JLabel(new ImageIcon("T-shirts/"+i+".jpg"), JLabel.CENTER);

            l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
            l.setFont(l.getFont().deriveFont(20f));
            panel.add(l);
            select.add(l);
          }//end of for loop

          panel.addMouseListener(new MouseAdapter(){
            public void mouseClicked(MouseEvent e){
              sizes = new JFrame("Shopping");
              sizes.setVisible(true);
              sizes.setSize(500, 500);
              sizes.setLocation(100,200);
              shirts.dispose();


            for(int i=0; i<12; i++){
                if(e.getSource()==select.get(i)){
            JLabel addition = newJLabel(newImageIcon(select.get(i).getText()));
                  //sizes.add(select.get(i));//Picture isn't added!!
               }//end of if

            }//end of for
            }//end of method  
          });//end of listener


          shirts.setContentPane(panel);
          shirts.setSize(1000, 1000);
          shirts.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          shirts.setVisible(true);

3 个答案:

答案 0 :(得分:3)

How to Write a Mouse Listener开始。

基本上,您希望使用代表您图片的MouseListener注册JLabel并实施mouseClicked方法。

然后,您希望获取被点击的Icon的{​​{1}}属性并将其传递给您的新框架,您只需使用该属性设置另一个JLabel属性{ {1}}

像...一样的东西。

Icon

作为例子

您可能还想查看The Use of Multiple JFrames, Good/Bad Practice?,并考虑使用JLabeladdition.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { JLabel label = (JLabel) e.getComponent(); Icon icon = label.getIcon(); // Create new frame and pass it the icon value } }); 而不是其他CardLayout ...这可能会变得混乱

答案 1 :(得分:2)

尝试将每张照片设为JButton,或者至少在每张照片后面放置一个隐形按钮。然后,当在ActionListener扩展类中按下它们时,创建新的JFrame,图片变大。

答案 2 :(得分:2)

您可以使用JButton并使其看起来像JLabel

JButton button = new JButton( new ImageIcon("..." ));
button.setBorderPainted( false );
button.setContentFilled( false );
button.setFocusPainted( false );
button.addActionListener( new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        JButton button = (JButton)e.getSource();
        Icon icon = button.getIcon();
        // do something with the Icon.
    }
});

然后您可以在按钮上添加ActionListener

ActionListener比使用MouseListener并处理mouseClicked事件更可靠。只有在同一鼠标点生成mouseClickedmousePressed事件时,才会生成mouseReleased事件。因此,如果鼠标在两个事件之间按像素移动,您将不会收到用户认为是随机问题的mouseClicked事件。