2014-11-27 3 views
0

그래서이 ABC 학습 게임을 만들고 있습니다. 한 번 이상 A 버튼을 클릭하면 3 개의 이미지가 위치를 변경합니다. 원하는 것은 무엇입니까? do 이니까 ! [이미지 설명은 여기에 입력하십시오] [1]JFrame에서 이미지의 위치 변경

내가 A 버튼을 클릭하면, 세 개의 이미지가 화면에 표시됩니다. 첫 번째는 사과와 같은 모양입니다. 두 번째 이미지는 무작위로 나타납니다. 그러나 때로는 하나의 사과가 다시 사과가 되더라도 해결할 수 있습니다.

내 질문은 "A"버튼을 두 번 이상 클릭하면 Apple의 두 번째 및 두 번째 이미지 위치를 첫 번째 및 세 번째 이미지로 두 번째 위치로 어떻게 변경할 수 있습니까? 그러면 사과가 클릭 "A"버튼을 기반으로 위치를 변경하고 다른 두 그림은 위치를 변경하고 배열에서 무작위로 선택됩니다.

그래서

, 여기에 모든

import java.awt.*; 
import java.awt.event.ActionListener; 
import javax.swing.*; 
import java.awt.event.*; 
import java.text.AttributedCharacterIterator; 
import java.util.Random; 
import javax.swing.ImageIcon; 

/** 
* 
* @author Dip 
*/ 
public class AbcGeniusPanel extends JPanel implements ActionListener { 

    //Declare the necessary Variables here 
    private JButton[] buttons; //create an array for buttons 
    private BorderLayout layout; //Declare object of BorderLayout 
    private Image image = null; 
    private boolean showImage = false; 
    //Initialize all the variables here 
    static int index = 0; 
    int randNumber = 0, id = 0; 
    int q = 0, w = 0; 
    int buttonClick = 0; 
    //Store all the imahges that will appear on the screen into an String type array 
    private static String[] imageList = {"src/Images/1.png", "src/Images/2.png", "src/Images/3.png", "src/Images/4.png", "src/Images/5.png", "src/Images/6.png", "src/Images/7.png", "src/Images/8.png", "src/Images/9.png", "src/Images  /10.png", 
     "src/Images/11.png", "src/Images/12.png", "src/Images/13.png", "src/Images   /14.png", "src/Images/15.png", 
     "src/Images/16.png", "src/Images/17.png", "src/Images/18.png", "src/Images   /19.png", "src/Images/20.png", 
     "src/Images/21.png", "src/Images/22.png", "src/Images/23.png", "src/Images   /24.png", "src/Images/25.png", 
     "src/Images/26.png" 
    }; 

    //Define the constructor here 
    public AbcGeniusPanel() { 
     ImageIcon[] alphabets = new ImageIcon[26]; 
     setBackground(Color.yellow); 
     //Load the images for alphabet images into the alphabets array using a for loop 
     for (int i = 0; i < alphabets.length; i++) { 
      alphabets[i] = new ImageIcon("C:\\Users\\Dip\\Desktop\\Java Projects\\AbcGeniusApp\\src\\Alphabets\\" + (i + 1) + ".png"); 
     } 
     //Create a JPnael object 
     JPanel panel = new JPanel(); 
     //Set a layoutManager on the panel 
     //panel.setLayout(new FlowLayout(FlowLayout.CENTER)); //This is not workling good 
     panel.setLayout(new GridLayout(2, 13, 5, 5)); //This is good for now 
     //Create an array for holdoing the buttons 
     buttons = new JButton[26]; 
     //This Loop will Store the buttons in the buttons array attatching each image for each button 
     //Try passing Images inside the JButton parameter later. 
     for (int i = 0; i < 26; i++) { 
      buttons[i] = new JButton(alphabets[i]); 
     } 
     // Now Setting up a new Borderlayout so that we can set the whole gridLayout at the botton of the panel 
     setLayout(new BorderLayout(2, 0)); 
     //add the panel to the Border layout 
     add(panel, BorderLayout.SOUTH); 
     //Add evenHandling mechanism to all the buttons 
     for (int k = 0; k < 26; k++) { 
      buttons[k].addActionListener(this); 
     } 
     for (int count1 = 0; count1 < 26; count1++) { 
      panel.add(buttons[count1]); 
     } 
    } 

    //This Method will generate a random Number and return it 
    public int random_number() { 
     int rand_num; 
     Random generator = new Random(System.currentTimeMillis()); 
     rand_num = generator.nextInt(26); 
     return rand_num; 
    } 

    //This method will draw the font on the Panel 
    public void paintComponent(Graphics g) { 
     Font font; //Declare Font object here 
     font = new Font("Wide Latin", Font.BOLD, 22); //Set font 
     super.paintComponent(g); //Ensure the drawing in super class 
     g.setFont(font); //Set the font 
     g.setColor(Color.RED); 
     String text = "CLICK ON THE RIGHT IMAGE!"; //Display the text 
     g.drawString(text, 255, 20); 
    } 

    //To draw the picture on the screen we need to override the paint Method 
    @Override 
    public void paint(Graphics g) { 
     super.paint(g); 
     //Here, x and y will determine the x and y position os each image 
     int x = 0, y = 0; 
     // the varibale q is declared above 
     for (q = 0; q < 3; q++) //This loop will generate three images on the screen 
     { 
      if (showImage) { 
       x = x + 265; //X-Position of the image 
       y = 90; //Y-Position of the image 
       //q is declared as q=0, so this will always be true 
       if (w == 1 || q == 0) { 
        g.drawImage(image, x, y, image.getWidth(null), image.getHeight(null), null); //This method will put the image on the screen 
        showImage = true; 
        w = 0; 
       } 
       while (true) //this loop will run anyway 
       { 
        //go inside this loop only when the generated random 
        //doesn't match with the index of the button that was pressed 
        while ((randNumber = random_number()) != index) { 
         index = randNumber; //Now put the randomVlaue in the index 
         this.image = new ImageIcon(imageList[randNumber]).getImage(); 
         showImage = true; 
         //make w=1 so that we can break from the outer loop 
         w = 1; 
         //break from the inner loop 
         break; 
        } 
        //Since we have made the w=1, so we are breaking out of the outer loop 
        if (w == 1) { 
         break; 
        } 
       } 
      } 
     } 
    } 

    @Override 
    public void actionPerformed(ActionEvent event) { 
     Object source = event.getSource(); 
     id = 0; 
     while (true) { 
      //id is set to zero, for example if the button A (buttons[0])is not pressed then it will go below 
      //to increase id until it matches the index of the button that we pressed 
      if (source == buttons[id]) { 
       //get the image of that same index of the buttons and then set the showImage true 
       //SO the the paint function above can draw the image 
       this.image = new ImageIcon(imageList[id]).getImage(); 
       showImage = true; 
       //save the index of the button that is presed in another variable 
       //then break from the while loop 
       index = id; 
       break; 
      } else { 
       id++; 
       //This is necessary to make sure that id will cross 26 
       //becasue we have only 26 letters or the array index is 26 
       //so highest value can be 26 only 
       id = id % 26; 
      } 
     } 
     repaint(); 
    } 
} 
+1

1- 코드에서'src' 디렉토리를 직접 참조하지 마십시오. 일단 프로그램이 빌드되면 존재하지 않습니다. 2- JButton # setIcon을 사용하여 요구 사항에 따라 이미지의 위치를 ​​변경하십시오 ... – MadProgrammer

답변

2
  1. 는 (이미지를 표시 할 것 무엇이든) 3 JLabels 또는 JButton의 추가 의견에 설명되어 코드의 place.Most 걸리는 JPanel의, 내 코드입니다 JPanel 컨테이너에 저장합니다. JPanel은 GridLayout(1, 3, horizontal_gap, 0) 레이아웃을 사용합니다.
  2. 모든 이미지를 ImageIcon으로 ArrayList에 저장합니다.
  3. 필요할 때 ArrayList를 섞습니다.
  4. setIcon(...) 메서드를 사용하여 for 루프의 JLabels/JButtons에 아이콘을 배치합니다.

    • 당신의 JPanel의이 paintComponent하지 paint를 오버라이드 (override) 할 필요가 있음을

참고. paint 메서드는 구성 요소의 자식과 테두리를 칠하는 작업을 담당하며 기본적으로 이중 버퍼링을 사용하지 않으므로보다 위험한 방법으로 재정의합니다.

  • 스레딩에 관계없이 Swing GUI에 while (true) 루프를 넣는 것은 매우 위험합니다.
  • 그림을 paint과 같이 넣는 것은 GUI 자살입니다. 그림을 그리는 방법이 프로그램의 응답 성을 결정 짓는 중요한 요소이기 때문에 절대로하지 마십시오. 속도를 늦추면 프로그램이 느리고 반응이 좋지 않으므로 기울여야하며 은 빠르며은 빠르며 그 안에 그림을 그려야합니다.
  • paint 메서드에는 프로그램 논리가 포함되어 있지만 수행하지 않아야합니다. 여부 또는 페인트 방법이 호출 될지 여부를 완전히 제어 할 수 없으므로 프로그램 논리를이 중 하나에 배치해서는 안됩니다.
  • MadProgrammer는 이미지를 src 경로로 사용하지 마십시오. 프로그램을 jar 파일로 빌드하면 존재하지 않으므로주의해야합니다. jar 파일에 리소스 디렉토리를 만들고 파일이 아닌 리소스로 이미지를 참조하는 것이 좋습니다.
  • +1

    'src' 참조 문제를 해결하고 싶습니다 ...또는 당신이 나처럼 존재하지 않는다고 생각하는가) +1 – MadProgrammer

    +0

    @MadProgrammer : 코드를 사용하여 작업하고 아직 도착하지는 않았지만 거기에 도달 할 것입니다. –