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