Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /***********/
- SCANNER
- Scanner sc = new Scanner(System.in);//new File("myNumbers") for parsing files
- int i = sc.nextInt();
- /***********/
- /***********/
- FILE READ
- //do try with finally where close the streams
- BufferedReader in = new BufferedReader(new FileReader("employee.txt"));//in.readLine()
- StringTokenizer t = new StringTokenizer(s,"token");//t.nextToken()
- /***********/
- /***********/
- FILE CLASS
- File file = new File("test");
- .exists(), .isFile(), .isDirectory(), .getName(), .getPath(), .length()
- /***********/
- /***********/
- Multitasking : more than one process at a time; CPU time distributed among processes
- Preemptive Multitasking: OS interrupts processes without waiting them to release CPU
- Co-Operative Multitasking: processes willing to yield control
- Threads get a portion of the CPU
- Threads not run in order thay are created
- Thread 4 states: new, runnable, blocked, dead *blocked thread reenters runnable using the same route that blocked it*
- thread dies when void run() finished normally or dies randomly caused by execption
- Sunchronization in java : Exclusion sync *mutual exclusion*, Condition sync
- public myRunnable implements Runnable{
- myRunnable() {
- (new Thread(this)).start();
- }
- @Override
- public void run() {
- //do stuff
- }
- }
- while (!Thread.currentThread().isInterrupted() && workToDo()) {
- //do work
- //if interrupted method is called on a blocked thread *waiting for stuff* the thread will be terminated by an InterrptedException
- }
- synchronized (expression) {
- //doWork
- //sync guarantees expression will not be modified by any other thread. called client-side sync
- }
- /***********/
- NETWORKING
- Request : sync *client waits for response* async*client proceeds computatuin before having response*
- Server: *waits, listens* on IP+PORT; called host machine *PORT 2 byte number 0-1023 well known ports, 1024-49151 your ports, 49152-65535 not registered*
- Socket s = new Socket(host, port);
- public class myServer {
- private static final int PORT;
- myServer(int port) {
- this.PORT = port;
- }
- public void startServer throws IOException {
- ServerSocket s = new ServerSocket(PORT);
- try {
- while (true) {
- Socket socket = s.accept();
- try {
- new myServerThreader(socket);
- } catch (IOException e) {
- socket.close();
- }
- }
- }
- finally {
- s.close();
- }
- }
- }
- public class myServerThreader implements Runnable {
- private Socket socket;
- private BufferedReader in;
- private PrintWriter out;
- myServerThreader(Socket socket) {
- this.socket = socket;
- this.in = new BufferedReader (new InputStreamReader (this.socket.getInputStream()));
- this.in = new PrintWriter (new OutputStreamWriter (this.socket.getOutputStream()), true);
- (new Thread(this)).start();
- }
- }
- URL url = new URL(string);
- InputStream inStream = url.openStream();
- BufferedReader in = new BufferedReader(mew InputStreamReader(inStream));
- URL connection class to get more info about web resource
- URLConnection conn = url.openConnection();
- conn.connect();//to connect
- /***********/
- /***********/
- GUI
- event source and handler binding is done at runtime, registration is done by passing refference, done when program starts
- JLabel, JTextField, JButton, JCheckBox, JComboBox, JList, JPanel
- {}
- JPanel :
- FlowLayout default; puts them in line and where is no space makes new row; auto reflow
- panel.setLayout(new FlowLayout(FlowLayout.LEFT)); //default CENTER
- BorderLayout default for JFrame, can place components CENTER NORTH SOUTH EAST WEST
- panel.setLayout(new BorderLayout());
- panel.add(yellowButton, BorderLayout.SOUTH);
- GridLayout puts them like a spreadsheet *row, cols* cells have same size
- panel.setLayout(new GridLayout(5,4)); //5 rows 4 cols
- JTextField :
- new JTextField("Default text", 20);
- void setText(string);
- String getText();
- void setEditable(boolean b);
- JLabel :
- new JLabel("Default text", JLabel.RIGHT);
- JPasswordField :
- new JPasswordField("Default Text", int columns);
- char[] getPassword();
- void setEchoChar(char echo);
- JFormattedTextField :
- DateFormat.getDateInstance
- .getTimeInstance
- .getDateTimeInstance
- new JFormattedTextField(NumberFormat.getIntegerInstance());
- int x = ((Number) txtField.getValue()).intValue();
- JTextArea :
- new JTextArea(8,40)
- void setLineWrap(boolean b)
- JScrollPane jScroll = new JScrollPane(textArea);
- JCheckBox :
- new JCheckBox("Text");
- void setSelected(boolean b);
- boolean isSelected();
- ActionListener listener = new ActionListener(actionPerformed)
- JCheckBox.addActionListener (listener);
- public void actionPerformed )ActionEvent e) {
- //doShit based on event
- }
- JRadioButton :
- ButtonGroup gr;
- new JRadioButton("Small", false);
- gr.add(RadioButton);
- JComboBox<String> :
- .setEditable(true);
- .addItem("da");
- .getSelected();
- .removeItem("");
- //make menu bar
- JMenuBar menuBar = new JMenuBar();
- frame.setMenuBar(menuBar);
- //add menu to menubar
- JMenu editMenu = new JMenu(“Edit“);
- menuBar.add(editMenu);
- //add item to menu
- JMenuItem pasteItem = new JMenuItem("Paste");
- editMenu.add(pasteItem);
- editMenu.addSeparator();
- pasteItem.addActionListener(listener);
- //add action to menu
- JMenuItem menuItemClose = new JMenuItem("Close");
- menuItemClose.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- System.exit(0);
- }
- });
- menu.add(menuItemClose);
- //add menu item with picture
- JMenuItem cutItem = new JMenuItem("Cut", new ImageIcon("cut.gif"));
- JCheckBoxMenuItem readonlyItem = new JCheckBoxMenuItem("Read-only");
- optionsMenu.add(readonlyItem);
- //popup menu
- JPopupMenu popup = new JPopupMenu();
- JMenuItem item = new JMenuItem("Cut");
- item.addActionListener(listener);
- popup.add(item);
- component.setComponentPopupMenu(popup);
- //toolbar
- JToolBar bar = new JToolBar();
- bar.add(blueButton);
- add(bar, BorderLayout.NORTH);
- /***********/
- /***********/
- Dialog
- int selection = JOptionPane.showConfirmDialog(parent, "Message", "Title",
- JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
- if (selection == JOptionPane.OK_OPTION) {
- //doShit
- }
- public AboutDialog extends JDialog {
- public AboutDialog(JFrame owner) {
- super (owner, "Title", true);
- add(new JLabel("Text"), BorderLayout.CENTER);
- JButton ok = new JButton("OK");
- ok.addActionListener( new
- ActionListener() {
- public void actionperformed(ActionEvent event) {
- //doShit
- setVisible(false);
- }
- });
- add(ok, BorderLayout.SOUTH);
- setSize(100,100);
- }
- }
- /***********/
- /***********/
- OpenDialog
- JFileChooser chooser = new JFileChooser();
- chooser.setFileFilter(new FileFilter() {
- @Override
- public String getDescription() {return "File desc";}
- @Override
- public boolean accept(File f) {
- if (f.isDirectory()) {
- return true;
- } else {
- return f.getName().toLowerCase().endsWith(".png");
- }
- }
- });
- chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
- chooser.setCurrentDirectory(new File("location"));
- int res = chooser.showOpenDialog(JFileChooserEx.this);
- if (res == JFileChooser.APPROVE_OPTION) {
- File file = chooser.getSelectedFile();
- } else {
- JOptionPane.showMessageDialog(this, "Dialog cancelled by the user");
- }
- /***********/
- /***********/
- SaveDialog
- JFileChooser fileChooser = new JFileChooser();
- fileChooser.setDialogTitle("Specify a file to save");
- int userSelection = fileChooser.showSaveDialog(parentFrame);
- if (userSelection == JFileChooser.APPROVE_OPTION) {
- File fileToSave = fileChooser.getSelectedFile();
- System.out.println("Save as file: " + fileToSave.getAbsolutePath());
- }
- /***********/
- /***********/
- public class Example extends JFrame {
- public Example() {
- initUI();
- }
- public final void initUI() {
- JMenuBar menubar = new JMenuBar();
- ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
- JMenu file = new JMenu("File");
- file.setMnemonic(KeyEvent.VK_F);
- JMenuItem eMenuItem = new JMenuItem("Exit", icon);
- eMenuItem.setMnemonic(KeyEvent.VK_E);
- eMenuItem.setToolTipText("Exit application");
- eMenuItem.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent event) {
- System.exit(0);
- }
- });
- file.add(eMenuItem);
- menubar.add(file);
- addSeparator();
- setJMenuBar(menubar);
- setTitle("Simple menu");
- setSize(300, 200);
- setLocationRelativeTo(null);
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- }
- public static void main(String[] args) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- Example ex = new Example();
- ex.setVisible(true);
- }
- });
- }
- }
- /***********/
- /***********/
- IMPORTS
- import java.io.*;
- import java.net.*;
- import java.util.*;
- import java.awt.*;
- import javax.swing.*;
- /***********/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement