2014-10-13 4 views
-1

Java의 JFrame을 사용하여 .jpeg 이미지를 표시하고 있습니다. 나는 체크 박스가 선택되었을 때 이미지에 수평 슬라이딩 효과를 시작해야한다. 기본적으로 체크 박스가 선택되면 이미지가 왼쪽에서 오른쪽으로 슬라이딩되기 시작합니다. 몇 초가 지나면 끝납니다. 확인란이 선택 취소 될 때까지 영원히 다시 시작하십시오. 이 기능을 어떻게 추가 할 수 있습니까?Java JFrame의 이미지에 가시성 효과 추가

편집 : 실제로 나는 그림 자체가 움직이는 것은 아닙니다. 나는 그림이 안정적이고 정적이지만 그림이 왼쪽에서 오른쪽으로 수평 슬라이딩 효과로 보이기 시작하고 다시 시작된다는 것을 의미합니다. 나는 그것이 충분히 분명하기를 바란다.

여기에 가정은 (자바 튜토리얼에서 가져온) 이미지와 체크 박스를 표시하는 내 코드입니다 :

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

/* 
* CheckBoxDemo.java requires 16 image files in the images/geek 
* directory: 
* geek-----.gif, geek-c---.gif, geek--g--.gif, geek---h-.gif, geek----t.gif, 
* geek-cg--.gif, ..., geek-cght.gif. 
*/ 
public class CheckBoxDemo extends JPanel 
          implements ItemListener { 
    JCheckBox chinButton; 
    JCheckBox glassesButton; 
    JCheckBox hairButton; 
    JCheckBox teethButton; 

    /* 
    * Four accessory choices provide for 16 different 
    * combinations. The image for each combination is 
    * contained in a separate image file whose name indicates 
    * the accessories. The filenames are "geek-XXXX.gif" 
    * where XXXX can be one of the following 16 choices. 
    * The "choices" StringBuffer contains the string that 
    * indicates the current selection and is used to generate 
    * the file name of the image to display. 

     ----    //zero accessories 

     c---    //one accessory 
     -g-- 
     --h- 
     ---t 

     cg--    //two accessories 
     c-h- 
     c--t 
     -gh- 
     -g-t 
     --ht 

     -ght    //three accessories 
     c-ht 
     cg-t 
     cgh- 

     cght    //all accessories 
    */ 

    StringBuffer choices; 
    JLabel pictureLabel; 

    public CheckBoxDemo() { 
     super(new BorderLayout()); 

     //Create the check boxes. 
     chinButton = new JCheckBox("Chin"); 
     chinButton.setMnemonic(KeyEvent.VK_C); 
     chinButton.setSelected(true); 

     glassesButton = new JCheckBox("Glasses"); 
     glassesButton.setMnemonic(KeyEvent.VK_G); 
     glassesButton.setSelected(true); 

     hairButton = new JCheckBox("Hair"); 
     hairButton.setMnemonic(KeyEvent.VK_H); 
     hairButton.setSelected(true); 

     teethButton = new JCheckBox("Teeth"); 
     teethButton.setMnemonic(KeyEvent.VK_T); 
     teethButton.setSelected(true); 

     //Register a listener for the check boxes. 
     chinButton.addItemListener(this); 
     glassesButton.addItemListener(this); 
     hairButton.addItemListener(this); 
     teethButton.addItemListener(this); 

     //Indicates what's on the geek. 
     choices = new StringBuffer("cght"); 

     //Set up the picture label 
     pictureLabel = new JLabel(); 
     pictureLabel.setFont(pictureLabel.getFont().deriveFont(Font.ITALIC)); 
     updatePicture(); 

     //Put the check boxes in a column in a panel 
     JPanel checkPanel = new JPanel(new GridLayout(0, 1)); 
     checkPanel.add(chinButton); 
     checkPanel.add(glassesButton); 
     checkPanel.add(hairButton); 
     checkPanel.add(teethButton); 

     add(checkPanel, BorderLayout.LINE_START); 
     add(pictureLabel, BorderLayout.CENTER); 
     setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); 
    } 

    /** Listens to the check boxes. */ 
    public void itemStateChanged(ItemEvent e) { 
     int index = 0; 
     char c = '-'; 
     Object source = e.getItemSelectable(); 

     if (source == chinButton) { 
      index = 0; 
      c = 'c'; 
     } else if (source == glassesButton) { 
      index = 1; 
      c = 'g'; 
     } else if (source == hairButton) { 
      index = 2; 
      c = 'h'; 
     } else if (source == teethButton) { 
      index = 3; 
      c = 't'; 
     } 

     //Now that we know which button was pushed, find out 
     //whether it was selected or deselected. 
     if (e.getStateChange() == ItemEvent.DESELECTED) { 
      c = '-'; 
     } 

     //Apply the change to the string. 
     choices.setCharAt(index, c); 

     updatePicture(); 
    } 

    protected void updatePicture() { 
     //Get the icon corresponding to the image. 
     ImageIcon icon = createImageIcon(
            "images/geek/geek-" 
            + choices.toString() 
            + ".gif"); 
     pictureLabel.setIcon(icon); 
     pictureLabel.setToolTipText(choices.toString()); 
     if (icon == null) { 
      pictureLabel.setText("Missing Image"); 
     } else { 
      pictureLabel.setText(null); 
     } 
    } 

    /** Returns an ImageIcon, or null if the path was invalid. */ 
    protected static ImageIcon createImageIcon(String path) { 
     java.net.URL imgURL = CheckBoxDemo.class.getResource(path); 
     if (imgURL != null) { 
      return new ImageIcon(imgURL); 
     } else { 
      System.err.println("Couldn't find file: " + path); 
      return null; 
     } 
    } 

    /** 
    * Create the GUI and show it. For thread safety, 
    * this method should be invoked from the 
    * event-dispatching thread. 
    */ 
    private static void createAndShowGUI() { 
     //Create and set up the window. 
     JFrame frame = new JFrame("CheckBoxDemo"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     //Create and set up the content pane. 
     JComponent newContentPane = new CheckBoxDemo(); 
     newContentPane.setOpaque(true); //content panes must be opaque 
     frame.setContentPane(newContentPane); 

     //Display the window. 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     //Schedule a job for the event-dispatching thread: 
     //creating and showing this application's GUI. 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 
} 
+0

* ... 당신이 페이딩 효과를 할 수있는 마스킹 기술을 사용할 수 있습니다 당신은 무엇을 의미합니까? 예를 들어, 여기에 '누군가가 나를 위해 이것을 끝낼 수 있습니까?'와 같이 읽습니다. 응답은 'VTC 및 다운 투표'입니다. –

답변

4

가장 간단한 해결 방법은 예를 들어, javax.swing.Timer 같은 자신의 사용 무언가를 출시 할 것 ...

Fly baby, fly

import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
import javax.imageio.ImageIO; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.Timer; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class SlidingAnimation { 

    public static void main(String[] args) { 
     new SlidingAnimation(); 
    } 

    public SlidingAnimation() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     private BufferedImage img; 
     private int x = 0; 

     private Timer timer; 
     private long startTime = -1; 
     private int playTime = 4000; 

     public TestPane() { 
      try { 
       img = ImageIO.read(new File("...")); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
      timer = new Timer(40, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        float progress = 0f; 
        if (startTime == -1) { 
         startTime = System.currentTimeMillis(); 
        } else { 
         long currentTime = System.currentTimeMillis(); 
         long diff = currentTime - startTime; 

         if (diff >= playTime) { 
          diff = 0; 
          startTime = -1; 
         } 
         progress = diff/(float)playTime; 
        } 

        x = (int)((getWidth() - img.getWidth()) * progress); 
        repaint(); 
       } 
      }); 
      timer.start(); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth() * 2, img.getHeight()); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      if (img != null) { 
       Graphics2D g2d = (Graphics2D) g.create(); 
       int y = (getHeight() - img.getHeight())/2; 
       g2d.drawImage(img, x, y, this); 
       g2d.dispose(); 
      } 
     } 

    } 

} 

이 은 성 차이에 근거하여 현재 위치를 계산하는 두 개의 제 2 고리이며 예술 시간과 현재 시간 및 애니메이션이 움직여야하는 총 면적. 이것은 유연하게 만들지 만 직선적 인 선형 애니메이션입니다. 애니메이션을보다 사실적인 움직임을 제공하는 편리한 완화 및 완화 기능이 없습니다 ...

고급 애니메이션 효과의 경우, 당신이 좀 봐봐 격려해.

  • The Timing Framework. 비정상적인 일을하기 위해 코어에 대한 좋은 액세스를 제공하지만 시간이 지남에 따라 객체 속성을 변경할 수도 있습니다.
  • Trident. 시간이 지남에 따라 객체의 속성을 변경할 수있는 기능을 제공합니다. 사용하지 않았지만 실제로보기에는 좋았습니다.
  • Universal Tween Engine
또한 내가 귀하의 의견을 이해한다면, 당신이 원하는,

그래서 업데이트 스윙

에서 수행되는 방법을 사용자 정의 그림에 대한 자세한 내용은 Performing Custom Painting를 살펴 할 수 있습니다

크로스 페이드 효과. 이제는 몇 가지 방법이 있습니다. BufferedImage#subImage을 사용하면 원본 이미지의 "잘린"버전을 얻을 수 있지만 IMHO는 멋진 효과를 내지 못합니다.

대신 당신은 특히 *? "누군가가 나를 도울 수있다"

enter image description here

import java.awt.AlphaComposite; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.LinearGradientPaint; 
import java.awt.Rectangle; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.geom.Point2D; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
import javax.imageio.ImageIO; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.Timer; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class SlidingAnimation { 

    public static void main(String[] args) { 
     new SlidingAnimation(); 
    } 

    public SlidingAnimation() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     private BufferedImage img; 

     private Timer timer; 
     private long startTime = -1; 
     private int playTime = 4000; 

     private float progress; 

     public TestPane() { 
      try { 
       img = ImageIO.read(new File("...")); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
      timer = new Timer(40, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        if (startTime == -1) { 
         startTime = System.currentTimeMillis(); 
        } else { 
         long currentTime = System.currentTimeMillis(); 
         long diff = currentTime - startTime; 

         if (diff >= playTime) { 
          diff = 0; 
          startTime = -1; 
         } 
         progress = diff/(float) playTime; 
        } 

        repaint(); 
       } 
      }); 
      timer.start(); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight()); 
     } 

     protected BufferedImage generateImage() { 

      BufferedImage buffer = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB); 
      Graphics2D g2d = buffer.createGraphics(); 
      g2d.setBackground(new Color(0, 0, 0, 0)); 
      g2d.clearRect(0, 0, buffer.getWidth(), buffer.getHeight()); 
      g2d.drawImage(img, 0, 0, this); 

      float startAt = progress - 0.05f; 
      float endAt = progress + 0.05f; 

      if (endAt <= 0.1f) { 
       startAt = 0; 
       endAt = Math.max(0.1f, progress); 
      } else if (endAt >= 1f) { 
       endAt = 1f; 
       startAt = progress; 
      } 

      LinearGradientPaint lgp = new LinearGradientPaint(
        new Point2D.Float(0, 0), 
        new Point2D.Float(img.getWidth(), 0), 
        new float[]{startAt, endAt}, 
        new Color[]{new Color(0, 0, 0, 0), Color.RED}); 

      g2d.setPaint(lgp); 

      g2d.setComposite(AlphaComposite.DstOut.derive(1f)); 
      g2d.fill(new Rectangle(0, 0, img.getWidth(), img.getHeight())); 
      g2d.dispose(); 

      return buffer; 

     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      if (img != null) { 
       Graphics2D g2d = (Graphics2D) g.create(); 
       int y = (getHeight() - img.getHeight())/2; 
       int x = (getWidth() - img.getWidth())/2; 
       g2d.drawImage(generateImage(), x, y, this); 

       g2d.dispose(); 
      } 
     } 

    } 

} 
+0

좋은 정보 주셔서 감사합니다. 실제로 저는 그림 자체가 움직이고 있다는 것을 의미하지 않았습니다. 나는 그림이 안정적이고 정적이라는 것을 의미하지만 이미지가 왼쪽에서 오른쪽으로 수평 슬라이딩 효과로 보이기 시작하고 다시 시작됩니다. 나는 그것이 충분히 분명하기를 바란다. –

+0

왼쪽에서 오른쪽으로 이미지가 희미 해지다는 것을 의미합니까? – MadProgrammer

+0

예! 사진을 가져 주셔서 감사합니다. 그러나 당신의 그림에서 날카로운 슬라이딩 에지를 생각할 때 이미지의 오른쪽 끝이 부드럽고 선명하지 않습니다. –

관련 문제