Jogo da velha em interface grafica
public class javaapplication6 extends JFrame implements ActionListener {
JButton[] x; JRadioButton j1; JRadioButton j2; Object obj; ActionEvent evt;
public javaapplication6() { JFrame s = new JFrame("Jogo da Velha"); setSize(600, 600); JPanel p = new JPanel(); JPanel p1 = new JPanel(new GridLayout(3, 3));
ButtonGroup b = new ButtonGroup(); j1 = new JRadioButton("Jogador 1"); j2 = new JRadioButton("Jogador 2"); b.add(j1); b.add(j2); p.add(j1); p.add(j2); j1.setSelected(true); x = new JButton[9]; for (int i = 0; i < 9; i++) { x[i] = new JButton(""); x[i].setPreferredSize(new Dimension(150, 150)); x[i].addActionListener(this); p1.add(x[i]); } p1.setSize(300, 300); p.add(p1); add(p); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
public static void main(String[] args) { javaapplication6 j = new javaapplication6(); }
@Override public void actionPerformed(ActionEvent e) { evt = e; obj = e.getSource(); for (int i = 0; i < 9; i++) { if (obj == x[i]) { if (j1.isSelected() == true) { if (x[i].getText() == "") { x[i].setText("X"); j2.setSelected(true); } } else { if (x[i].getText() == "") { x[i].setText("O"); j1.setSelected(true); } } }