Skip to content

Instantly share code, notes, and snippets.

@Omar-Handouk
Created April 20, 2018 15:45
Show Gist options
  • Save Omar-Handouk/0f125db58d7a8a42b8bff9143d662db3 to your computer and use it in GitHub Desktop.
Save Omar-Handouk/0f125db58d7a8a42b8bff9143d662db3 to your computer and use it in GitHub Desktop.
Simple Accumulator
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.event.*;
import java.util.TimerTask;
public class Sandbox extends JFrame implements ActionListener {
private JLabel label;
private JTextField txtField;
private JButton increment;
private JButton clear;
private int count = 0;
private Sandbox() throws HeadlessException {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setTitle("Counter");
this.setSize(300, 95);
this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2 - this.getSize().height / 2);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
Container contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.setBackground(new Color(88, 88, 89));
JPanel panel_1 = new JPanel(new GridLayout(1, 2));
label = new JLabel("Counter");
label.setHorizontalAlignment(JLabel.CENTER);
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
label.setText("BOI, don't click me!");
(new java.util.Timer()).schedule(new TimerTask() {
@Override
public void run() {
label.setText("Counter");
}
}, 3 * 1000);
}
});
txtField = new JTextField();
txtField.setEditable(false);
txtField.setBorder(new BevelBorder(BevelBorder.LOWERED));
txtField.setHorizontalAlignment(JTextField.CENTER);
txtField.setText(Integer.toString(count));
txtField.setPreferredSize(new Dimension(20, 30));
panel_1.add(label);
panel_1.add(txtField);
JPanel panel_2 = new JPanel(new GridLayout(1, 2));
increment = new JButton("Increment");
increment.addActionListener(this);
increment.setMnemonic(KeyEvent.VK_I);
clear = new JButton("Clear");
clear.addActionListener(this);
clear.setMnemonic(KeyEvent.VK_C);
panel_2.add(increment);
panel_2.add(clear);
contentPane.add(panel_1, BorderLayout.NORTH);
contentPane.add(panel_2, BorderLayout.SOUTH);
this.update();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == increment)
count += 1;
else
count = 0;
txtField.setText(Integer.toString(count));
this.update();
}
private void update() {
this.repaint();
this.revalidate();
}
public static void main(String[] args) {
Sandbox a = new Sandbox();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment