Xu Hướng 11/2022 # Cách Tạo, Sử Dụng Và Tuỳ Biến Một Button Trong Java Swing / 2023 # Top 16 View | Rafs.edu.vn

Bạn đang xem bài viết Cách Tạo, Sử Dụng Và Tuỳ Biến Một Button Trong Java Swing / 2023 được cập nhật mới nhất trên website Rafs.edu.vn. Hy vọng những thông tin mà chúng tôi đã chia sẻ là hữu ích với bạn. Nếu nội dung hay, ý nghĩa bạn hãy chia sẻ với bạn bè của mình và luôn theo dõi, ủng hộ chúng tôi để cập nhật những thông tin mới nhất.

Button được biến đến như là một control được sử dụng rất nhiều trong Java Swing cùng với Label, TextField, etc. Trong bài viết này chúng ta sẽ cùng nhau tìm hiểu nhanh cách để tạo, sử dụng và tuỳ biến một Button theo mục đích riêng của chúng ta.

Cách tạo Button trong Java Swing

Để khởi tạo một Button trong Java Swing chúng ta có thể làm như sau:

Ví dụ tạo Button và xử lý sự kiện

import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class JButtonExample extends JFrame { private JLabel lb; public JButtonExample() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 200); setLayout(new GridLayout(2, 1, 5, 5)); lb = new JLabel(“Label Title”); lb.setHorizontalAlignment(JLabel.CENTER); add(lb); JButton btn = new JButton(“Nhấn vào đây”); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { changeTextJLabel(); } }); add(btn); setLocationRelativeTo(null); setVisible(true); } private void changeTextJLabel() { lb.setText(“Bạn đã nhấp vào Button”); } public static void main(String[] args) { new JButtonExample(); } } import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class JButtonExample extends JFrame { private JLabel lb; public JButtonExample() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 200); setLayout(new GridLayout(2, 1, 5, 5)); lb = new JLabel(“Label Title”); lb.setHorizontalAlignment(JLabel.CENTER); add(lb); JButton btn = new JButton(“Nhấn vào đây”); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { changeTextJLabel(); } }); add(btn); setLocationRelativeTo(null); setVisible(true); } private void changeTextJLabel() { lb.setText(“Bạn đã nhấp vào Button”); } public static void main(String[] args) { new JButtonExample(); } }

import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class JButtonExample extends JFrame { private JLabel lb; public JButtonExample() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 200); setLayout(new GridLayout(2, 1, 5, 5)); lb = new JLabel(“Label Title”); lb.setHorizontalAlignment(JLabel.CENTER); add(lb); JButton btn = new JButton(“Nhấn vào đây”); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { changeTextJLabel(); } }); add(btn); setLocationRelativeTo(null); setVisible(true); } private void changeTextJLabel() { lb.setText(“Bạn đã nhấp vào Button”); } public static void main(String[] args) { new JButtonExample(); } } import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class JButtonExample extends JFrame { private JLabel lb; public JButtonExample() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 200); setLayout(new GridLayout(2, 1, 5, 5)); lb = new JLabel(“Label Title”); lb.setHorizontalAlignment(JLabel.CENTER); add(lb); JButton btn = new JButton(“Nhấn vào đây”); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { changeTextJLabel(); } }); add(btn); setLocationRelativeTo(null); setVisible(true); } private void changeTextJLabel() { lb.setText(“Bạn đã nhấp vào Button”); } public static void main(String[] args) { new JButtonExample(); } }

Kết quả:

Khi mới khởi chạy

Mặc định thì khi khởi tạo một JButton chỉ có đoạn văn bảng đại diện cho Button, chúng ta có thể thêm các hình ảnh vào Button cho sinh động đẹp mắt thêm như sau.

Button chỉ chứa hình

JButton button = new JButton(new ImageIcon(“images/start.gif”));

JButton button = new JButton(new ImageIcon(“images/start.gif”));

Button chứa cả hình và chữa

JButton button = new JButton(“Start”, new ImageIcon(“images/start.gif”));

JButton button = new JButton(“Start”, new ImageIcon(“images/start.gif”));

Xử lý sự kiện trong Button

Để xử lý sự kiện khi người dùng nhấp vào Button chúng ta có thể làm như sau:

button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { } }); import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JTextField; public class Main { public static void main(String[] argv) throws Exception { JTextField component = new JTextField(); component.addMouseListener(new MyMouseListener()); JFrame f = new JFrame(); f.add(component); f.setSize(300, 300); f.setVisible(true); component.addMouseListener(new MyMouseListener()); } } class MyMouseListener extends MouseAdapter { } } }

button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { } }); import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JTextField; public class Main { public static void main(String[] argv) throws Exception { JTextField component = new JTextField(); component.addMouseListener(new MyMouseListener()); JFrame f = new JFrame(); f.add(component); f.setSize(300, 300); f.setVisible(true); component.addMouseListener(new MyMouseListener()); } } class MyMouseListener extends MouseAdapter { } } }

Tạo phím tắt, phím ghi nhớ cho Button

Nếu các bạn để ý thì hầu hết các ứng dụng đều tạo một số phím tắt, phím ghi nhớ dùng cho các chức năng sử dụng nhiều.

Ví dụ tạo phím nhớ ALT + E để gọi đến sự kiện nhấp vào Button Edit.

button.setMnemonic(KeyEvent.VK_E);

button.setMnemonic(KeyEvent.VK_E);

Hoặc chúng ta có thể tạo các phím nóng bằng cách sau:

String mapKey = “KEY_F2”; InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke(“F2”), mapKey); button.getActionMap().put(mapKey, new AbstractAction() { public void actionPerformed(ActionEvent evt) { buttonActionPerformed(evt); } });

String mapKey = “KEY_F2”; InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke(“F2”), mapKey); button.getActionMap().put(mapKey, new AbstractAction() { public void actionPerformed(ActionEvent evt) { buttonActionPerformed(evt); } });

Trong ví dụ trên mình đã tạo một phím nóng F2 để gọi đến sự kiện nhấp chuột vào Button, khi đó hàm xử lý sự kiện sẽ được thực thi.

Tuỳ biến giao diện Button

Một số thao thác thường dùng với Button như thay đổi màu nền với setBackground().

button.setBackground(Color.YELLOW);

button.setBackground(Color.YELLOW);

Hay xác định Font, cỡ chữ

button.setFont(new java.awt.Font(“Arial”, Font.BOLD, 14));

button.setFont(new java.awt.Font(“Arial”, Font.BOLD, 14));

Nguồn tham khảo

JTextField là một component có lẽ cũng được sử dụng rất nhiều trong các ứng dụng Java Swing cùng với Button, Label, CheckBox, etc.

JTextField là một component cho phép nhập và chỉnh sữa đoạn văn bản trên cùng một dòng vì thế nó thường phù hợp cho việc nhập, chỉnh sửa các thông tin dạng ngắn gọn, mang đại ý như là email, password, tên công ty, tên sinh viên, etc. Còn những thông tin dài hơn thì chúng ta có thể sử dụng JTextArea cho phép nhập, chỉnh sửa dữ liệu trên nhiều dòng.

Tạo JTextField

Để khởi tạo một JTextField trong Java Swing rất đơn giản với cú pháp sau:

JTextField jTextField = new JTextField();

JTextField jTextField = new JTextField();

Để khởi tạo một JTextField với đoạn văn bản có sẵn thì có thể làm như sau:

JTextField jTextField = new JTextField(“Default Text”);

JTextField jTextField = new JTextField(“Default Text”);

Trong JTextField có một thuộc tính gọi là columns được dùng để tính toán độ rộng của JTextField, mặc định nó là 0 nên khi không có dữ liệu thì kích thước của nó sẽ rất nhỏ. Để chỉ định columns cho JTextField chúng ta có thể khởi tạo như sau:

JTextField textField = new JTextField(20);

JTextField textField = new JTextField(20);

Note:

Nếu JTextField được khởi tạo mà không được cung cấp đoạn văn bản ban đầu thì giá trị này sẽ là null. Các bạn nhớ lưu ý khi thao tác nếu không có thể bị NullPointerException.

Nếu columns không được cung cấp lúc khởi tạo thì giá trị mặc định nó là 0, chiều rộng của JTextField sẽ được tính dựa vào văn bản. Nếu cả 2 văn bản và columns không được cung cấp thì chiều rộng của nó sẽ nhỏ tối đa.

Ví dụ tạo 2 JTextFiled trong JFrame

import javax.swing.*; public class JTextFieldExample { public static void main(String[] agrs) { JFrame mainFrame = new JFrame(“JtextField Exampke”); mainFrame.setSize(400, 150); JPanel panel = new JPanel(); JTextField jTextField = new JTextField(10); JTextField jTextField1 = new JTextField(20); panel.add(jTextField); panel.add(jTextField1); mainFrame.add(panel); mainFrame.setVisible(true); } }

import javax.swing.*; public class JTextFieldExample { public static void main(String[] agrs) { JFrame mainFrame = new JFrame(“JtextField Exampke”); mainFrame.setSize(400, 150); JPanel panel = new JPanel(); JTextField jTextField = new JTextField(10); JTextField jTextField1 = new JTextField(20); panel.add(jTextField); panel.add(jTextField1); mainFrame.add(panel); mainFrame.setVisible(true); } }

Để lấy giá trị của String trong JTextField chúng ta có thể sử dụng getText() method.

String content = textField.getText()

String content = textField.getText()

Hoặc có thể tuỳ chọn vị trí bắt đầu của String và đọc với số lượng tối đa bao nhiêu ký tự thì làm như sau:

int offset = 5; int length = 10; try { content = textField.getText(offset, length); } catch (BadLocationException ex) { }

int offset = 5; int length = 10; try { content = textField.getText(offset, length); } catch (BadLocationException ex) { }

Đoạn code trên sẽ sẽ trả về 10 ký tự từ vị trí thứ 5 trong văn bản.

Tạo Tooltip cho JTextField

Đôi khi đoạn văn bản của chúng ta quá nhiều và không thể hiển thị đầy đủ trên JTextField, hay bạn muốn hiển thị một thông điệp gì đó khi người dùng rê chuột vào một JTextField thì các bạn có thể sử dụng setToolTipText() method

public class JTextFieldExample { public static void main(String[] agrs) { JFrame mainFrame = new JFrame(“JtextField Exampke”); mainFrame.setSize(400, 150); JPanel panel = new JPanel(); JTextField jTextField = new JTextField(10); jTextField.setToolTipText(“Tooltip here!”); panel.add(jTextField); mainFrame.add(panel); mainFrame.setLocationRelativeTo(null); mainFrame.setVisible(true); } }

public class JTextFieldExample { public static void main(String[] agrs) { JFrame mainFrame = new JFrame(“JtextField Exampke”); mainFrame.setSize(400, 150); JPanel panel = new JPanel(); JTextField jTextField = new JTextField(10); jTextField.setToolTipText(“Tooltip here!”); panel.add(jTextField); mainFrame.add(panel); mainFrame.setLocationRelativeTo(null); mainFrame.setVisible(true); } }

Thông thường JTextField sẽ ở trạng thái khi người dùng nhấp chuột vào đó, tuy nhiên chúng ta vẫn có thể xử lý chuyện này với code thông qua requestFocusInWindow() method.

textField.requestFocusInWindow();

textField.requestFocusInWindow();

Xử lý sự kiện trong JTextField

Việc thêm một sự kiện cho JTextField thông thường được dùng để kiểm tra xem người dùng đang nhập những gì từ đó có chương trình có thể làm những tác vụ tiếp theo, ví dụ JTextFiled dùng để tra từ điển thì khi người dùng đang nhập từng chữ thì có chúng ta thể tìm kiếm dưới database trước và hiển thị lên giao diện gợi ý cho người dùng. Hay kiểm tra lỗi realtime, mỗi ký tự nhập vào là kiểm tra lỗi luôn chẳng hạn.

import javax.swing.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class JTextFieldExample { public static void main(String[] agrs) { JFrame mainFrame = new JFrame(“JtextField Exampke”); mainFrame.setSize(400, 150); JPanel panel = new JPanel(); JTextField jTextField = new JTextField(10); jTextField.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent event) { System.out.println(“key typed”); } @Override public void keyReleased(KeyEvent event) { System.out.println(“key released”); } @Override public void keyPressed(KeyEvent event) { System.out.println(“key pressed”); } }); panel.add(jTextField); jTextField.requestFocusInWindow(); mainFrame.add(panel); mainFrame.setLocationRelativeTo(null); mainFrame.setVisible(true); } }

import javax.swing.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class JTextFieldExample { public static void main(String[] agrs) { JFrame mainFrame = new JFrame(“JtextField Exampke”); mainFrame.setSize(400, 150); JPanel panel = new JPanel(); JTextField jTextField = new JTextField(10); jTextField.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent event) { System.out.println(“key typed”); } @Override public void keyReleased(KeyEvent event) { System.out.println(“key released”); } @Override public void keyPressed(KeyEvent event) { System.out.println(“key pressed”); } }); panel.add(jTextField); jTextField.requestFocusInWindow(); mainFrame.add(panel); mainFrame.setLocationRelativeTo(null); mainFrame.setVisible(true); } }

Select các ký tự trong JTextFiled

Hành động này tương tự với việc người dùng nhấp chuột và kéo bôi những đoạn văn bản họ muốn.

Ví dụ chọn tất cả các văn bản trong JTextField

textField.selectAll();

Chọn các ký tự từ một vị trí bắt đầu và kết thúc được chỉ định

textField.setSelectionEnd(12);

Tuỳ biến JTextField

Với JTextField chúng ta có thể tuỳ biến nó trong một số trường hợp sau:

Vô hiệu hoá tính năng chỉnh sửa, tính năng này thường được dùng khi JTextField này không thể nhập dữ liệu đối với một số trường hợp cụ thể.

textField.setEditable(false);

textField.setEditable(false);

Căn chỉnh văn bản ở giữa

textField.setHorizontalAlignment(JTextField.CENTER)

textField.setHorizontalAlignment(JTextField.CENTER)

Chúng ta có thể tuỳ chỉnh bằng các hằng số khác tuỳ vào nhu cầu sử dụng

JTextField.LEFT

JTextField.CENTER

JTextField.RIGHT

JTextField.LEADING

JTextField.TRAILING

Có thể chỉ định font chữ, kích thước, màu nền

textField.setForeground(Color.BLUE); textField.setBackground(Color.YELLOW);

Nguồn tham khảo

https://www.codejava.net/java-se/swing/jtextfield-basic-tutorial-and-examples

Hôm nay mình sẽ hướng dẫn các bạn sử dụng Pattern, nó cũng gần giống với cách sử dụng Texture, nhưng về cơ bản nó chỉ là những mẫu rất nhỏ và dùng để fill lên bề mặt của hình ảnh. Thông thường bạn thấy những tấm ảnh nhìn rất giống những ảnh in lụa, có sọc sọc, đó chính là hiệu ứng của Pattern, mình có một ví dụ như sau:

I. Pattern là gì?

Pattern trước hết bắt nguồn từ tiếng Pháp Patron, có nghĩa “một dạng, một khuôn thức, hay một mô hình (một cách trừu tượng, là một tập hợp các qui tắc) mà có thể dùng để làm ra hay tạo nên những sự vật hoặc các bộ phận của của một vật”. (Wikipedia).

Khái niệm này được sử dụng rộng rãi trong các ngành khoa học như thiên văn học, toán học, hình học, tâm lý học…

Trong đồ họa cũng vậy, pattern được hiểu là một dạng “gạch lát”. Ta hãy xem một số pattern:

Hãy tưởng tượng mỗi khung nhỏ trong hình là một viên gạch. Nếu ta có một viên gạch thứ hai giống hệt “lát” cạnh viên gạch cũ thì “hoa văn” trên viên gạch sẽ lặp lại; tiếp tục đến viên thứ ba, thứ tư… nếu có đủ số “gạch” để lát toàn bộ bề mặt bức tranh thì cả bức tranh sẽ có một “hoa văn” như nhau.

II. Tại sao cần pattern?

Hãy hình dung một người thợ định sơn toàn bộ bức tường. Người này thiết kế ra một mẫu họa tiết rất đẹp, nhưng lại quá nhỏ. Anh nghĩ ra một cách, đó là sơn đi sơn lại họa tiết này để phủ kín bức tường. Hiển nhiên cách làm của anh là hoàn toàn có thể, nhưng người thợ ốp lại có cách nghĩ khác. Anh này lập tức cầm mẫu thiết kế hoa văn của mình và gọi đến công ty chuyên cung cấp gạch ốp lát, yêu cầu một loạt gạch ốp lát có hoa văn y hệt như thế. Vậy là trong lúc người thợ sơn kia sơn từng ô một, mỗi lần sơn là một lần tốn công sức làm việc và còn sợ sai sót nữa, anh này chỉ cần ốp số gạch đã đặt lên tường – không kể thời gian đặt số gạch đó!

Pattern cũng vậy. Bạn có thể tỉ mẩn tô từng ô một, kết quả không khác biệt gì. Nhưng thay vì tốn công như vậy, vả lại còn dễ phạm sai sót – tăng số lần làm nghĩa là tăng xác suất sai – chi bằng dựa vào người “thợ ốp lát kiêm công ty cung cấp gạch ốp lát” của bạn – chính là photoshop!

III. Cách tạo một pattern

Để tạo một pattern cho riêng bạn, làm theo các bước sau. Cụ thể ở đây tớ sẽ tạo một dạng pattern sọc chéo.

1. Tạo một file mới, kích thước tùy ý có nền trong suốt (không màu). Ở đây tớ chọn 3 x 3.

2. Dùng pencil tool hoặc công cụ khác tô màu đen vào các pixel như sau. Chú ý phần caro trắng và xám là không màu.

Từ giờ trở đi mỗi lần bạn làm việc với pattern, pattern bạn vừa tạo sẽ nằm cuối cùng trong danh sách các pattern của photoshop.

Lưu ý là nếu khu vực bạn lựa chọn thực chất có nhiều ô giống hệt nhau ghép lại thì photoshop sẽ tự động lựa chọn ô đó làm pattern thay vì lấy toàn bộ vùng chọn.

IV. Cách sử dụng pattern

2. Brush: Sử dụng pattern như một brush (cọ) để “tô” lên tranh. Để thực hiện thao tác này, chọn công cụ Pattern Stamp, thiết lập như hình vẽ và tiến hành tô:

Hơi khó hiểu phải không? các bạn chú ý theo dõi bằng video clip nha…

Luồng nhị phân dẫn đầu bởi 2 class InputStream và OutputStream dưới 2 class này là rất nhiều các class con , nếu so sánh về lực lượng theo cách này mà nói thì họ hàng luồng nhị phân (Binary Stream) nhiều và phức tạp hơn hẳn so với họ hàng luồng ký tự (Charactor Stream).Với JDK1.5 trong luồng nhị phân có 2 class được khuyến cáo là không nên sử dụng là LineNumberInputStream và StringBufferInputStream vì đã bị lỗi thời .

2- Class InputStream & OutputStream

Class InputStream là một class trừu tượng vì vậy bạn không thể khởi tạo đối tượng InputStream thông qua chính class InputStream. Tuy nhiên class này rẽ ra nhiều nhánh thông qua các class con thừa kế nó. Tùy vào các tình huống bạn có thể tạo đối tượng InputStream từ các Constructor của các class con.

InputStream fileStream =new FileInputStream(“C:/test.txt”); InputStream is = System.in;

InputStream fileStream =new FileInputStream(“C:/test.txt”); InputStream is = System.in;

Class OutputStream là một class trìu tượng vì vậy bạn không thể khởi tạo đối tượng OutputStream thông qua chính class OutputStream .Tuy nhiên class này rẽ ra nhiều nhánh thông qua các class con thừa kế nó và quan trọng .Tùy vào các tình huống bạn có thể tạo đối tượng InputStream từ cấu tử của các class con.

OutputStream os=new FileOutputStream(“D:/outData.txt”); OutputStream w=System.out; package org.o7planning.tutorial.javaio.stream; import java.io.FileInputStream; import java.io.InputStream; public class HelloInputStream { public static void main(String[] args) { try { InputStream is = new FileInputStream(“data.txt”); int i = -1; while ((i = is.read()) != -1) { System.out.println(i + ” ” + (char) i); } is.close(); } catch (Exception e) { e.printStackTrace(); } } } package org.o7planning.tutorial.javaio.stream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; public class HelloOutputStream { public static void main(String[] args) { try { File dir = new File(“C:/Test”); dir.mkdirs(); OutputStream w = new FileOutputStream( “C:/Test/test_outputStream.txt”); byte[] by = new byte[] { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ }; for (int i = 0; i < by.length; i++) { byte b = by[i]; w.write(b); } w.close(); } catch (Exception e) { e.printStackTrace(); } } }

OutputStream os=new FileOutputStream(“D:/outData.txt”); OutputStream w=System.out; package org.o7planning.tutorial.javaio.stream; import java.io.FileInputStream; import java.io.InputStream; public class HelloInputStream { public static void main(String[] args) { try { InputStream is = new FileInputStream(“data.txt”); int i = -1; while ((i = is.read()) != -1) { System.out.println(i + ” ” + (char) i); } is.close(); } catch (Exception e) { e.printStackTrace(); } } } package org.o7planning.tutorial.javaio.stream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; public class HelloOutputStream { public static void main(String[] args) { try { File dir = new File(“C:/Test”); dir.mkdirs(); OutputStream w = new FileOutputStream( “C:/Test/test_outputStream.txt”); byte[] by = new byte[] { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ }; for (int i = 0; i < by.length; i++) { byte b = by[i]; w.write(b); } w.close(); } catch (Exception e) { e.printStackTrace(); } } }

2 Ví dụ phía trên là đơn giản, chúng đọc hoặc ghi từng byte, trong ví dụ tiếp theo chúng ta sẽ đọc hoặc ghi đồng loạt nhiều byte, việc này làm tăng tốc việc xử lý.

package org.o7planning.tutorial.javaio.stream; import java.io.FileInputStream; import java.io.InputStream; public class InputStreamExample2 { public static void main(String[] args) { try { InputStream in = new FileInputStream(“data.txt”); byte[] temp = new byte[10]; int i = -1; while ((i = in.read(temp)) != -1) { String s = new String(temp, 0, i); System.out.println(s); } in.close(); } catch (Exception e) { e.printStackTrace(); } } }

package org.o7planning.tutorial.javaio.stream; import java.io.FileInputStream; import java.io.InputStream; public class InputStreamExample2 { public static void main(String[] args) { try { InputStream in = new FileInputStream(“data.txt”); byte[] temp = new byte[10]; int i = -1; while ((i = in.read(temp)) != -1) { String s = new String(temp, 0, i); System.out.println(s); } in.close(); } catch (Exception e) { e.printStackTrace(); } } }

OutputStreamExample2.java

package org.o7planning.tutorial.javaio.stream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; public class OutputStreamExample2 { public static void main(String[] args) { try { File dir = new File(“C:/Test”); dir.mkdirs(); OutputStream os = new FileOutputStream(“C:/Test/test_writerOutputStream.txt”); byte[] by = new byte[] { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, 31, 34, 92 }; byte[] by2 = new byte[] { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘b’, ‘o’, ‘y’ }; os.write(by); os.flush(); os.write(by2); os.close(); } catch (Exception e) { e.printStackTrace(); } } }

package org.o7planning.tutorial.javaio.stream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; public class OutputStreamExample2 { public static void main(String[] args) { try { File dir = new File(“C:/Test”); dir.mkdirs(); OutputStream os = new FileOutputStream(“C:/Test/test_writerOutputStream.txt”); byte[] by = new byte[] { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, 31, 34, 92 }; byte[] by2 = new byte[] { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘b’, ‘o’, ‘y’ }; os.write(by); os.flush(); os.write(by2); os.close(); } catch (Exception e) { e.printStackTrace(); } } }

ByteArrayInputStream bao bọc một mảng các byte (byte[] buf) và thông qua ByteArrayInputStream truy cập phần tử mảng ..

ByteArrayOutputStream là một luồng các byte, bên trong đối tượng này chứa một mảng các byte (byte[] buf) có khả năng tự tăng kích cỡ khi số byte của luồng tăng lên.Mỗi khi luồng được ghi vào các byte thì chính là gán tiếp byte đó vào các vị trí mảng chưa được gán ..

Khi mảng đầy phần tử thì chương trình tạo mảng mới có độ dài lớn hơn và copy các phần tử của mảng cũ vào …(Đó là cách tự lớn lên của mảng các byte như đã nói trên)

Vài method của ByteArrayOutputStream:

– byte[] toByteArray(); – String toString() ; – int size();

– byte[] toByteArray(); – String toString() ; – int size();

ByteArrayInputStreamExample.java

package org.o7planning.tutorial.javaio.bytestream; import java.io.ByteArrayInputStream; import java.io.IOException; public class ByteArrayInputStreamExample { public static void main(String args[]) throws IOException { byte[] bytes = new byte[] { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘I’, ‘O’ }; ByteArrayInputStream bInput = new ByteArrayInputStream(bytes); System.out.println(“Converting characters to Upper case “); int c = 0; while ((c = bInput.read()) != -1) { char ch = (char) c; ch = Character.toUpperCase(ch); System.out.println(ch); } boolean markSupport = bInput.markSupported(); System.out.println(“Mark Support? ” + markSupport); bInput.reset(); char ch = (char) bInput.read(); System.out.println(ch); ch = (char) bInput.read(); System.out.println(ch); System.out.println(“Skip 4”); bInput.skip(4); ch = (char) bInput.read(); System.out.println(ch); } }

package org.o7planning.tutorial.javaio.bytestream; import java.io.ByteArrayInputStream; import java.io.IOException; public class ByteArrayInputStreamExample { public static void main(String args[]) throws IOException { byte[] bytes = new byte[] { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘I’, ‘O’ }; ByteArrayInputStream bInput = new ByteArrayInputStream(bytes); System.out.println(“Converting characters to Upper case “); int c = 0; while ((c = bInput.read()) != -1) { char ch = (char) c; ch = Character.toUpperCase(ch); System.out.println(ch); } boolean markSupport = bInput.markSupported(); System.out.println(“Mark Support? ” + markSupport); bInput.reset(); char ch = (char) bInput.read(); System.out.println(ch); ch = (char) bInput.read(); System.out.println(ch); System.out.println(“Skip 4”); bInput.skip(4); ch = (char) bInput.read(); System.out.println(ch); } }

ByteArrayOutputStreamExample.java

package org.o7planning.tutorial.javaio.bytestream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class ByteArrayOutputStreamExample { public static void main(String args[]) throws IOException { ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12); String s = “Hello ByteArrayOutputStream”; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch != ‘a’ && ch != ‘e’) { bOutput.write(ch); } } int size = bOutput.size(); System.out.println(“Size = ” + size); byte[] bytes = bOutput.toByteArray(); String ss = new String(bytes); System.out.println(“New String = ” + ss); } }

package org.o7planning.tutorial.javaio.bytestream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class ByteArrayOutputStreamExample { public static void main(String args[]) throws IOException { ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12); String s = “Hello ByteArrayOutputStream”; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch != ‘a’ && ch != ‘e’) { bOutput.write(ch); } } int size = bOutput.size(); System.out.println(“Size = ” + size); byte[] bytes = bOutput.toByteArray(); String ss = new String(bytes); System.out.println(“New String = ” + ss); } }

4- Class ObjectInputStream & ObjectOutputStream

ObjectInputStream, ObjectOutputStream cho phép bạn đọc hoặc ghi một Object vào luồng. Các Object này phải là kiểu Serializable (Nghĩa là có thể sắp hàng).

package org.o7planning.tutorial.javaio.objstream; import java.io.Serializable; public class Student implements Serializable { private static final long serialVersionUID = -5074534753977873204L; private String firstName; private String lastName; public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } package org.o7planning.tutorial.javaio.objstream; import java.io.Serializable; public class Pupil implements Serializable { private static final long serialVersionUID = -8501383434011302991L; private String fullName; public Pupil(String fullName) { this.fullName= fullName; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } }

package org.o7planning.tutorial.javaio.objstream; import java.io.Serializable; public class Student implements Serializable { private static final long serialVersionUID = -5074534753977873204L; private String firstName; private String lastName; public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } package org.o7planning.tutorial.javaio.objstream; import java.io.Serializable; public class Pupil implements Serializable { private static final long serialVersionUID = -8501383434011302991L; private String fullName; public Pupil(String fullName) { this.fullName= fullName; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } }

ObjectOutputStreamExample.java

package org.o7planning.tutorial.javaio.objstream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.Date; public class ObjectOutputStreamExample { public static void main(String[] args) throws IOException { File dir = new File(“C:/Test”); dir.mkdirs(); FileOutputStream fos = new FileOutputStream( “C:/Test/testObjectStream.txt”); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeUTF(“This is student, pupil profiles”); oos.writeObject(new Date()); Student student1 = new Student(“Thanh”, “Phan”); Student student2 = new Student(“Ngan”, “Tran”); Pupil pupil1 = new Pupil(“Nguyen Van Ba”); oos.writeObject(student1); oos.writeObject(pupil1); oos.writeObject(student2); oos.close(); System.out.println(“Write successful”); } }

package org.o7planning.tutorial.javaio.objstream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.Date; public class ObjectOutputStreamExample { public static void main(String[] args) throws IOException { File dir = new File(“C:/Test”); dir.mkdirs(); FileOutputStream fos = new FileOutputStream( “C:/Test/testObjectStream.txt”); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeUTF(“This is student, pupil profiles”); oos.writeObject(new Date()); Student student1 = new Student(“Thanh”, “Phan”); Student student2 = new Student(“Ngan”, “Tran”); Pupil pupil1 = new Pupil(“Nguyen Van Ba”); oos.writeObject(student1); oos.writeObject(pupil1); oos.writeObject(student2); oos.close(); System.out.println(“Write successful”); } }

Và ví dụ với ObjectInputStream đọc file vừa được ghi ra tại ví dụ trên:

ObjectInputStreamExample.java

package org.o7planning.tutorial.javaio.objstream; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Date; public class ObjectInputStreamExample { public static void main(String[] args) throws IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream( “C:/Test/testObjectStream.txt”); ObjectInputStream ois = new ObjectInputStream(fis); String s = ois.readUTF(); System.out.println(s); Date date = (Date) ois.readObject(); System.out.println(“Date = ” + date); Student student1 = (Student) ois.readObject(); System.out.println(“Student ” + student1.getFirstName()); Pupil pupil = (Pupil) ois.readObject(); System.out.println(“Pupil ” + pupil.getFullName()); Student student2 = (Student) ois.readObject(); System.out.println(“Student ” + student2.getFirstName()); ois.close(); } } public DataOutputStream(OutputStream out) public void writeChar(int val) public void writeDouble(double val) public void writeFloat(float val) public void writeInt(int val) public void writeUTF(String obj) …. public DataInputStream(InputStream in) public char readChar() public double readDouble() public float readFloat() public int readInt() public String readUTF() ….

package org.o7planning.tutorial.javaio.objstream; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Date; public class ObjectInputStreamExample { public static void main(String[] args) throws IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream( “C:/Test/testObjectStream.txt”); ObjectInputStream ois = new ObjectInputStream(fis); String s = ois.readUTF(); System.out.println(s); Date date = (Date) ois.readObject(); System.out.println(“Date = ” + date); Student student1 = (Student) ois.readObject(); System.out.println(“Student ” + student1.getFirstName()); Pupil pupil = (Pupil) ois.readObject(); System.out.println(“Pupil ” + pupil.getFullName()); Student student2 = (Student) ois.readObject(); System.out.println(“Student ” + student2.getFirstName()); ois.close(); } } public DataOutputStream(OutputStream out) public void writeChar(int val) public void writeDouble(double val) public void writeFloat(float val) public void writeInt(int val) public void writeUTF(String obj) …. public DataInputStream(InputStream in) public char readChar() public double readDouble() public float readFloat() public int readInt() public String readUTF() ….

DataOutputStreamExample.java

package org.o7planning.tutorial.javaio.datastream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class DataOutputStreamExample { public static void main(String[] args) throws IOException { int cityIdA = 1; String cityNameA = “Green Lake City”; int cityPopulationA = 500000; float cityTempA = 15.50f; int cityIdB = 2; String cityNameB = “Salt Lake City”; int cityPopulationB = 250000; float cityTempB = 10.45f; File dir = new File(“C:/Test”); dir.mkdirs(); FileOutputStream fos = new FileOutputStream(“C:/Test/cities.txt”); DataOutputStream dos = new DataOutputStream(fos); dos.writeInt(cityIdA); dos.writeUTF(cityNameA); dos.writeInt(cityPopulationA); dos.writeFloat(cityTempA); dos.writeInt(cityIdB); dos.writeUTF(cityNameB); dos.writeInt(cityPopulationB); dos.writeFloat(cityTempB); dos.flush(); dos.close(); } }

package org.o7planning.tutorial.javaio.datastream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class DataOutputStreamExample { public static void main(String[] args) throws IOException { int cityIdA = 1; String cityNameA = “Green Lake City”; int cityPopulationA = 500000; float cityTempA = 15.50f; int cityIdB = 2; String cityNameB = “Salt Lake City”; int cityPopulationB = 250000; float cityTempB = 10.45f; File dir = new File(“C:/Test”); dir.mkdirs(); FileOutputStream fos = new FileOutputStream(“C:/Test/cities.txt”); DataOutputStream dos = new DataOutputStream(fos); dos.writeInt(cityIdA); dos.writeUTF(cityNameA); dos.writeInt(cityPopulationA); dos.writeFloat(cityTempA); dos.writeInt(cityIdB); dos.writeUTF(cityNameB); dos.writeInt(cityPopulationB); dos.writeFloat(cityTempB); dos.flush(); dos.close(); } }

Chạy class DataOutputStreamExample và nhận được một file dữ liệu được ghi ra.

DataInputStreamExample.java

package org.o7planning.tutorial.javaio.datastream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class DataInputStreamExample { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream(“C:/Test/cities.txt”); DataInputStream dis = new DataInputStream(fis); int cityId1 = dis.readInt(); System.out.println(“Id: ” + cityId1); String cityName1 = dis.readUTF(); System.out.println(“Name: ” + cityName1); int cityPopulation1 = dis.readInt(); System.out.println(“Population: ” + cityPopulation1); float cityTemperature1 = dis.readFloat(); System.out.println(“Temperature: ” + cityTemperature1); int cityId2 = dis.readInt(); System.out.println(“Id: ” + cityId2); String cityName2 = dis.readUTF(); System.out.println(“Name: ” + cityName2); int cityPopulation2 = dis.readInt(); System.out.println(“Population: ” + cityPopulation2); float cityTemperature2 = dis.readFloat(); System.out.println(“Temperature: ” + cityTemperature2); dis.close(); } }

package org.o7planning.tutorial.javaio.datastream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class DataInputStreamExample { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream(“C:/Test/cities.txt”); DataInputStream dis = new DataInputStream(fis); int cityId1 = dis.readInt(); System.out.println(“Id: ” + cityId1); String cityName1 = dis.readUTF(); System.out.println(“Name: ” + cityName1); int cityPopulation1 = dis.readInt(); System.out.println(“Population: ” + cityPopulation1); float cityTemperature1 = dis.readFloat(); System.out.println(“Temperature: ” + cityTemperature1); int cityId2 = dis.readInt(); System.out.println(“Id: ” + cityId2); String cityName2 = dis.readUTF(); System.out.println(“Name: ” + cityName2); int cityPopulation2 = dis.readInt(); System.out.println(“Population: ” + cityPopulation2); float cityTemperature2 = dis.readFloat(); System.out.println(“Temperature: ” + cityTemperature2); dis.close(); } }

6- Dẫy luồng đầu vào nhị phân – SequenceInputStream

Thông thường bạn đã quen thuộc với việc đọc một file nào đó và thu được một luồng đầu vào .Nhưng trong thực tế đôi khi bạn cần đọc từ nhiều file và lấy các dữ liệu đó ghép với nhau để ghi thành 1 file khác chẳng hạn .Vậy là ý tưởng ghép nhiều luồng đầu vào với nhau để thành một luồng lớn hơn nối đuôi nhau . Chúng ta đang nói đến class java.io.SequenceInputStream. Khái niệm này không có tương ứng cho luồng đầu ra …

public SequenceInputStream(InputStream s1,InputStream s2) InputStream is1=new FileInputStream(“File1.txt”); InputStream is2=new FileInputStream(“File2.txt”); SequenceInputStream sis=new SequenceInputStream(is1,is2);

public SequenceInputStream(InputStream s1,InputStream s2) InputStream is1=new FileInputStream(“File1.txt”); InputStream is2=new FileInputStream(“File2.txt”); SequenceInputStream sis=new SequenceInputStream(is1,is2);

Đặt ra một tình huống bạn có 2 luồng một luồng đầu vào và một luồng đầu ra …Chẳng hạn luồng đầu vào dữ liệu A đọc một file , lấy thông tin từ luồng này ghi vào luồng dữ liệu B đầu ra là một file khác .. Hai luồng A và B trong tình huống này là tách riêng nhau… Vì vậy trong ứng dụng bạn phải có 3 thao tác:

Tạo luồng dữ liệu đọc A

Tạo luồng ghi dữ liệu B

Đọc từ A ghi vào B …

Hai thao tác đầu phải có, nhưng bạn muốn bỏ đi thao tác thứ 3 … nghĩa là có một cái gì đó liên hệ ngầm với nhau giữa 2 luồng (vào-ra) ,để sao cho những byte xuất hiện trên luồng đầu đọc A lập tức được ghi tự động vào B…. Đó được gọi là liên hệ đường ngầm giữa 2 luồng vào và ra ..

package org.o7planning.tutorial.javaio.pipestream; import java.io.IOException; import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; public class PipeStreamExample1 { private InputStream pipedInputStream; public static void main(String[] args) throws IOException, InterruptedException { new PipeStreamExample1().test(); } private void test() throws IOException, InterruptedException { PipedOutputStream pipedOutputStream = new PipedOutputStream(); pipedInputStream = new PipedInputStream(pipedOutputStream); new ThreadRead().start(); char[] chs = new char[] { ‘a’, ‘a’, ‘b’, ‘c’ , ‘e’ }; for (char ch : chs) { pipedOutputStream.write(ch); Thread.sleep(1000); } pipedOutputStream.close(); } class ThreadRead extends Thread { @Override public void run() { try { int data = 0; while ((data = pipedInputStream.read()) != -1) { System.out.println((char) data); } } catch (Exception e) { e.printStackTrace(); } finally { closeQuietly(pipedInputStream); } } } private void closeQuietly(InputStream is) { if (is != null) { try { is.close(); } catch (IOException e) { } } } } public PrintStream(OutputStream out) public PrintStream(OutputStream out,boolean autoFlush) public PrintStream(String fileName) public void println(String s) public void print(char ch) public void print(Object obj) public void print(long n) public PrintStream append(java.lang.CharSequence csq) .

package org.o7planning.tutorial.javaio.pipestream; import java.io.IOException; import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; public class PipeStreamExample1 { private InputStream pipedInputStream; public static void main(String[] args) throws IOException, InterruptedException { new PipeStreamExample1().test(); } private void test() throws IOException, InterruptedException { PipedOutputStream pipedOutputStream = new PipedOutputStream(); pipedInputStream = new PipedInputStream(pipedOutputStream); new ThreadRead().start(); char[] chs = new char[] { ‘a’, ‘a’, ‘b’, ‘c’ , ‘e’ }; for (char ch : chs) { pipedOutputStream.write(ch); Thread.sleep(1000); } pipedOutputStream.close(); } class ThreadRead extends Thread { @Override public void run() { try { int data = 0; while ((data = pipedInputStream.read()) != -1) { System.out.println((char) data); } } catch (Exception e) { e.printStackTrace(); } finally { closeQuietly(pipedInputStream); } } } private void closeQuietly(InputStream is) { if (is != null) { try { is.close(); } catch (IOException e) { } } } } public PrintStream(OutputStream out) public PrintStream(OutputStream out,boolean autoFlush) public PrintStream(String fileName) public void println(String s) public void print(char ch) public void print(Object obj) public void print(long n) public PrintStream append(java.lang.CharSequence csq) .

Bạn đã quen biết với bắt ngoại lệ Exception thông qua khối try, catch.

try { int i=10/0; } catch(Exception e) { System.out.println(“Error on try…”+e.getMessage()); e.printStackTrace(); }

try { int i=10/0; } catch(Exception e) { System.out.println(“Error on try…”+e.getMessage()); e.printStackTrace(); }

Đây là ‘Stack Trace’ bạn thường thấy khi có lỗi gì đó.

Ví dụ sau đây lấy ra “Stack Trace”

package org.o7planning.tutorial.javaio.printstream; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class GetStackTraceString { private static String getStackTraceString(Exception e) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(baos); e.printStackTrace(printStream); printStream.close(); byte[] bytes = baos.toByteArray(); String s = new String(bytes); return s; } public static void main(String[] args) { try { int i = 10 / 0; } catch (Exception e) { System.out.println(“Error on try…” + e.getMessage()); String s = getStackTraceString(e); System.out.println(“Stack Trace String ” + s); } } } PrintStream os = System.out; e.printStackTrace(os); e.printStackTrace();

package org.o7planning.tutorial.javaio.printstream; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class GetStackTraceString { private static String getStackTraceString(Exception e) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(baos); e.printStackTrace(printStream); printStream.close(); byte[] bytes = baos.toByteArray(); String s = new String(bytes); return s; } public static void main(String[] args) { try { int i = 10 / 0; } catch (Exception e) { System.out.println(“Error on try…” + e.getMessage()); String s = getStackTraceString(e); System.out.println(“Stack Trace String ” + s); } } } PrintStream os = System.out; e.printStackTrace(os); e.printStackTrace();

Cập nhật thông tin chi tiết về Cách Tạo, Sử Dụng Và Tuỳ Biến Một Button Trong Java Swing / 2023 trên website Rafs.edu.vn. Hy vọng nội dung bài viết sẽ đáp ứng được nhu cầu của bạn, chúng tôi sẽ thường xuyên cập nhật mới nội dung để bạn nhận được thông tin nhanh chóng và chính xác nhất. Chúc bạn một ngày tốt lành!