我打算建造一个机器人地板。我的要求是只需应用障碍即改变按钮的颜色,即可在运行时设置地板。到目前为止,只需按下按钮即可更改按钮的颜色,但如果我再次按下该特定按钮,我想将其改回原来的颜色。按下偶数次点击后,我无法将按钮的颜色更改回以前的颜色。如果点击次数是偶数,那么按钮不应该是彩色的,而是它的奇怪,它应该改变它的颜色。以下是我的代码
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JFrame;
class butMaddFrame extends JFrame implements ActionListener
{
int x=20;
int y=20;
JButton[][] buttons = new JButton[x][y];
JPanel mPanel = new JPanel();
JPanel bPanel = new JPanel();
JPanel cPanel = new JPanel();
JTextArea scoreKeeper = new JTextArea();
Container c = getContentPane();
int[][] intArray = new int[x][y];
public butMaddFrame()
{
butGen();
score2();
//cPanel.add(scoreKeeper);
bPanel.setLayout(new GridLayout(x,y));
mPanel.setLayout(new BorderLayout());
mPanel.add(bPanel, BorderLayout.CENTER);
// mPanel.add(cPanel, BorderLayout.LINE_END);
c.add(mPanel);
setTitle("ButtonMaddness");
setSize(500,400);
setLocation(200,200);
setVisible(true);
}
private void butGen()
{
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
{
buttons[i][j] = new JButton(String.valueOf(i)+"x"+String.valueOf(j));
buttons[i][j].setActionCommand("button" +i +"_" +j);
buttons[i][j].addActionListener(this);
buttons[i][j].setSize(100, 100);
bPanel.add(buttons[i][j]);
}
}
private void score()
{
}
private void score2()
{
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
// buttons[i][j].setText(String.valueOf(intArray[i][j]));
buttons[i][j].setText("");
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().contains("button"))
{
String str = e.getActionCommand().replaceAll("button", "");
System.out.println(str);
String[] v = str.split("_");
int i = Integer.parseInt(v[0]);
int j = Integer.parseInt(v[1]);
intArray[i][j]++;
buttons[i][j].setBackground(Color.BLUE);
//buttons[i][j].setBackground(null);
System.out.println(e.getActionCommand() +" " +i +" " +j);
// System.out.println();
score2();
}
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class buttonMaddness {
public static void main(String[] args)
{
butMaddFrame myFrame = new butMaddFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
答案 0 :(得分:2)
如果已将按钮颜色单击两次,则将其设置为默认颜色:
int check [][]= new int [100][100];
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().contains("button"))
{
String str = e.getActionCommand().replaceAll("button", "");
System.out.println(str);
String[] v = str.split("_");
int i = Integer.parseInt(v[0]);
int j = Integer.parseInt(v[1]);
intArray[i][j]++;
if(check[i][j]!=1){
buttons[i][j].setBackground(Color.BLUE);
check[i][j]=1;
}
else{
buttons[i][j].setBackground(null);
check[i][j]=0;
}
//buttons[i][j].setBackground(null);
System.out.println(e.getActionCommand() +" " +i +" " +j);
// System.out.println();
score2();
}
}