Advertisement
ungureanuvladvictor

Java CheatSheet

Dec 10th, 2013
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.05 KB | None | 0 0
  1. /***********/
  2. SCANNER
  3. Scanner sc = new Scanner(System.in);//new File("myNumbers") for parsing files
  4. int i = sc.nextInt();
  5. /***********/
  6.  
  7. /***********/
  8. FILE READ
  9. //do try with finally where close the streams
  10. BufferedReader in = new BufferedReader(new FileReader("employee.txt"));//in.readLine()
  11. StringTokenizer t = new StringTokenizer(s,"token");//t.nextToken()
  12. /***********/
  13.  
  14. /***********/
  15. FILE CLASS
  16. File file = new File("test");
  17. .exists(), .isFile(), .isDirectory(), .getName(), .getPath(), .length()
  18. /***********/
  19.  
  20. /***********/
  21. Multitasking : more than one process at a time; CPU time distributed among processes
  22. Preemptive Multitasking: OS interrupts processes without waiting them to release CPU
  23. Co-Operative Multitasking: processes willing to yield control
  24. Threads get a portion of the CPU
  25. Threads not run in order thay are created
  26. Thread 4 states: new, runnable, blocked, dead *blocked thread reenters runnable using the same route that blocked it*
  27.                 thread dies when void run() finished normally or dies randomly caused by execption
  28. Sunchronization in java : Exclusion sync *mutual exclusion*, Condition sync
  29.  
  30. public myRunnable implements Runnable{
  31.    
  32.     myRunnable() {
  33.         (new Thread(this)).start();
  34.     }
  35.  
  36.     @Override
  37.     public void run() {
  38.         //do stuff
  39.     }
  40. }
  41.  
  42. while (!Thread.currentThread().isInterrupted() && workToDo()) {
  43.     //do work
  44.     //if interrupted method is called on a blocked thread *waiting for stuff* the thread will be terminated by an InterrptedException
  45. }
  46.  
  47. synchronized (expression) {
  48.     //doWork
  49.     //sync guarantees expression will not be modified by any other thread. called client-side sync
  50. }
  51.  
  52. /***********/
  53. NETWORKING
  54. Request : sync *client waits for response* async*client proceeds computatuin before having response*
  55. 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*
  56. Socket s = new Socket(host, port);
  57. public class myServer {
  58.     private static final int PORT;
  59.  
  60.     myServer(int port) {
  61.         this.PORT = port;
  62.     }
  63.  
  64.     public void startServer throws IOException {
  65.         ServerSocket s = new ServerSocket(PORT);
  66.         try {
  67.             while (true) {
  68.                 Socket socket = s.accept();
  69.                 try {
  70.                     new myServerThreader(socket);
  71.                 } catch (IOException e) {
  72.                     socket.close();
  73.                 }
  74.             }
  75.         }
  76.         finally {
  77.             s.close();
  78.         }
  79.     }
  80. }
  81.  
  82. public class myServerThreader implements Runnable {
  83.     private Socket socket;
  84.     private BufferedReader in;
  85.     private PrintWriter out;
  86.  
  87.     myServerThreader(Socket socket) {
  88.         this.socket = socket;
  89.         this.in = new BufferedReader (new InputStreamReader (this.socket.getInputStream()));
  90.         this.in = new PrintWriter (new OutputStreamWriter (this.socket.getOutputStream()), true);
  91.         (new Thread(this)).start();
  92.     }
  93. }
  94.  
  95. URL url = new URL(string);
  96. InputStream inStream = url.openStream();
  97. BufferedReader in = new BufferedReader(mew InputStreamReader(inStream));
  98.  
  99. URL connection class to get more info about web resource
  100. URLConnection conn = url.openConnection();
  101. conn.connect();//to connect
  102. /***********/
  103.  
  104. /***********/
  105. GUI
  106. event source and handler binding is done at runtime, registration is done by passing refference, done when program starts
  107. JLabel, JTextField, JButton, JCheckBox, JComboBox, JList, JPanel
  108. {}
  109. JPanel :
  110.     FlowLayout default; puts them in line and where is no space makes new row; auto reflow
  111.         panel.setLayout(new FlowLayout(FlowLayout.LEFT)); //default CENTER
  112.     BorderLayout default for JFrame, can place components CENTER NORTH SOUTH EAST WEST
  113.         panel.setLayout(new BorderLayout());
  114.         panel.add(yellowButton, BorderLayout.SOUTH);
  115.     GridLayout puts them like a spreadsheet *row, cols* cells have same size
  116.         panel.setLayout(new GridLayout(5,4)); //5 rows 4 cols
  117.  
  118. JTextField :
  119.         new JTextField("Default text", 20);
  120.         void setText(string);
  121.         String getText();
  122.         void setEditable(boolean b);
  123.  
  124. JLabel :
  125.     new JLabel("Default text", JLabel.RIGHT);
  126.  
  127. JPasswordField :
  128.     new JPasswordField("Default Text", int columns);
  129.     char[] getPassword();
  130.     void setEchoChar(char echo);
  131.  
  132. JFormattedTextField :
  133.     DateFormat.getDateInstance
  134.               .getTimeInstance
  135.               .getDateTimeInstance
  136.     new JFormattedTextField(NumberFormat.getIntegerInstance());
  137.     int x = ((Number) txtField.getValue()).intValue();
  138.  
  139. JTextArea :
  140.     new JTextArea(8,40)
  141.     void setLineWrap(boolean b)
  142.     JScrollPane jScroll = new JScrollPane(textArea);
  143.  
  144. JCheckBox :
  145.     new JCheckBox("Text");
  146.     void setSelected(boolean b);
  147.     boolean isSelected();
  148.     ActionListener listener = new ActionListener(actionPerformed)
  149.     JCheckBox.addActionListener (listener);
  150.     public void actionPerformed )ActionEvent e) {
  151.         //doShit based on event
  152.     }
  153.  
  154. JRadioButton :
  155.     ButtonGroup gr;
  156.     new JRadioButton("Small", false);
  157.     gr.add(RadioButton);
  158.  
  159. JComboBox<String> :
  160.     .setEditable(true);
  161.     .addItem("da");
  162.     .getSelected();
  163.     .removeItem("");
  164.  
  165. //make menu bar
  166. JMenuBar menuBar = new JMenuBar();
  167. frame.setMenuBar(menuBar);
  168.  
  169. //add menu to menubar
  170. JMenu editMenu = new JMenu(“Edit“);
  171. menuBar.add(editMenu);
  172.  
  173. //add item to menu
  174. JMenuItem pasteItem = new JMenuItem("Paste");
  175. editMenu.add(pasteItem);
  176. editMenu.addSeparator();
  177. pasteItem.addActionListener(listener);
  178.  
  179.  
  180.  
  181. //add action to menu
  182. JMenuItem menuItemClose = new JMenuItem("Close");
  183. menuItemClose.addActionListener(new ActionListener() {
  184.     public void actionPerformed(ActionEvent e) {
  185.         System.exit(0);
  186.     }
  187. });
  188. menu.add(menuItemClose);
  189.  
  190.  
  191. //add menu item with picture
  192. JMenuItem cutItem = new JMenuItem("Cut", new ImageIcon("cut.gif"));
  193.  
  194.  
  195. JCheckBoxMenuItem readonlyItem = new JCheckBoxMenuItem("Read-only");
  196. optionsMenu.add(readonlyItem);
  197.  
  198. //popup menu
  199. JPopupMenu popup = new JPopupMenu();
  200.     JMenuItem item = new JMenuItem("Cut");
  201.     item.addActionListener(listener);
  202. popup.add(item);
  203. component.setComponentPopupMenu(popup);
  204.  
  205. //toolbar
  206. JToolBar bar = new JToolBar();
  207.     bar.add(blueButton);
  208. add(bar, BorderLayout.NORTH);
  209. /***********/
  210.  
  211. /***********/
  212. Dialog
  213. int selection = JOptionPane.showConfirmDialog(parent, "Message", "Title",
  214.                 JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
  215. if (selection == JOptionPane.OK_OPTION) {
  216.     //doShit
  217. }
  218.  
  219. public AboutDialog extends JDialog {
  220.     public AboutDialog(JFrame owner) {
  221.         super (owner, "Title", true);
  222.         add(new JLabel("Text"), BorderLayout.CENTER);
  223.         JButton ok = new JButton("OK");
  224.         ok.addActionListener( new
  225.             ActionListener() {
  226.                 public void actionperformed(ActionEvent event) {
  227.                     //doShit
  228.                     setVisible(false);
  229.                 }
  230.             });
  231.         add(ok, BorderLayout.SOUTH);
  232.         setSize(100,100);
  233.     }
  234. }
  235. /***********/
  236.  
  237. /***********/
  238. OpenDialog
  239. JFileChooser chooser = new JFileChooser();
  240. chooser.setFileFilter(new FileFilter() {        
  241.        @Override
  242.        public String getDescription() {return "File desc";}
  243.        @Override
  244.        public boolean accept(File f) {
  245.             if (f.isDirectory()) {
  246.                 return true;
  247.             } else {
  248.                 return f.getName().toLowerCase().endsWith(".png");
  249.             }
  250.         }
  251.     });
  252. chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  253. chooser.setCurrentDirectory(new File("location"));
  254. int res = chooser.showOpenDialog(JFileChooserEx.this);
  255. if (res == JFileChooser.APPROVE_OPTION) {
  256.     File file = chooser.getSelectedFile();      
  257. } else {
  258.     JOptionPane.showMessageDialog(this, "Dialog cancelled by the user");
  259. }
  260. /***********/
  261.  
  262. /***********/
  263. SaveDialog
  264. JFileChooser fileChooser = new JFileChooser();
  265. fileChooser.setDialogTitle("Specify a file to save");  
  266.  
  267. int userSelection = fileChooser.showSaveDialog(parentFrame);
  268.  
  269. if (userSelection == JFileChooser.APPROVE_OPTION) {
  270.     File fileToSave = fileChooser.getSelectedFile();
  271.     System.out.println("Save as file: " + fileToSave.getAbsolutePath());
  272. }
  273. /***********/
  274.  
  275. /***********/
  276. public class Example extends JFrame {
  277.  
  278.     public Example() {
  279.         initUI();
  280.     }
  281.  
  282.     public final void initUI() {
  283.  
  284.         JMenuBar menubar = new JMenuBar();
  285.         ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
  286.  
  287.         JMenu file = new JMenu("File");
  288.         file.setMnemonic(KeyEvent.VK_F);
  289.  
  290.         JMenuItem eMenuItem = new JMenuItem("Exit", icon);
  291.         eMenuItem.setMnemonic(KeyEvent.VK_E);
  292.         eMenuItem.setToolTipText("Exit application");
  293.         eMenuItem.addActionListener(new ActionListener() {
  294.             public void actionPerformed(ActionEvent event) {
  295.                 System.exit(0);
  296.             }
  297.         });
  298.  
  299.         file.add(eMenuItem);
  300.  
  301.         menubar.add(file);
  302.         addSeparator();
  303.         setJMenuBar(menubar);
  304.  
  305.         setTitle("Simple menu");
  306.         setSize(300, 200);
  307.         setLocationRelativeTo(null);
  308.         setDefaultCloseOperation(EXIT_ON_CLOSE);
  309.     }
  310.  
  311.     public static void main(String[] args) {
  312.  
  313.         SwingUtilities.invokeLater(new Runnable() {
  314.             public void run() {
  315.                 Example ex = new Example();
  316.                 ex.setVisible(true);
  317.             }
  318.         });
  319.     }
  320. }
  321. /***********/
  322.  
  323. /***********/
  324. IMPORTS
  325. import java.io.*;
  326. import java.net.*;
  327. import java.util.*;
  328. import java.awt.*;
  329. import javax.swing.*;
  330. /***********/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement