【发布时间】:2014-01-10 03:19:09
【问题描述】:
我正计划建造一个机器人地板。我的要求是地板将在运行时设置,只需应用障碍即可,即更改按钮的颜色。到目前为止,只需按下按钮即可更改按钮的颜色,但如果再次按下该特定按钮,我想将其更改回以前的颜色。按偶数次点击时,我无法将按钮的颜色更改回之前的颜色。如果点击次数是偶数,则按钮不应该被着色,但它的奇数应该改变它的颜色。以下是我的代码
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);
}
}
【问题讨论】:
-
检查当前颜色并设置另一种?这样做的具体问题是什么?不仅仅是“我无法改变”,它看起来更像是“我什至没有试图找到改变的方法”......
-
这不是 Android 代码。这是针对 Java Swing 应用程序的。为什么是 Android 标签?