我打算建造一個機器人地板。我的要求是,只需施加障礙即改變按鈕的顏色,即可在運行時設置樓層。到目前爲止,只需按下按鈕即可更改按鈕的顏色,但如果再次按下該特定按鈕,我想將其更改回其以前的顏色。按下偶數次點擊後,我無法將按鈕的顏色改回原來的顏色。如果點擊的數量是偶數,按鈕不應該着色,但是它的奇數應該改變它的顏色。以下是我的代碼無法改變多次點擊按鈕的顏色
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);
}
}
檢查當前顏色和另一個設置?具體的問題是什麼?不僅僅是「我無法改變」,它更像是「我甚至沒有試圖找到改變方式」...... – SJuan76
這不是Android代碼。這是針對Java Swing應用程序的。爲什麼Android標籤? – Simon