Skip to content

Instantly share code, notes, and snippets.

@umuturan
Last active March 13, 2016 09:02
Show Gist options
  • Select an option

  • Save umuturan/47a252d004eba8d91cc7 to your computer and use it in GitHub Desktop.

Select an option

Save umuturan/47a252d004eba8d91cc7 to your computer and use it in GitHub Desktop.
LAB04-A
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PotLuck extends JFrame {
static JButton[] buttons;
JButton close;
JLabel statuBar;
int clickCount;
static int luckyCount;
JPanel buttonsPanel, topPanel;
public PotLuck() {
clickCount = 0;
luckyCount = (int) (Math.random() * 24);
setLayout(new BorderLayout());
buttons = new JButton[25];
statuBar = new JLabel(clickCount + " tries made!");
buttonsPanel = new JPanel();
topPanel = new JPanel();
close = new JButton("Quit");
buttonsPanel.setLayout(new GridLayout(5, 5));
for (int i = 0; i < 25; i++) {
buttons[i] = new JButton("Click!");
buttonsPanel.add(buttons[i]);
buttons[i].addActionListener(new PotLuckListener());
}
dyeButtons();
close.addActionListener(new MyCloseListener());
topPanel.setLayout(new BorderLayout());
topPanel.add(close, BorderLayout.EAST);
topPanel.add(statuBar, BorderLayout.WEST);
add(buttonsPanel, BorderLayout.CENTER);
add(topPanel, BorderLayout.NORTH);
setBounds(600,300,500,400);
setVisible(true);
}
public static void dyeButtons(){
for(int i=0; i<25;i++){
buttons[i].setBackground(Color.WHITE);
}
buttons[luckyCount].setBackground(Color.YELLOW);
}
public class PotLuckListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttons[luckyCount]) {
clickCount++;
new WinScreen();
statuBar.setText("YOU HAVE FOUND İN " + clickCount + " TRIES!");
clickCount = 0;
luckyCount = (int) (Math.random() * 24);
dyeButtons();
} else {
if(((JButton)e.getSource()).getBackground() != Color.RED){
((JButton)e.getSource()).setBackground(Color.RED);
clickCount++;
statuBar.setText(clickCount + " TRIES HAVE BEEN MADE!");
}else{
statuBar.setText("YOU HAD ALREADY CLİCKED THAT BUTTON, TRY ANOTHER!");
}
}
}
}
public class MyCloseListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
dispose();
((Component) arg0.getSource()).getParent().setVisible(false);
}
}
public class WinScreen extends JFrame {
public WinScreen() {
Label win;
Button closeWin;
setBounds(650, 450, 140, 150);
setLayout(new FlowLayout());
win = new Label(" YOU HAVE FOUND IN " + clickCount + " TRIES!");
closeWin = new Button("Click to Close");
closeWin.setBackground(Color.YELLOW);
closeWin.addActionListener(new MyActListener());
add(win);
add(closeWin);
//pack();
setVisible(true);
}
public class MyActListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
dispose();
((Component) arg0.getSource()).getParent().setVisible(false);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment