JButton用Image替换Image大小不同?

时间:2016-03-17 18:03:43

标签: java swing memory awt jbutton

首先,我编写了一个简单的记忆游戏。它工作得很好,但只有一件事被打破。

当我点击一个按钮然后他将背景改为卡背后的数字。之后,我点击另一个按钮然后如果两张卡不相等,他们切换回默认值。现在图像移动到左侧,但我不知道为什么。我在初始化时使用相同的方法来计算和缩小图像。

Startmodul: enter image description here

方法:

public void setImageWithResizeImage(ImageIcon icon, int width, int height) {
    this.icon = icon;
    Image img = icon.getImage();
    Image newImg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
    this.setIcon(new ImageIcon(newImg));
}

如果我单击两个按钮并且它将为false,则调用此方法

public void changeBGImage(boolean revealed) {
    if (revealed == true) {
        this.revealed = revealed;
        setIcon(null);
        setText(Integer.toString(id));

    } else {
        this.revealed = revealed;
        System.out.println(this.getWidth() + " " + this.getHeight());
        setImageWithResizeImage(this.icon, this.getWidth(), this.getHeight());
    }
}

之后游戏显示如下:

enter image description here

任何想法?

编辑*

GUI类:

enter code herepackage de.thesimplecode.marvin;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.util.Arrays;
import java.util.Collections;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class GUI extends JFrame {

    private static final long serialVersionUID = 1L;

    public static int pGameMode = 3;
    public static int fieldsCount;
    private int pPlayerPoints = 0;
    private int pKIPoints = 0;
    private final int WIDTH = 800;
    private final int HEIGHT = 800;
    private final String rWinLabel = "Memorys";
    private final String rPlayerScore = "PlayerScore: ";
    private final String rKIScore = "KIScore: ";
    private MemoButton[] rFields;
    private JLabel playerScore, KIScore;
    private JPanel rGameFields;
    private final ImageIcon icon = new ImageIcon("cardBack.jpg");

    public GUI() {
        myFrame();
    }

    public void changeKIScore(int change) {
        this.pKIPoints += change;
        this.KIScore.setText(rKIScore + pKIPoints);
    }

    public void changePlayerScore(int change) {
        this.pPlayerPoints += change;
        this.playerScore.setText(rPlayerScore + pPlayerPoints);
    }

    public JPanel createFields() {
        rGameFields = new JPanel();
        switch (pGameMode) {

        case 1:
            fieldsCount = 16;
            break;
        case 2:
            fieldsCount = 36;
            break;
        case 3:
            fieldsCount = 64;
            break;
        default:
            fieldsCount = 16;
            break;
        }

        try {
            rFields = new MemoButton[fieldsCount];
            fieldsCount = findBestGrid(fieldsCount);

            rGameFields.setLayout(new GridLayout(fieldsCount, fieldsCount));
            for (int i = 0; i < fieldsCount * fieldsCount; i++) {
                if (i > ((fieldsCount * fieldsCount) / 2) - 1) {
                    rFields[i] = new MemoButton(((fieldsCount * fieldsCount) - 1) - i);
                } else {
                    rFields[i] = new MemoButton(i);
                }
            }
            // Shuffle array
            Collections.shuffle(Arrays.asList(rFields));

            for (MemoButton button : rFields) {
                rGameFields.add(button);
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return rGameFields;
    }

    public MemoButton[] getFields() {
        return this.rFields;
    }

    public int getKiScore() {
        return pKIPoints;
    }

    public int getPlayerScore() {
        return pPlayerPoints;
    }

    public boolean refreshJFrame() {
        try {
            remove(rGameFields);
            refreshModuls();
            add(createFields(), BorderLayout.CENTER);
            refreshModuls();
            setBGtoFields(rFields);
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    private JPanel createInfoTable() {
        JPanel rInfoTable = new JPanel();
        rInfoTable.setBackground(Color.GREEN);
        rInfoTable.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        playerScore = new JLabel(rPlayerScore + " 0");
        c.insets = new Insets(0, this.getWidth() / 4, 0, this.getWidth() / 4);
        rInfoTable.add(playerScore, c);

        KIScore = new JLabel(rKIScore + " 0");

        rInfoTable.add(KIScore, c);
        return rInfoTable;
    }

    private int findBestGrid(int count) {
        for (int i = 2; i < 10; i++) {
            if (i * i == count) {
                return i;
            }
        }
        return 0;
    }

    private JMenuBar JMenu() {
        JMenuBar rMainMenu = new JMenuBar();
        JMenu game = new JMenu("Game");
        JMenu settings = new JMenu("Settings");
        JMenuItem newGame = new JMenuItem("New Game");
        JMenu tableSize = new JMenu("TableSize");
        JMenu kiDifficulty = new JMenu("Ki Level");
        // First MenuItems for gameoptions
        JMenuItem small = new JMenuItem("4x4 - 16 cards");
        JMenuItem medium = new JMenuItem("6x6 - 36 cards");
        JMenuItem big = new JMenuItem("8x8 - 64 cards");
        // Second
        JMenuItem low = new JMenuItem("Low");
        JMenuItem mediumsmart = new JMenuItem("Medium smart");
        JMenuItem smart = new JMenuItem("Smart");

        tableSize.add(small);
        tableSize.add(medium);
        tableSize.add(big);

        kiDifficulty.add(low);
        kiDifficulty.add(mediumsmart);
        kiDifficulty.add(smart);

        game.add(newGame);
        game.add(tableSize);
        game.add(kiDifficulty);

        rMainMenu.add(game);
        rMainMenu.add(settings);
        return rMainMenu;
    }

    private void myFrame() {
        setSize(WIDTH, HEIGHT);
        setTitle(rWinLabel);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setJMenuBar(JMenu());
        add(createInfoTable(), BorderLayout.PAGE_START);
        add(createFields(), BorderLayout.CENTER);

        setVisible(true);
        setBGtoFields(rFields);
    }

    private void refreshModuls() {
        validate();
        repaint();
    }

    private void setBGtoFields(MemoButton[] buttons) {
        for (MemoButton button : buttons) {
            button.setImageWithResizeImage(this.icon, button.getWidth(), button.getHeight());
        }
    }
}

自己的按钮类:

package de.thesimplecode.marvin;

import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JButton;

public class MemoButton extends JButton {

    private static final long serialVersionUID = 1L;
    private int id;
    private boolean revealed = false;
    private ImageIcon icon;

    public MemoButton(int id) {
        this.id = id;
    }

    public void changeBGImage(boolean revealed) {
        if (revealed == true) {
            this.revealed = revealed;
            setIcon(null);
            setText(Integer.toString(id));

        } else {
            this.revealed = revealed;
            System.out.println(this.getWidth() + " " + this.getHeight());
            setImageWithResizeImage(this.icon, this.getWidth(), this.getHeight());
        }
    }

    public void getBackIcon(ImageIcon icon) {
        this.icon = icon;
    }

    public int getID() {
        return this.id;
    }

    public boolean getRevealed() {
        return this.revealed;
    }

    public void revealed(boolean revealed) {
        this.revealed = revealed;
    }

    public void setID(int id) {
        this.id = id;
    }

    public void setImageWithResizeImage(ImageIcon icon, int width, int height) {
        this.icon = icon;
        Image img = icon.getImage();
        Image newImg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        this.setIcon(new ImageIcon(newImg));
    }

    public void setRevealed(boolean revealed) {
        this.revealed = revealed;
    }
}

控制器类:

    package de.thesimplecode.marvin;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class Controller implements ActionListener {

    private MemoButton[] fields;
    private GUI gui;
    private KI ki;
    private int counter;
    private MemoButton savebut, savebut2;
    private boolean notMatch = false;
    private boolean abwechseln = true;
    private boolean player = true;
    Timer t = new Timer();

    public Controller(MemoButton[] fields, GUI gui) {
        this.fields = fields;
        this.gui = gui;
        addListenerToButton(this.fields);
        addListenerToMenu(this.gui);
        gameLoop();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() instanceof JButton) {
            MemoButton button = (MemoButton) e.getSource();
            if (notMatch) {
                savebut2.changeBGImage(false);
                savebut.changeBGImage(false);
                savebut2 = null;
                notMatch = false;
            }

            if (button.getRevealed() != true) {
                counter++;
                button.setRevealed(true);
                button.changeBGImage(true);

                if (counter % 2 == 0) {
                    if (button.getRevealed() && savebut.getRevealed()) {
                        if (button.getID() == savebut.getID()) {
                            if (player) {
                                gui.changePlayerScore(gui.getPlayerScore() + 1);
                            } else {
                                gui.changeKIScore(gui.getKiScore() + 1);
                            }
                        } else {
                            notMatch = true;
                            if (player) {
                                player = false;
                            } else {
                                player = true;
                            }
                        }
                    }
                }

                if (abwechseln) {
                    savebut = button;
                    abwechseln = false;
                } else {
                    savebut2 = button;
                    abwechseln = true;
                }

            } else {
                System.out.println("Button würde schoin gewählt");
            }
        } else if (e.getSource() instanceof JMenuItem) {
            JMenuItem rMenuItem = (JMenuItem) e.getSource();
            switch (rMenuItem.getText()) {
            case "New Game":
                newGame();
                break;
            case "4x4 - 16 cards":
                GUI.pGameMode = 1;
                refreshContent();
                break;
            case "6x6 - 36 cards":
                GUI.pGameMode = 2;
                refreshContent();
                break;
            case "8x8 - 64 cards":
                GUI.pGameMode = 3;
                refreshContent();
                break;
            case "Low":
                break;
            case "Medium smart":
                break;
            case "Smart":
                break;
            }
        }
    }

    public void gameLoop() {
        t.schedule(new TimerTask() {

            @Override
            public void run() {
                if (!player) {
                    ki.nextKI();
                }
            }
        }, 0, 1000);

    }

    public void getKI(KI ki) {
        this.ki = ki;
    }

    private void addListenerToButton(MemoButton[] fields) {
        for (MemoButton button : fields) {
            button.addActionListener(this);
        }
    }

    private void addListenerToMenu(GUI gui) {
        JMenuBar menu = gui.getJMenuBar();

        for (int i = 0; i < menu.getMenuCount(); i++) {
            for (int j = 0; j < menu.getMenu(i).getItemCount(); j++) {
                if (menu.getMenu(i).getItem(j) instanceof JMenu) {
                    JMenu rJMenu = (JMenu) menu.getMenu(i).getItem(j);
                    for (int y = 0; y < rJMenu.getItemCount(); y++) {
                        JMenuItem rJMenuItem = rJMenu.getItem(y);
                        rJMenuItem.addActionListener(this);
                    }
                } else if (menu.getMenu(i).getItem(j) instanceof JMenuItem) {
                    menu.getMenu(i).getItem(j).addActionListener(this);
                }
            }
        }
    }

    private void newGame() {
        refreshContent();
        gui.changeKIScore(0);
        gui.changePlayerScore(0);
    }

    private void refreshContent() {
        if (gui.refreshJFrame()) {
            addListenerToButton(gui.getFields());
            ki.resetButton();
            ki.getFields(gui.getFields());
        }
    }
}

KI代码:

package de.thesimplecode.marvin;

import java.awt.event.ActionEvent; import java.util.Random;

公共类KI {

private MemoButton[] button;
private Controller controll;
private Random r = new Random();

public KI(MemoButton[] button, Controller controll) {
    this.button = button;
    this.controll = controll;
}

public void getFields(MemoButton[] button) {
    this.button = button;
}

public void nextKI() {
    takeCard();
}

public void resetButton() {
    this.button = null;
}

private void takeCard() {
    controll.actionPerformed(new ActionEvent(button[r.nextInt((GUI.fieldsCount * GUI.fieldsCount) - 1)],
            ActionEvent.ACTION_PERFORMED, null));
}

}

主要:

package de.thesimplecode.marvin;

public class Memory {

public static void main(String[] args) {
    GUI gui = new GUI();
    Controller cl = new Controller(gui.getFields(), gui);
    KI ki = new KI(gui.getFields(), cl);
    cl.getKI(ki);
}

}

1 个答案:

答案 0 :(得分:0)

解决:

imageButton.setOnClickListener(new.View.OnClickListener(){
@Override
Public void onClick(View :)
{
    Intent intent = New intent(activity,     ExampleActivityName.class);
    activity.startActivity(intent);

}

});

我必须添加方法setText(“”);因为有了setText

public void changeBGImage(ImageIcon icon, boolean revealed) {
    if (revealed == true) {
        this.revealed = revealed;
        setIcon(null);
        setText(Integer.toString(id));

    } else {
        this.revealed = revealed;
        System.out.println(this.getWidth() + " " + this.getHeight());
        setText("");
        setImageWithResizeImage(icon, this.getWidth(), this.getHeight());
    }
}

我在按钮中添加一个数字或字符串,并使用setText(“”);我删除它,现在它的工作原理。他的右侧有一个小点,因此左侧是合并的图像。