英文:
If condition for 9 Jbuttons simultaneously?
问题
[if condition working for only one button at a time]
我已经编写了代码来使得9个JButton在鼠标点击时随机显示其中一种8种颜色之一。我添加了一个JLabel来显示结果,如果所有的JButton都是相同的颜色,我希望结果显示"Winner!"。
以下是完整的代码!
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import static java.awt.Color.*;
public class buttonTest {
public static void main(String[] args) {
new buttonTest();
}
public buttonTest() { //构造函数。
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Colour Button 4.0");
frame.add(new colourButton());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class colourButton extends JPanel implements ActionListener {
Random rand = new Random();
JButton buttons[]; // 创建一个按钮数组。
JLabel gameRules = new JLabel("Match the colour buttons.");
JLabel timer = new JLabel("00:00 (placeholder)");
JLabel result = new JLabel("Result: (placeholder)");
byte value = 0;
public colourButton() {
add(gameRules);
buttons = new JButton[9];
setLayout(new GridLayout(3, 3));
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("colour button");
buttons[i].setBorderPainted(false);
buttons[i].setContentAreaFilled(false);
buttons[i].setOpaque(true);
buttons[i].addActionListener(this);
add(buttons[i]);
add(timer);
add(result);
setVisible(true);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (!(e.getSource() instanceof JButton)) {
return;
}
String clickedbutton = e.getActionCommand();
System.out.println(clickedbutton + " button clicked.");
JButton button = (JButton) e.getSource();
value++;
value %= 9;
switch (rand.nextInt(9)) {
case 0:
button.setBackground(null);
case 1:
button.setBackground(red);
break;
case 2:
button.setBackground(orange);
break;
case 3:
button.setBackground(yellow);
break;
case 4:
button.setBackground(green);
break;
case 5:
button.setBackground(cyan);
break;
case 6:
button.setBackground(blue);
break;
case 7:
button.setBackground(MAGENTA);
break;
case 8:
button.setBackground(pink);
break;
}
if (button.getBackground() == magenta) {
result.setText("magenta");
} else {
result.setText("placeholder result");
}
}
}
}
我认为逻辑上应该是这样的:
如果按钮数量为9,并且它们都是"这种"颜色,那么就返回这个字符串。
<details>
<summary>英文:</summary>
[if condition working for only one button at a time][1]I have programmed 9 Jbuttons to return one of 8 colors randomly on mouse-click. I have added a Jlabel that returns the result - and I want the result to return a "Winner!" string if all Jbuttons are the same color.
HERE'S THE FULL CODE!
import javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import static java.awt.Color.*;
public class buttonTest {
public static void main(String[] args) {
new buttonTest();
}
public buttonTest() { //CONSTRUCTOR.
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Colour Button 4.0");
frame.add(new colourButton());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class colourButton extends JPanel implements ActionListener {
Random rand = new Random();
JButton buttons[]; // created a button array.
JLabel gameRules = new JLabel("Match the colour buttons.");
JLabel timer = new JLabel("00:00 (placeholder)");
JLabel result = new JLabel("Result: (placeholder)");
byte value = 0;
public colourButton() {
add(gameRules);
buttons = new JButton[9];
setLayout(new GridLayout(3, 3));
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("colour button");
buttons[i].setBorderPainted(false);
buttons[i].setContentAreaFilled(false);
buttons[i].setOpaque(true);
buttons[i].addActionListener(this);
add(buttons[i]);
add(timer);
add(result);
setVisible(true);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (!(e.getSource() instanceof JButton)) {
return;
}
String clickedbutton = e.getActionCommand();
System.out.println(clickedbutton + " button clicked.");
JButton button = (JButton) e.getSource();
value++;
value %= 9;
switch (rand.nextInt(9)) {
case 0:
button.setBackground(null);
case 1:
button.setBackground(red);
break;
case 2:
button.setBackground(orange);
break;
case 3:
button.setBackground(yellow);
break;
case 4:
button.setBackground(green);
break;
case 5:
button.setBackground(cyan);
break;
case 6:
button.setBackground(blue);
break;
case 7:
button.setBackground(MAGENTA);
break;
case 8:
button.setBackground(pink);
break;
}
if (button.getBackground() == magenta) {
result.setText("magenta");
} else {
result.setText("placeholder result");
}
}
}
}
I'd imagine it logically be something like:
if button count is 9 and if they're all 'this' colour, then return this string.
[1]: https://i.stack.imgur.com/HzwVS.png
</details>
# 答案1
**得分**: 0
以下是翻译好的内容:
当您创建一个Swing应用程序时,您还应该创建一个应用程序的逻辑模型。这是[model / view / controller][1]模式的一个示例。
通过将Swing应用程序的逻辑部分分开,您可以一次专注于应用程序的一个部分。
这是我测试过的GUI。正如您所见,结果文本显示为“Winner!”。
[![Colour Button GUI][2]][2]
我创建了一个`GameModel`类来保存游戏模型,以及一个`ButtonModel`类来保存`JButton`的值和颜色。
测试所有九个ButtonModels的方法是`GameModel`类的`isMatch`方法。您可以看到使用模型大大简化了`ColourButton`类的`actionListener`方法。
以下是代码:
```java
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JButtonTesting {
public static void main(String[] args) {
new JButtonTesting();
}
private GameModel model;
public JButtonTesting() { // 构造函数。
this.model = new GameModel();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Colour Button 4.0");
frame.add(new ColourButton());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ColourButton extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
Random rand = new Random();
JButton buttons[]; // 创建一个按钮数组。
JLabel gameRules = new JLabel("匹配颜色按钮。");
JLabel timer = new JLabel("00:00 (占位符)");
JLabel result = new JLabel("结果:(占位符)");
int value = 0;
public ColourButton() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
gameRules.setAlignmentX(JLabel.CENTER_ALIGNMENT);
add(gameRules);
JPanel buttonPanel = createButtonPanel();
add(buttonPanel);
timer.setAlignmentX(JLabel.CENTER_ALIGNMENT);
add(timer);
result.setAlignmentX(JLabel.CENTER_ALIGNMENT);
add(result);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttons = new JButton[9];
buttonPanel.setLayout(new GridLayout(0, 3));
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("颜色按钮");
buttons[i].setActionCommand(Integer.toString(i));
buttons[i].setBorderPainted(false);
buttons[i].setContentAreaFilled(false);
buttons[i].setOpaque(true);
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
return buttonPanel;
}
public void setButtonColour(int index, Color colour) {
buttons[index].setBackground(colour);
}
@Override
public void actionPerformed(ActionEvent event) {
if (!(event.getSource() instanceof JButton)) {
return;
}
int buttonIndex = Integer.valueOf(event.getActionCommand());
System.out.println(buttonIndex + "按钮已点击。");
value++;
value %= 9;
model.setColour(buttonIndex, value);
setButtonColour(buttonIndex, model.getColour(buttonIndex));
if (model.isMatch()) {
result.setText("赢家!");
}
}
}
public class GameModel {
private Color[] colours = { null, Color.RED, Color.ORANGE, Color.YELLOW,
Color.GREEN, Color.CYAN, Color.BLUE,
Color.MAGENTA, Color.PINK };
private ButtonModel[] buttonValues;
public GameModel() {
buttonValues = new ButtonModel[9];
for (int i = 0; i < buttonValues.length; i++) {
buttonValues[i] = new ButtonModel();
setColour(i, 0);
}
}
public Color getColour(int index) {
return buttonValues[index].getColour();
}
public void setColour(int index, int value) {
buttonValues[index].setValue(value);
buttonValues[index].setColour(colours[value]);
}
public boolean isMatch() {
int value = buttonValues[0].getValue();
for (int i = 1; i < buttonValues.length; i++) {
if (buttonValues[i].getValue() != value) {
return false;
}
}
return true;
}
}
public class ButtonModel {
private int value;
private Color colour;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Color getColour() {
return colour;
}
public void setColour(Color colour) {
this.colour = colour;
}
}
}
英文:
When you create a Swing application, you should also create a logical model of the application. This is an example of the model / view / controller pattern.
By separating the logical portions of your Swing application, you can focus on one part of the application at a time.
Here's the GUI I tested with. As you can see, the result text says "Winner!".
I created a GameModel
class to hold the game model and a ButtonModel
class to hold the value and colour for a JButton
.
The method to test all nine ButtonModels is the isMatch
method of the GameModel
class. You can see how using a model greatly simplified the actionListener
method of the ColourButton
class.
Here's the code.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JButtonTesting {
public static void main(String[] args) {
new JButtonTesting();
}
private GameModel model;
public JButtonTesting() { // CONSTRUCTOR.
this.model = new GameModel();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Colour Button 4.0");
frame.add(new ColourButton());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ColourButton extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
Random rand = new Random();
JButton buttons[]; // created a button array.
JLabel gameRules = new JLabel("Match the colour buttons.");
JLabel timer = new JLabel("00:00 (placeholder)");
JLabel result = new JLabel("Result: (placeholder)");
int value = 0;
public ColourButton() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
gameRules.setAlignmentX(JLabel.CENTER_ALIGNMENT);
add(gameRules);
JPanel buttonPanel = createButtonPanel();
add(buttonPanel);
timer.setAlignmentX(JLabel.CENTER_ALIGNMENT);
add(timer);
result.setAlignmentX(JLabel.CENTER_ALIGNMENT);
add(result);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttons = new JButton[9];
buttonPanel.setLayout(new GridLayout(0, 3));
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("colour button");
buttons[i].setActionCommand(Integer.toString(i));
buttons[i].setBorderPainted(false);
buttons[i].setContentAreaFilled(false);
buttons[i].setOpaque(true);
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
return buttonPanel;
}
public void setButtonColour(int index, Color colour) {
buttons[index].setBackground(colour);
}
@Override
public void actionPerformed(ActionEvent event) {
if (!(event.getSource() instanceof JButton)) {
return;
}
int buttonIndex = Integer.valueOf(event.getActionCommand());
System.out.println(buttonIndex + " button clicked.");
value++;
value %= 9;
model.setColour(buttonIndex, value);
setButtonColour(buttonIndex, model.getColour(buttonIndex));
if (model.isMatch()) {
result.setText("Winner!");
}
}
}
public class GameModel {
private Color[] colours = { null, Color.RED, Color.ORANGE, Color.YELLOW,
Color.GREEN, Color.CYAN, Color.BLUE,
Color.MAGENTA, Color.PINK };
private ButtonModel[] buttonValues;
public GameModel() {
buttonValues = new ButtonModel[9];
for (int i = 0; i < buttonValues.length; i++) {
buttonValues[i] = new ButtonModel();
setColour(i, 0);
}
}
public Color getColour(int index) {
return buttonValues[index].getColour();
}
public void setColour(int index, int value) {
buttonValues[index].setValue(value);
buttonValues[index].setColour(colours[value]);
}
public boolean isMatch() {
int value = buttonValues[0].getValue();
for (int i = 1; i < buttonValues.length; i++) {
if (buttonValues[i].getValue() != value) {
return false;
}
}
return true;
}
}
public class ButtonModel {
private int value;
private Color colour;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Color getColour() {
return colour;
}
public void setColour(Color colour) {
this.colour = colour;
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论