更改JFrame上图像的位置

时间:2014-11-27 00:47:47

标签: java swing oop user-interface

所以我正在制作这个ABC学习游戏,我想要做的就是如果我不止一次点击A按钮,三个图像将改变它们的位置,我想要做的就是这个 ![在此输入图像说明] [1]

当我点击A按钮时,三个图像将出现在屏幕上,第一个是苹果,因为我在循环中设置了那个,但是后两个图像将随机出现,尽管有时它们中的一个是苹果,我可以解决这个问题。

我的问题是,如果多次单击“A”按钮,如何将Apple的第二和第二图像的位置更改为第一和第三图像到第二图像。 那么,结果将是苹果将根据点击“A”按钮改变位置,其他两张图片改变它们的位置并从阵列中随机选择。

所以,这是我的JPanel代码,其中发生了一切。大部分代码都在评论中解释

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 个答案:

答案 0 :(得分:2)

  1. 将3个JLabel或JButton(将显示图像的任何内容)添加到JPanel容器中。 JPanel可能会使用GridLayout(1, 3, horizontal_gap, 0)布局。
  2. 将所有图像作为ImageIcons放入ArrayList。
  3. 在需要时随机播放ArrayList
  4. 使用setIcon(...)方法将图标拖放到for循环中的JLabel / JButton中。
  5. 请注意

    • 您的JPanel应该覆盖paintComponent,而不是paintpaint方法负责绘制组件的子项和边框,默认情况下它不使用双缓冲,这是一种更危险的覆盖方法。
    • while (true)循环放入Swing GUI而不考虑线程是非常危险的。
    • 将这个放入paint这样的绘画方法中是GUI自杀。从来没有这样做,因为绘画方法是你的程序感知响应性的主要决定因素。如果你放慢速度,程序会被认为是缓慢且响应不佳,因此它必须尽可能精简和快速,并且你应该有绘画并且只有绘画代码。
    • 您的paint方法中包含程序逻辑,这也是不应该完成的。您无法完全控制是否<甚至如果将调用绘制方法,因此不应将程序逻辑放在其中一个内。
    • 正如MadProgrammer所说,不要将src路径用于您的图像,因为一旦您将程序构建到jar文件中,它就不会存在。最好在jar文件中创建资源目录,并将图像称为资源,而不是文件。