按下键时删除平铺

时间:2015-12-01 20:25:28

标签: java

我正在创建一个游戏Keybricks,我需要在按下按键时移除一个磁贴。目前,我使用以下类:

Game.java

package code;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JButton;

public class Game implements Runnable{


@Override
public void run() {
    // TODO Auto-generated method stub


    JFrame frame = new JFrame ("Game");
     frame.setVisible(true);
     frame.setSize(500,200);
     frame.setLocationRelativeTo(null);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);




      JPanel panel = new JPanel();
      frame.add(panel);
      JButton button = new JButton("Start The Game");
      panel.add(button);
      button.addActionListener(new Tile(frame));
}
}

Tile.java

package code;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Tile implements ActionListener {

private JFrame _j;
public Tile(JFrame frame){
    _j = frame;
}
public void actionPerformed (ActionEvent e) {     

    JFrame frame2 = new JFrame("Keybricks");


    frame2.setVisible(true);
    frame2.setSize(600,600);

    JPanel panel = new JPanel();
    frame2.add(panel);

    _j.setVisible(true); //This creates a new game frame

    GridLayout experimentLayout = new GridLayout(4,4);

            panel.setLayout(experimentLayout);

            ArrayList<Color> colors = new ArrayList<>();

            colors.add(Color.RED);
            colors.add(Color.BLUE);
            colors.add(Color.GREEN);
            colors.add(Color.YELLOW);

            String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

            ArrayList<Character> letters = new ArrayList<>(); 

            for (char c : alphabet.toCharArray()) {
                  letters.add(c);
                }

            Random rnd = new Random();

            ArrayList<JButton> buttons = new ArrayList<>();

            for (int i = 0; i < 16; i++){
                JButton jb = new JButton();
                buttons.add(jb);
                jb.addActionListener(new eventhandler(panel,jb));
                panel.add(jb);
            }


            for (JButton button : buttons){
                Color randomColor = colors.get(rnd.nextInt(colors.size())); // Get a new random color
                button.setBackground(randomColor);
                button.setOpaque(true);
            }

            for(int j=0; j < 4; j++){

                JButton randbutton = buttons.get(rnd.nextInt(buttons.size()));
                char randletter = letters.get(rnd.nextInt(letters.size()));
                randbutton.setText("" + randletter);


            }


}
}

eventhandler.java

package code;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JPanel;

public class eventhandler implements ActionListener {

static JPanel fe;
private JButton b1;



public eventhandler(JPanel panel, JButton b) {

    b1=b;
    fe=panel;
}


public void actionPerformed(ActionEvent e) {


fe.remove(b1);

}

}

Link to sample output image

我的问题是当用户输入该字符时,如何使用keylistener删除包含该字符的jbutton以及其附近相似颜色的所有其他按钮?

1 个答案:

答案 0 :(得分:0)

不要使用KeyListener。 KeyListener仅在组件具有焦点时才有效。

而是使用Key Bindings。有关详细信息,请阅读How to Use Key Bindings上Swing教程中的部分。所有Swing组件都使用了Key Bindings。

这是一个显示按下的字母的简单示例:

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

public class CalculatorPanel extends JPanel
{
    private JTextField display;

    public CalculatorPanel()
    {
        Action numberAction = new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
//              display.setCaretPosition( display.getDocument().getLength() );
                display.replaceSelection(e.getActionCommand());
            }
        };

        setLayout( new BorderLayout() );

        display = new JTextField();
        display.setEditable( false );
        display.setHorizontalAlignment(JTextField.RIGHT);
        add(display, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout( new GridLayout(0, 5) );
        add(buttonPanel, BorderLayout.CENTER);

        for (int i = 0; i < 10; i++)
        {
            String text = String.valueOf(i);
            JButton button = new JButton( text );
            button.addActionListener( numberAction );
            button.setBorder( new LineBorder(Color.BLACK) );
            button.setPreferredSize( new Dimension(30, 30) );
            buttonPanel.add( button );

            InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(KeyStroke.getKeyStroke(text), text);
            inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
            button.getActionMap().put(text, numberAction);
        }
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("Calculator Panel");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new CalculatorPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

如果要删除该按钮,则可以修改actionPerformed(...)方法以删除该按钮。代码类似于:

JButton button = (JButton)e.getSource();
Container parent = button.getParent();
parent.remove(button);
parent.revalidate();