寫了一個可以用的 GUI ,不過有些小地方還需要修改
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
class GuessNumber implements ActionListener {
JFrame frame;
JTextField input;
JButton newgame, guess;
JLabel result;
ArrayList<JComponent> GUIComponent;
String answer;
public static void main(String[] args) {
new GuessNumber();
}
public GuessNumber() {
frame = new JFrame("Guess Number");
frame.setSize(200, 100);
frame.setLayout(new GridBagLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
input = new JTextField();
newgame = new JButton("New Game");
newgame.setActionCommand("new");
newgame.addActionListener(this);
guess = new JButton("Guess");
guess.setActionCommand("guess");
guess.addActionListener(this);
result = new JLabel("0A0B");
int att[][] = {{0, 0, 2, 1, 0, 0, 1, 10},
{0, 1, 1, 1, 0, 0, 1, 10},
{1, 1, 1, 1, 0, 0, 1, 10},
{0, 2, 2, 1, 0, 0, 1, 10}};
GUIComponent = new ArrayList<JComponent>(4);
GUIComponent.add(input);
GUIComponent.add(newgame);
GUIComponent.add(guess);
GUIComponent.add(result);
int i;
for (i = 0; i < 4; i++) {
GridBagConstraints c = new GridBagConstraints();
int a[] = att[i];
c.gridx = a[0];
c.gridy = a[1];
c.gridwidth = a[2];
c.gridheight = a[3];
c.weightx = a[4];
c.weighty = a[5];
c.fill = a[6];
c.anchor = a[7];
frame.add(GUIComponent.get(i), c);
}
answer = new String("");
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
int i, j;
if (cmd == "guess") {
int a = 0;
int b = 0;
char[] number = input.getText().toCharArray();
if (answer.isEmpty()) {
result.setText("No answer!!");
}
else {
char[] s = answer.toCharArray();
for (i = 0; i < 4; i++) {
if (number[i] == s[i]) {
a++;
}
for (j = 0; j < 4; j++) {
if (number[j] == s[i]) {
b++;
}
}
}
b -= a;
System.out.println(input.getText() + " - " + a + "A" + b + "B");
result.setText(a + "A" + b + "B!!");
}
}
if (cmd == "new") {
char[] n = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
answer = "";
for (i = 0; i < 4; i++) {
do {
j = (int) (Math.random() * 9);
if (n[j] == 'x') {
continue;
}
else {
answer += n[j];
n[j] = 'x';
break;
}
} while (true);
}
//System.out.println(answer);
}
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.169.146.232