0% found this document useful (0 votes)
3 views15 pages

Java

The document provides an overview of Java programming concepts, including Java IO, Swing components, JDBC, and multithreading. It contains code examples for various input/output streams, GUI components, and database connectivity. Additionally, it outlines layout managers and event handling in Swing applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views15 pages

Java

The document provides an overview of Java programming concepts, including Java IO, Swing components, JDBC, and multithreading. It contains code examples for various input/output streams, GUI components, and database connectivity. Additionally, it outlines layout managers and event handling in Swing applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import [Link].

Scanner;

public class Test {

public static void main(String[] args) {


[Link]("Hello world!");
Scanner scanner = new Scanner([Link]);
int n = [Link]();
[Link](n);
[Link]();
}
}

Contents
Java IO..............................................................................................................................................................2
Buffered..Stream:.........................................................................................................................................2
BufferedReader:...........................................................................................................................................2
FileReader:....................................................................................................................................................2
PrintWriter:..................................................................................................................................................3
FileInputStream:...........................................................................................................................................3
FileOutputStream:........................................................................................................................................3
DataInputStream:.........................................................................................................................................3
DataOutputStream:......................................................................................................................................3
Swing................................................................................................................................................................3
JTabbedPane:...............................................................................................................................................4
JOptionPane:.........................................................................................................................................4
JDialog:........................................................................................................................................................4
JList:.......................................................................................................................................................4
JTable:.....................................................................................................................................................5
BorderLayout:...............................................................................................................................................5
BoxLayout:....................................................................................................................................................5
CardLayout:..................................................................................................................................................6
FlowLayout:..................................................................................................................................................6
GridBagLayout:.............................................................................................................................................6
GridLayout:...................................................................................................................................................7
EventDemo (Beeper):...................................................................................................................................7
ComboBox demo:.........................................................................................................................................8
JDBC................................................................................................................................................................10
Multithread....................................................................................................................................................10
DeprecatedMethod:...........................................................................................................................11
Concurrency...................................................................................................................................................12
Executors:............................................................................................................................................12
Callable:..............................................................................................................................................12
Synchronization:..............................................................................................................................12
1
Networking.....................................................................................................................................................13
TCP:..........................................................................................................................................................13
UDP:..........................................................................................................................................................14
URLDirect:............................................................................................................................................14

Java IO
Các lớp chia làm 2 loại:

- Xử lí byte: InputStream, OutputStream (abstract class)


- Xử lí text: Reader, Writer

Buffered..Stream:
try {
BufferedInputStream bin = new BufferedInputStream(new FileInputStream("[Link]"));
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("[Link]"));
while (true) {
int datum = [Link]();

if (datum == -1)
break;
[Link](datum);
}
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}

BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader([Link], "utf8"));
[Link]("Enter a number:");
String str = [Link]();
int iNum = [Link](str);
[Link](iNum);
[Link]();

BufferedReader br2 = new BufferedReader(new FileReader("[Link]"));


while (true) {
str = [Link]();
if (str == null)
break;
[Link](str);
}
[Link]();

FileReader:
FileReader fr = new FileReader("[Link]");
while (true) {
int i = [Link]();
if (i == -1)
break;
char ch = (char) i;
[Link](ch);
}
[Link]();

2
FileReader fr2 = new FileReader("[Link]");
FileWriter fw2 = new FileWriter("[Link]");

while (true) {
int i = [Link]();
if (i == -1)
break;
[Link](i);
}
[Link]();
[Link]();

PrintWriter:
File fOut = new File("[Link]");
PrintWriter out = new PrintWriter(fOut);
[Link]("...123");
[Link]("456789");
[Link]("%d %c\n", 49, 49);
[Link]();

FileInputStream:
FileInputStream fin = new FileInputStream("[Link]");
int a = [Link]();
[Link]();

FileOutputStream:
FileOutputStream fout = new FileOutputStream("[Link]");
[Link](97);
[Link]();
[Link]();

DataInputStream:
DataInputStream in = new DataInputStream(new FileInputStream(new
File(fileName)));
[Link]();
[Link]();
[Link]();

DataOutputStream:
DataOutputStream dos = new DataOutputStream(new FileOutputStream("[Link]"));
[Link]("Hào");
[Link](25678);
[Link](-67.76);
[Link](true);
[Link]();

Swing
import [Link].*;

public class Test {

public static void main(String[] args) {


JFrame frame = new JFrame();

JPanel mainPanel = new JPanel();


JLabel label = new JLabel("Hello world!");
[Link](label);

3
[Link]("Hello world");
[Link](mainPanel);
[Link](JFrame.EXIT_ON_CLOSE);
[Link]();
[Link](true);
}
}

JTabbedPane:
JTabbedPane mainJTabbedPane = new JTabbedPane();
[Link]("Tài khoản", tkPanel);
[Link]("Môn học", new MonHocPanel());
[Link]("Học kì", new HocKiPanel());
[Link]("Lớp học", new LopHocPanel());
[Link]("Kỳ đăng ký học phần", new KyDKHPPanel());
[Link]("Học phần", new HocPhanPanel());

JOptionPane:
[Link](chooseUserDialog, "Tên group không được trống",
"Lỗi tạo group", JOptionPane.WARNING_MESSAGE);
-------------------------------------------
String[] options = { "Thêm", "Ghi đè" };
int choice = [Link](this,
"Bạn muốn thêm các học sinh vào danh sách có sẵn hoặc ghi đè thành danh
sách mới?", "Thêm hay ghi đè", JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

if (choice == 0)
[Link]([Link](fileName));
else
[Link] = [Link](fileName);
-------------------------------------------
int confirmDelete = [Link](this, "Bạn có chắc muố
n xoá
những học sinh sau: a, b, c");
if (confirmDelete == JOptionPane.YES_OPTION) {

JDialog:
Giống Jframe nhưng có thêm 2 cái này:
[Link](JDialog.DEFAULT_MODALITY_TYPE); //tránh bấ
m mấy cái đằng sau
[Link](null);

JList:
//code này không có ý nghĩa, chỉ ghi mấ
y cái cú pháp ra

JList<String> onlineUserJList = new JList<String>();


[Link](new String[] { "a", "b", "c" });
[Link](new MouseAdapter() {
public void mouseClicked(MouseEvent e) {

}
}

JScrollPane onlineUserScrollPane = new JScrollPane(onlineUserJList);


[Link]([Link]("Danh sách user
đang online"));

[Link]();
[Link]();

4
JTable:
//code này không có ý nghĩa, chỉ ghi mấ
y cái cú pháp ra

public void updateTable(Object[][] objectMatrix) {


[Link](new DefaultTableModel(objectMatrix, columnNames) {

private static final long serialVersionUID = 1L;

@Override
public boolean isCellEditable(int row, int column) {
return false;
}
});
}

JTable theTable = new JTable();


[Link](30);

JScrollPane theScrollPane = new JScrollPane();


[Link](theTable);

[Link]().addListSelectionListener(new
ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {

}
});

[Link]();
[Link](0, 0);
[Link]();
[Link](selectedRow, i).toString();

BorderLayout:
JPanel pane = new JPanel(new BorderLayout());
JButton button = new JButton("Button 1 (PAGE_START)");
[Link](button, BorderLayout.PAGE_START);

button = new JButton("Button 2 (CENTER)");


[Link](new Dimension(200, 100));
[Link](button, [Link]);

button = new JButton("Button 3 (LINE_START)");


[Link](button, BorderLayout.LINE_START);

button = new JButton("Long-Named Button 4 (PAGE_END)");


[Link](button, BorderLayout.PAGE_END);

button = new JButton("5 (LINE_END)");


[Link](button, BorderLayout.LINE_END);

BoxLayout:
private static void addAButton(String text, Container container) {
JButton button = new JButton(text);
[Link](Component.CENTER_ALIGNMENT);
[Link](button);
}

JPanel pane = new JPanel();


[Link](new BoxLayout(pane, BoxLayout.Y_AXIS));

5
addAButton("Button 1", pane);
addAButton("Button 2", pane);
addAButton("Button 3", pane);
addAButton("Long-Named Button 4", pane);
addAButton("5", pane);

CardLayout:
String comboBoxItems[] = { "JPanel with JButtons", "JPanel with JTextField" };
JComboBox<String> cb = new JComboBox<String>(comboBoxItems);
[Link](false);

JPanel card1 = new JPanel();


[Link](new JButton("Button 1"));
[Link](new JButton("Button 2"));

JPanel card2 = new JPanel();


[Link](new JTextField("TextField", 20));

JPanel cardPanel;
cardPanel = new JPanel(new CardLayout());
[Link](card1, "JPanel with JButtons");
[Link](card2, "JPanel with JTextField");

[Link](new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
CardLayout cl = (CardLayout) ([Link]());
[Link](cardPanel, (String) [Link]());
}
});

[Link](cb, [Link]);
[Link](cardPanel, [Link]);

FlowLayout:
[Link](ComponentOrientation.RIGHT_TO_LEFT);

[Link](new FlowLayout());

[Link](new JButton("Button 1"));


[Link](new JButton("Button 2"));
[Link](new JButton("Button 3"));
[Link](new JButton("Long-Named Button 4"));
[Link](new JButton("5"));

GridBagLayout:
JButton button;
[Link](new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
[Link] = [Link];

button = new JButton("Button 1");


[Link] = 0.5;
[Link] = 0;
[Link] = 0;
[Link] = 0.4;
[Link](button, c);

button = new JButton("Button 2");


[Link] = 1;
[Link] = 0;
[Link](button, c);

6
button = new JButton("Button 3");
[Link] = 2;
[Link] = 0;
[Link](button, c);

button = new JButton("Long-Named Button 4");


// ipad padding trong, insets padding ngoài
[Link] = 40;
[Link] = 0.0;
[Link] = 0.3;
[Link] = 3;
[Link] = 0;
[Link] = 1;
[Link](button, c);

button = new JButton("5");


[Link] = 0;
[Link] = 0.3;
[Link] = [Link];
[Link] = new Insets(10, 0, 0, 0); // top left bottom right
[Link] = 1;
[Link] = 2;
[Link] = 2;
[Link](button, c);

GridLayout:
[Link](new GridLayout(0, 2));

[Link](new JButton("Button 1"));


[Link](new JButton("Button 2"));
[Link](new JButton("Button 3"));
[Link](new JButton("Long-Named Button 4"));
[Link](new JButton("5"));

EventDemo (Beeper):
import [Link].*;
import [Link].*;
import [Link].*;

class AnotherClass implements ActionListener {


public void actionPerformed(ActionEvent ae) {
[Link]("From Another Class!");
}
}

class MyClass implements ActionListener {


MyClass() {
}

public void actionPerformed(ActionEvent e) {


String strActionCommand = [Link]();
if ([Link]("OK")) {

[Link]().beep();
7
[Link]("BEEP");
} else
[Link]("Hello!");
}
}

public class Beeper extends JPanel {


// implements ActionListener{
JButton button;

public Beeper() {
super(new BorderLayout());

button = new JButton("OK");


[Link](new Dimension(200, 80));
add(button, [Link]);
[Link]("OK");

MyClass mc = new MyClass();


[Link](mc);
[Link](new AnotherClass());

JButton button2 = new JButton("Hello");


add(button2, BorderLayout.LINE_END);
[Link]("HELLO");

[Link](mc);

/*
* public void actionPerformed(ActionEvent e) {
* [Link]().beep(); [Link]("BEEP"); }
*/
private static void createAndShowGUI() {
[Link](true);

JFrame frame = new JFrame("Beeper");


[Link](JFrame.EXIT_ON_CLOSE);

JComponent newContentPane = new Beeper();


[Link](true);
[Link](newContentPane);

[Link]();
[Link](true);
}

public static void main(String[] args) {


[Link](new Runnable() {
public void run() {
createAndShowGUI();
}
});

}
}

ComboBox demo:
import [Link].*;
import [Link].*;
import [Link].*;

public class ComboBoxDemo extends JPanel implements ActionListener {


JLabel picture;

public ComboBoxDemo() {
super(new BorderLayout());

String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };

8
JComboBox<String> petList = new JComboBox<String>(petStrings);
[Link](4);
[Link](this);

picture = new JLabel();


[Link]([Link]().deriveFont([Link]));
[Link]([Link]);
updateLabel(petStrings[[Link]()]);
[Link]([Link](10, 0, 0, 0));

[Link](new Dimension(177, 122 + 10));

add(petList, BorderLayout.PAGE_START);
add(picture, BorderLayout.PAGE_END);
setBorder([Link](20, 20, 20, 20));
}

public void actionPerformed(ActionEvent e) {


JComboBox<String> cb = (JComboBox<String>) [Link]();
String petName = (String) [Link]();
updateLabel(petName);
}

protected void updateLabel(String name) {


ImageIcon icon = createImageIcon("images/" + name + ".gif");
[Link](icon);
[Link]("A drawing of a " + [Link]());
if (icon != null) {
[Link](null);
} else {
[Link]("Image not found");
}
}

/** Returns an ImageIcon, or null if the path was invalid. */


protected static ImageIcon createImageIcon(String path) {
[Link] imgURL = [Link](path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
[Link]("Couldn't find file: " + path);
return null;
}
}

private static void createAndShowGUI() {


[Link](true);

JFrame frame = new JFrame("ComboBoxDemo");


[Link](JFrame.EXIT_ON_CLOSE);

JComponent newContentPane = new ComboBoxDemo();


[Link](true);
[Link](newContentPane);

[Link]();
[Link](true);
}

public static void main(String[] args) {


[Link](new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

9
JDBC
import [Link].*;

public class MyJDBC {


public static void main(String args[]) {
Connection con = null;

try {

// String driverName = "[Link]"; // MySQL MM JDBC driver


// [Link](driverName);
//
// String serverName = "localhost";
// String mydatabase = "mydatabase";
// String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
// String username = "username";
// String password = "password";
// connection = [Link](url, username, password);

[Link]("[Link]");
con = DriverManager
.getConnection("jdbc:sqlserver://
localhost:1433;databaseName=QLHS;user=hao;password=123");

// Statement st = [Link]();
// String strsql = "select * from HOCSINH";
// ResultSet rs = [Link](strsql);
PreparedStatement pst = [Link]("SELECT * FROM HOCSINH");
ResultSet rs = [Link]();

while ([Link]()) {
[Link]([Link]("MAHS") + " | ");
[Link]([Link]("TENHS") + " | ");
[Link]([Link]("DIEM") + " | ");
[Link]([Link]("HINHANH") + " | ");
[Link]([Link]("DIACHI") + " | ");
[Link]([Link]("GHICHU"));
}

String addStatement = "INSERT INTO HOCSINH "


+ "(MAHS, TENHS, DIEM, HINHANH, DIACHI, GHICHU) VALUES ('218', N'Nguyễn Thị
E', 9.3, 'C:\\Users\\Admin\\Desktop\\[Link]', N'địa chỉ bủh', N'no ghi chú')";

// Statement st = [Link]();
// [Link](addStatement);
pst = [Link](addStatement);
[Link]();

[Link]();
} catch (Exception ex) {
[Link]("Error: " + [Link]());
}
}
}

Có nên ôn Callable của jdbc k nhỉ :0

Multithread
invokeAndWait(Runnable doRun): thực thi đồng bộ một thread.
invokeLater(Runnable doRun): thực thi bất đồng bộ một thread
synchronized: 1 thằng sửdụng xong mới tới thằng khác

DeprecatedMethod:
class NewThread implements Runnable { New thread:
String name;
10
Thread t; Thread[One,5,main]
New thread:
NewThread(String threadname) {
name = threadname; Thread[Two,5,main]
t = new Thread(this, name); One: 15
[Link]("New thread: " + t); Two: 15
[Link](); Two: 14
}
One: 14
public void run() { Two: 13
try { One: 13
for (int i = 15; i > 0; i--) { Two: 12
[Link](name + ": " + i); One: 12
[Link](100); Two: 11
} One: 11
} catch (InterruptedException e) { Suspending thread
[Link](name + " interrupted."); One
}
Two: 10
[Link](name + " exiting.");
} Two: 9
} Two: 8
Two: 7
class Test { Two: 6
public static void main(String args[]) {
Resuming thread
NewThread ob1 = new NewThread("One"); One
NewThread ob2 = new NewThread("Two"); Suspending thread
try { Two
[Link](500);
One: 10
[Link](); One: 9
One: 8
[Link]("Suspending thread One"); One: 7
One: 6
[Link](500);
Resuming thread
[Link](); Two
[Link]("Resuming thread One"); Waiting for
[Link](); threads to finish.
Two: 5
[Link]("Suspending thread Two");
[Link](500); One: 5
[Link](); Two: 4
// [Link](); One: 4
[Link]("Resuming thread Two"); Two: 3
} catch (InterruptedException e) {
[Link]("Main thread Interrupted");
One: 3
} Two: 2
One: 2
try { Two: 1
[Link]("Waiting for threads to finish."); One: 1
[Link]();
[Link](); Two exiting.
} catch (InterruptedException e) { One exiting.
[Link]("Main thread Interrupted"); Main thread
} exiting.
[Link]("Main thread exiting.");
}
}

[Link]()

Concurrency
Executors là bất đồng bộ

11
Callable như Runnable nhưng nó có kế
t quả trả về
Future nhận kết quả trả vềtrong tương lai, đồng bộ
ReentrantLock như Synchronized

Executors:
ExecutorService executor = [Link](5);
[Link](() -> {
String threadName = [Link]().getName();
[Link]("Hello " + threadName);
}); //y hệt async if you know what I mean
[Link]();

Callable:
Callable<String> callableTask = () -> {
[Link]("Task is executing ...");
[Link](3);
return "Hello!";
};

try {
ExecutorService executor = [Link](5);
Future<String> future = [Link](callableTask);

[Link]("Task execution finished: " + [Link]());

// wait for the task to finished


String message = [Link]();

[Link]("Task execution finished: " + [Link]());


[Link]("Message: " + message);
} catch (Exception ex) {
[Link]([Link]());
}

Synchronization:
import [Link].*; [Hello[World[Synchronized]
]
class Printer1 { ]
void print(String msg) {
[Link]("[");
[Link](msg); Khi bỏ hết dấu comment:
try { [Hello]
[Link](1000); [Synchronized]
} catch (InterruptedException e) { [World]
[Link]("Interrupted");
}
[Link]("]");
}
}

class PrintThread implements Runnable {


String msg;
Printer1 printer;
Thread t;
// static Lock lock = new ReentrantLock();

public PrintThread(Printer1 targ, String s) {


printer = targ;
msg = s;
t = new Thread(this);
[Link]();
}

public void run() {


// [Link]();

12
// try
// {
// synchronized (printer)
// {
[Link](msg);
// }
// }
// finally
// {
// [Link]();
// }

}
}

public class Test {


public static void main(String args[]) {

Printer1 printer = new Printer1();


PrintThread ob1 = new PrintThread(printer,
"Hello");
PrintThread ob2 = new PrintThread(printer,
"Synchronized");
PrintThread ob3 = new PrintThread(printer,
"World");

try {
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Interrupted");
}

[Link]();
}
}

Networking
import [Link].*;
import [Link].*;

TCP:
TCPServer TCPClient
ServerSocket s = new ServerSocket(3200); Socket s = new Socket("localhost", 3200);
[Link]([Link]());
do {
[Link]("Waiting for a Client"); InputStream is = [Link]();
BufferedReader br = new BufferedReader(new
Socket ss = [Link](); // synchronous InputStreamReader(is));

[Link]("Talking to client"); OutputStream os = [Link]();


[Link]([Link]()); BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(os));
InputStream is = [Link]();
BufferedReader br = new BufferedReader(new String sentMessage = "";
InputStreamReader(is)); String receivedMessage;

OutputStream os = [Link](); [Link]("Talking to Server");


BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(os)); do {
13
BufferedReader brConsole = new
String receivedMessage; BufferedReader(new
InputStreamReader([Link]));
do { sentMessage = [Link]();
receivedMessage = [Link](); [Link](sentMessage);
[Link]("Received : " + [Link]();
receivedMessage); [Link]();
if
([Link]("quit")) if ([Link]("quit"))
{ break;
[Link]("Client has left !"); else {
break; receivedMessage = [Link]();
} else { [Link]("Received : " +
BufferedReader brConsole = new receivedMessage);
BufferedReader(new InputStreamReader([Link])); }
String k = [Link]();
[Link](k); } while (true);
[Link]();
[Link](); [Link]();
} [Link]();
} while (true);
[Link]();
[Link]();
} while (true);

UDP:
UDPClient1 UDPClient2
DatagramSocket utpSocket = new DatagramSocket utpSocket = new
DatagramSocket(3400); DatagramSocket(3500);

byte[] receivedBuf = new byte[100]; InetAddress sentHost =


DatagramPacket receivedPacket = new [Link]("localhost");
DatagramPacket(receivedBuf, String sentMessage = "Hello, there !";
[Link]); byte[] sentBuf = new byte[100];
[Link](receivedPacket); sentBuf = [Link]("ascii");
[Link]("Received : " + new DatagramPacket sentPacket = new
String(receivedBuf)); DatagramPacket(sentBuf, [Link],
sentHost, 3400); //send thì nó ở port khác
InetAddress sentHost = socket
[Link]("localhost"); [Link](sentPacket);
String sentMessage = "I had received your [Link](" Sent : " + sentMessage);
message";
byte[] sentBuf = new byte[100]; byte[] receivedBuf = new byte[100];
sentBuf = [Link]("ascii"); DatagramPacket receivedPacket = new
DatagramPacket sentPacket = new DatagramPacket(receivedBuf,
DatagramPacket(sentBuf, [Link], [Link]);
sentHost, 3500); //send thì nó ở port khác [Link](receivedPacket);
socket [Link](" Received : " + new
[Link](sentPacket); String(receivedBuf));
[Link]("Sent : " + sentMessage);
[Link]();
[Link]();

URLDirect:
try {
URL url = new URL("[Link]

BufferedReader in = new BufferedReader(new


InputStreamReader([Link]()));
String inputLine;
while ((inputLine = [Link]()) != null)
[Link](inputLine);
[Link]();
} catch (MalformedURLException mue) {
[Link]("Check your URL");
} catch (IOException ioe) {
[Link]("Check your IO stream");

14
}

15

You might also like