code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
package jsqlite;
/**
* String encoder/decoder for SQLite.
*
* This module was kindly donated by Eric van der Maarel of Nedap N.V.
*
* This encoder was implemented based on an original idea from an anonymous
* author in the source code of the SQLite distribution.
* I feel obliged to provide a quote from the original C-source code:
*
* "The author disclaims copyright to this source code. In place of
* a legal notice, here is a blessing:
*
* May you do good and not evil.
* May you find forgiveness for yourself and forgive others.
* May you share freely, never taking more than you give."
*
*/
public class StringEncoder {
/**
* Encodes the given byte array into a string that can be used by
* the SQLite database. The database cannot handle null (0x00) and
* the character '\'' (0x27). The encoding consists of escaping
* these characters with a reserved character (0x01). The escaping
* is applied after determining and applying a shift that minimizes
* the number of escapes required.
* With this encoding the data of original size n is increased to a
* maximum of 1+(n*257)/254.
* For sufficiently large n the overhead is thus less than 1.2%.
* @param a the byte array to be encoded. A null reference is handled as
* an empty array.
* @return the encoded bytes as a string. When an empty array is
* provided a string of length 1 is returned, the value of
* which is bogus.
* When decoded with this class' <code>decode</code> method
* a string of size 1 will return an empty byte array.
*/
public static String encode(byte[] a) {
// check input
if (a == null || a.length == 0) {
// bogus shift, no data
return "x";
}
// determine count
int[] cnt = new int[256];
for (int i = 0 ; i < a.length; i++) {
cnt[a[i] & 0xff]++;
}
// determine shift for minimum number of escapes
int shift = 1;
int nEscapes = a.length;
for (int i = 1; i < 256; i++) {
if (i == '\'') {
continue;
}
int sum = cnt[i] + cnt[(i + 1) & 0xff] + cnt[(i + '\'') & 0xff];
if (sum < nEscapes) {
nEscapes = sum;
shift = i;
if (nEscapes == 0) {
// cannot become smaller
break;
}
}
}
// construct encoded output
int outLen = a.length + nEscapes + 1;
StringBuffer out = new StringBuffer(outLen);
out.append((char)shift);
for (int i = 0; i < a.length; i++) {
// apply shift
char c = (char)((a[i] - shift)&0xff);
// insert escapes
if (c == 0) { // forbidden
out.append((char)1);
out.append((char)1);
} else if (c == 1) { // escape character
out.append((char)1);
out.append((char)2);
} else if (c == '\'') { // forbidden
out.append((char)1);
out.append((char)3);
} else {
out.append(c);
}
}
return out.toString();
}
/**
* Decodes the given string that is assumed to be a valid encoding
* of a byte array. Typically the given string is generated by
* this class' <code>encode</code> method.
* @param s the given string encoding.
* @return the byte array obtained from the decoding.
* @throws IllegalArgumentException when the string given is not
* a valid encoded string for this encoder.
*/
public static byte[] decode(String s) {
char[] a = s.toCharArray();
if (a.length > 2 && a[0] == 'X' &&
a[1] == '\'' && a[a.length-1] == '\'') {
// SQLite3 BLOB syntax
byte[] result = new byte[(a.length-3)/2];
for (int i = 2, k = 0; i < a.length - 1; i += 2, k++) {
byte tmp;
switch (a[i]) {
case '0': tmp = 0; break;
case '1': tmp = 1; break;
case '2': tmp = 2; break;
case '3': tmp = 3; break;
case '4': tmp = 4; break;
case '5': tmp = 5; break;
case '6': tmp = 6; break;
case '7': tmp = 7; break;
case '8': tmp = 8; break;
case '9': tmp = 9; break;
case 'A':
case 'a': tmp = 10; break;
case 'B':
case 'b': tmp = 11; break;
case 'C':
case 'c': tmp = 12; break;
case 'D':
case 'd': tmp = 13; break;
case 'E':
case 'e': tmp = 14; break;
case 'F':
case 'f': tmp = 15; break;
default: tmp = 0; break;
}
result[k] = (byte) (tmp << 4);
switch (a[i+1]) {
case '0': tmp = 0; break;
case '1': tmp = 1; break;
case '2': tmp = 2; break;
case '3': tmp = 3; break;
case '4': tmp = 4; break;
case '5': tmp = 5; break;
case '6': tmp = 6; break;
case '7': tmp = 7; break;
case '8': tmp = 8; break;
case '9': tmp = 9; break;
case 'A':
case 'a': tmp = 10; break;
case 'B':
case 'b': tmp = 11; break;
case 'C':
case 'c': tmp = 12; break;
case 'D':
case 'd': tmp = 13; break;
case 'E':
case 'e': tmp = 14; break;
case 'F':
case 'f': tmp = 15; break;
default: tmp = 0; break;
}
result[k] |= tmp;
}
return result;
}
// first element is the shift
byte[] result = new byte[a.length-1];
int i = 0;
int shift = s.charAt(i++);
int j = 0;
while (i < s.length()) {
int c;
if ((c = s.charAt(i++)) == 1) { // escape character found
if ((c = s.charAt(i++)) == 1) {
c = 0;
} else if (c == 2) {
c = 1;
} else if (c == 3) {
c = '\'';
} else {
throw new IllegalArgumentException(
"invalid string passed to decoder: " + j);
}
}
// do shift
result[j++] = (byte)((c + shift) & 0xff);
}
int outLen = j;
// provide array of correct length
if (result.length != outLen) {
result = byteCopy(result, 0, outLen, new byte[outLen]);
}
return result;
}
/**
* Copies count elements from source, starting at element with
* index offset, to the given target.
* @param source the source.
* @param offset the offset.
* @param count the number of elements to be copied.
* @param target the target to be returned.
* @return the target being copied to.
*/
private static byte[] byteCopy(byte[] source, int offset,
int count, byte[] target) {
for (int i = offset, j = 0; i < offset + count; i++, j++) {
target[j] = source[i];
}
return target;
}
static final char[] xdigits = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
/**
* Encodes the given byte array into SQLite3 blob notation, ie X'..'
* @param a the byte array to be encoded. A null reference is handled as
* an empty array.
* @return the encoded bytes as a string.
*/
public static String encodeX(byte[] a) {
// check input
if (a == null || a.length == 0) {
return "X''";
}
char[] out = new char[a.length * 2 + 3];
int i = 2;
for (int j = 0; j < a.length; j++) {
out[i++] = xdigits[(a[j] >> 4) & 0x0F];
out[i++] = xdigits[a[j] & 0x0F];
}
out[0] = 'X';
out[1] = '\'';
out[i] = '\'';
return new String(out);
}
}
| Java |
package jsqlite;
/**
* Callback interface for SQLite's query results.
* <BR><BR>
* Example:<BR>
*
* <PRE>
* class TableFmt implements SQLite.Callback {
* public void columns(String cols[]) {
* System.out.println("<TH><TR>");
* for (int i = 0; i < cols.length; i++) {
* System.out.println("<TD>" + cols[i] + "</TD>");
* }
* System.out.println("</TR></TH>");
* }
* public boolean newrow(String cols[]) {
* System.out.println("<TR>");
* for (int i = 0; i < cols.length; i++) {
* System.out.println("<TD>" + cols[i] + "</TD>");
* }
* System.out.println("</TR>");
* return false;
* }
* }
* ...
* SQLite.Database db = new SQLite.Database();
* db.open("db", 0);
* System.out.println("<TABLE>");
* db.exec("select * from TEST", new TableFmt());
* System.out.println("</TABLE>");
* ...
* </PRE>
*/
public interface Callback {
/**
* Reports column names of the query result.
* This method is invoked first (and once) when
* the SQLite engine returns the result set.<BR><BR>
*
* @param coldata string array holding the column names
*/
public void columns(String coldata[]);
/**
* Reports type names of the columns of the query result.
* This is available from SQLite 2.6.0 on and needs
* the PRAGMA show_datatypes to be turned on.<BR><BR>
*
* @param types string array holding column types
*/
public void types(String types[]);
/**
* Reports row data of the query result.
* This method is invoked for each row of the
* result set. If true is returned the running
* SQLite query is aborted.<BR><BR>
*
* @param rowdata string array holding the column values of the row
*/
public boolean newrow(String rowdata[]);
}
| Java |
package jsqlite;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Internal class implementing java.io.InputStream on
* SQLite 3.4.0 incremental blob I/O interface.
*/
class BlobR extends InputStream {
/**
* Blob instance
*/
private Blob blob;
/**
* Read position, file pointer.
*/
private int pos;
/**
* Contruct InputStream from blob instance.
*/
BlobR(Blob blob) {
this.blob = blob;
this.pos = 0;
}
/**
* Return number of available bytes for reading.
* @return available input bytes
*/
public int available() throws IOException {
int ret = blob.size - pos;
return (ret < 0) ? 0 : ret;
}
/**
* Mark method; dummy to satisfy InputStream class.
*/
public void mark(int limit) {
}
/**
* Reset method; dummy to satisfy InputStream class.
*/
public void reset() throws IOException {
}
/**
* Mark support; not for this class.
* @return always false
*/
public boolean markSupported() {
return false;
}
/**
* Close this blob InputStream.
*/
public void close() throws IOException {
blob.close();
blob = null;
pos = 0;
}
/**
* Skip over blob data.
*/
public long skip(long n) throws IOException {
long ret = pos + n;
if (ret < 0) {
ret = 0;
pos = 0;
} else if (ret > blob.size) {
ret = blob.size;
pos = blob.size;
} else {
pos = (int) ret;
}
return ret;
}
/**
* Read single byte from blob.
* @return byte read
*/
public int read() throws IOException {
byte b[] = new byte[1];
int n = blob.read(b, 0, pos, b.length);
if (n > 0) {
pos += n;
return b[0];
}
return -1;
}
/**
* Read byte array from blob.
* @param b byte array to be filled
* @return number of bytes read
*/
public int read(byte b[]) throws IOException {
int n = blob.read(b, 0, pos, b.length);
if (n > 0) {
pos += n;
return n;
}
return -1;
}
/**
* Read slice of byte array from blob.
* @param b byte array to be filled
* @param off offset into byte array
* @param len length to be read
* @return number of bytes read
*/
public int read(byte b[], int off, int len) throws IOException {
if (off + len > b.length) {
len = b.length - off;
}
if (len < 0) {
return -1;
}
if (len == 0) {
return 0;
}
int n = blob.read(b, off, pos, len);
if (n > 0) {
pos += n;
return n;
}
return -1;
}
}
/**
* Internal class implementing java.io.OutputStream on
* SQLite 3.4.0 incremental blob I/O interface.
*/
class BlobW extends OutputStream {
/**
* Blob instance
*/
private Blob blob;
/**
* Read position, file pointer.
*/
private int pos;
/**
* Contruct OutputStream from blob instance.
*/
BlobW(Blob blob) {
this.blob = blob;
this.pos = 0;
}
/**
* Flush blob; dummy to satisfy OutputStream class.
*/
public void flush() throws IOException {
}
/**
* Close this blob OutputStream.
*/
public void close() throws IOException {
blob.close();
blob = null;
pos = 0;
}
/**
* Write blob data.
* @param v byte to be written at current position.
*/
public void write(int v) throws IOException {
byte b[] = new byte[1];
b[0] = (byte) v;
pos += blob.write(b, 0, pos, 1);
}
/**
* Write blob data.
* @param b byte array to be written at current position.
*/
public void write(byte[] b) throws IOException {
if (b != null && b.length > 0) {
pos += blob.write(b, 0, pos, b.length);
}
}
/**
* Write blob data.
* @param b byte array to be written.
* @param off offset within byte array
* @param len length of data to be written
*/
public void write(byte[] b, int off, int len) throws IOException {
if (b != null) {
if (off + len > b.length) {
len = b.length - off;
}
if (len <= 0) {
return;
}
pos += blob.write(b, off, pos, len);
}
}
}
/**
* Class to represent SQLite3 3.4.0 incremental blob I/O interface.
*
* Note, that all native methods of this class are
* not synchronized, i.e. it is up to the caller
* to ensure that only one thread is in these
* methods at any one time.
*/
public class Blob {
/**
* Internal handle for the SQLite3 blob.
*/
private long handle = 0;
/**
* Cached size of blob, setup right after blob
* has been opened.
*/
protected int size = 0;
/**
* Return InputStream for this blob
* @return InputStream
*/
public InputStream getInputStream() {
return new BlobR(this);
}
/**
* Return OutputStream for this blob
* @return OutputStream
*/
public OutputStream getOutputStream() {
return new BlobW(this);
}
/**
* Close blob.
*/
public native void close();
/**
* Internal blob write method.
* @param b byte array to be written
* @param off offset into byte array
* @param pos offset into blob
* @param len length to be written
* @return number of bytes written to blob
*/
native int write(byte[] b, int off, int pos, int len) throws IOException;
/**
* Internal blob read method.
* @param b byte array to be written
* @param off offset into byte array
* @param pos offset into blob
* @param len length to be written
* @return number of bytes written to blob
*/
native int read(byte[] b, int off, int pos, int len) throws IOException;
/**
* Destructor for object.
*/
protected native void finalize();
/**
* Internal native initializer.
*/
private static native void internal_init();
static {
internal_init();
}
}
| Java |
package jsqlite;
/**
* Context for execution of SQLite's user defined functions.
* A reference to an instance of this class is passed to
* user defined functions.
*/
public class FunctionContext {
/**
* Internal handle for the native SQLite API.
*/
private long handle = 0;
/**
* Set function result from string.
*
* @param r result string
*/
public native void set_result(String r);
/**
* Set function result from integer.
*
* @param r result integer
*/
public native void set_result(int r);
/**
* Set function result from double.
*
* @param r result double
*/
public native void set_result(double r);
/**
* Set function result from error message.
*
* @param r result string (error message)
*/
public native void set_error(String r);
/**
* Set function result from byte array.
* Only provided by SQLite3 databases.
*
* @param r result byte array
*/
public native void set_result(byte[] r);
/**
* Set function result as empty blob given size.
* Only provided by SQLite3 databases.
*
* @param n size for empty blob
*/
public native void set_result_zeroblob(int n);
/**
* Retrieve number of rows for aggregate function.
*/
public native int count();
/**
* Internal native initializer.
*/
private static native void internal_init();
static {
internal_init();
}
}
| Java |
package com.spatialite.test.utilities;
import java.io.File;
import java.io.IOException;
import com.spatialite.utilities.ActivityHelper;
import com.spatialite.utilities.AssetHelper;
import jsqlite.Exception;
import android.test.AndroidTestCase;
public abstract class DatabaseTestCase extends AndroidTestCase {
// Specifies whether to place the temporary database in the internal (phone)
// or external (SD card) storage.
private static final boolean USE_EXTERNAL_STORAGE = true;
protected jsqlite.Database db = null;
protected File dbPath = null;
public void openExistingDatabase(String dbName) throws Exception,
IOException {
dbPath = getDatabaseName(dbName);
if (!dbPath.exists()) {
AssetHelper.CopyAsset(getContext(), dbPath.getParentFile(), dbName);
}
db = new jsqlite.Database();
db.open(dbPath.toString(), jsqlite.Constants.SQLITE_OPEN_READWRITE);
}
public void openNewDatabase(String dbName) throws Exception, IOException {
dbPath = getDatabaseName(dbName);
db = new jsqlite.Database();
db.open(dbPath.toString(), jsqlite.Constants.SQLITE_OPEN_READWRITE
| jsqlite.Constants.SQLITE_OPEN_CREATE);
}
private File getDatabaseName(String dbName) {
return new File(ActivityHelper.getPath(getContext(),
USE_EXTERNAL_STORAGE), dbName);
}
public void deleteDatabase() {
if (dbPath != null) {
dbPath.delete();
dbPath = null;
}
}
public void closeDatabase() throws Exception {
if (db == null) {
return;
}
db.close();
db = null;
}
}
| Java |
package com.spatialite.test.spatialite;
import com.spatialite.test.utilities.DatabaseTestCase;
import jsqlite.Callback;
import jsqlite.Stmt;
import android.util.Log;
public class RTreeTest2 extends DatabaseTestCase {
private static final String TAG = "RTreeTest2";
@Override
protected void setUp() throws Exception {
super.setUp();
openExistingDatabase("test-2.3.sqlite");
}
@Override
protected void tearDown() throws Exception {
closeDatabase();
deleteDatabase();
super.tearDown();
}
public void testIndex() throws Exception {
db.exec("select DisableSpatialIndex('HighWays','Geometry')",
new Callback() {
public void types(String[] types) {
}
public boolean newrow(String[] rowdata) {
return false;
}
public void columns(String[] coldata) {
}
});
// Create index
Stmt stmt1 = db
.prepare("select createspatialindex('HighWays','Geometry')");
if (stmt1.step()) {
assertEquals(1, stmt1.column_int(0));
} else {
fail("couldn't create spatial index");
}
stmt1.close();
// Check index
Stmt stmt2 = db.prepare("select CheckSpatialIndex()");
if (stmt2.step()) {
assertEquals(1, stmt2.column_int(0));
} else {
fail("index check failed");
}
stmt2.close();
// MATCH - prepare query
Stmt stmt3 = db
.prepare("SELECT PK_UID FROM HighWays WHERE ROWID IN ( select pkid from idx_HighWays_Geometry where pkid match RTreeDistWithin(675182.242021, 4679818.170099,.000001))");
if (stmt3.step()) {
assertEquals(661, stmt3.column_int(0));
} else {
fail("query failed");
}
stmt3.close();
// MATCH - exec
db.exec("SELECT PK_UID FROM HighWays WHERE ROWID IN ( select pkid from idx_HighWays_Geometry where pkid match RTreeDistWithin(675182.242021, 4679818.170099,.000001))",
new Callback() {
public void types(String[] types) {
}
public boolean newrow(String[] rowdata) {
assertEquals(661, Integer.parseInt(rowdata[0]));
return false;
}
public void columns(String[] coldata) {
}
});
// using raw index database - prepare
Stmt stmt4 = db
.prepare("SELECT PK_UID FROM HighWays WHERE ROWID IN (SELECT pkid FROM idx_HighWays_Geometry WHERE xmin<675182.242022 AND xmax>675182.242020 AND ymin<4679818.170100 AND ymax>4679818.170098)");
if (stmt4.step()) {
assertEquals(661, stmt4.column_int(0));
} else {
fail("query failed");
}
stmt4.close();
// using raw index database - exec
String sql = "SELECT pkid FROM idx_HighWays_Geometry WHERE xmin<675182.242022 AND xmax>675182.242020 AND ymin<4679818.170100 AND ymax>4679818.170098";
Log.i(TAG, sql);
db.exec(sql, new Callback() {
public void types(String[] types) {
}
public boolean newrow(String[] rowdata) {
assertEquals(661, Integer.parseInt(rowdata[0]));
return false;
}
public void columns(String[] coldata) {
}
});
// disable index
Stmt stmt9 = db
.prepare("select DisableSpatialIndex('HighWays','Geometry')");
if (stmt9.step()) {
assertEquals(1, stmt9.column_int(0));
} else {
fail("couldn't disable spatial index");
}
stmt9.close();
}
}
| Java |
package NetworkManager;
import java.io.*;
import java.net.*;
import java.util.Observable;
import MiddleLayer.OtherClass.*;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MultiThreadChatServer implements Observer{
MyObservable _observable = new MyObservable();
// Declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
static private int iNumOfThread = 4;// This chat server can accept up to 4 clients' connections
private int iNumOfClient = 0;//Số lượng client connect vào server
private boolean isAcceptConnect = true;
static clientThread threadPools[] = new clientThread[iNumOfThread];
//Chứa dữ liệu nhận được từ client: Đã được chuyển từ chuỗi về kiểu cấu trúc
//Đẩy lên lớp trên để xử lý
public CommandStruct clientCMDReceiver[] = new CommandStruct[iNumOfThread];
//Khung chat
public CommandStruct clientChatReceiver[] = new CommandStruct[iNumOfThread];
public void initServer(int port_number)
{
// Initialization section:
// Try to open a server socket on port port_number (default 2222)
// Note that we can'threadPools choose a port less than 1023 if we are not
// privileged users (root)
try {
serverSocket = new ServerSocket(port_number, iNumOfThread);
}
catch (IOException e)
{System.out.println(e);}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams for this socket will be created in
// client's thread since every client is served by the server in
// an individual thread
if(serverSocket.isBound())
{
System.out.println("Server init at port number " + port_number + ".");
while(isAcceptConnect()){
try {
clientSocket = serverSocket.accept();
for(int i = 0; i < iNumOfThread; i++){
if(threadPools[i] == null){
threadPools[i] = new clientThread(clientSocket,threadPools, iNumOfThread, clientCMDReceiver, clientChatReceiver, i);
threadPools[i].addObserver(this);
iNumOfClient++;
threadPools[i].start();
break;
}
}
}
catch (IOException e) {
System.out.println(e);}
}
}
}
public MyObservable observable() {
return _observable;
}
//Có dữ liệu đến, đẩy dữ liệu lên cho lớp bên trên xử lý
public void update(Observable o, Object arg) {
notifyNewMessageFromClient(arg);
}
/*
* Báo cho bên trên biết là có dữ liệu tới từ thread số mấy
* Bên trên sẽ lấy dữ liệu từ trong clientCMDReceiver[]
* arg chứa giá trị số nguyên cho biết là thread số mấy có dữ liệu tới
*/
public void notifyNewMessageFromClient(Object arg)
{
this._observable.setChanged(); // set changed flag
this._observable.notifyObservers(arg); // do notification
}
/**
* Gửi dữ liệu đến thread số mấy, nhớ kiểm tra kĩ trước khi gọi hàm này
* Dữ liệu này đã có thêm mã lệnh ở phía trước
*/
public void sendDataToThreadNumber(int iOrderOfThread, CommandStruct cmdStruct){
if (threadPools[iOrderOfThread] != null){
threadPools[iOrderOfThread].os.println(cmdStruct.toString());
threadPools[iOrderOfThread].os.flush();
}
}
/**
* Gửi dữ liệu text đến các thread khác, thường là chỉ có dữ liệu chat
*/
public void sendDataToAllThread(CommandStruct cmdStruct)
{
for(int i = 0; i < iNumOfThread; i++){
if (threadPools[i] != null)
{
threadPools[i].os.println(cmdStruct.toString());
threadPools[i].os.flush();
}
}
}
/**
* Gửi dữ liệu text đến các thread khác, thường là gửi dữ liệu chat
*/
public void sendDataToOtherThread(CommandStruct cmdStruct, int iClientWillSend) {
for(int i = 0; i < iNumOfThread; i++)
if (threadPools[i] != null && i != iClientWillSend)
{
threadPools[i].os.println(cmdStruct.toString());
threadPools[i].os.flush();
}
}
/**
* Ngắt kết nối với tất cả client
*/
public void disconnectClients()
{
for(int i = 0; i < iNumOfThread; i++)
if (threadPools[i] != null)
{
//Gửi lệnh ngắt tới server
sendDataToThreadNumber(i,
new CommandStruct(
CommandStruct.MessageType.Quit,
""));
threadPools[i].closed = true;
}
}
public synchronized void addObserver(Observer o)
{
this._observable.addObserver(o);
}
/**
* @return the isAcceptConnect
*/
public boolean isAcceptConnect() {
return isAcceptConnect;
}
/**
* Không chấp nhận kết nối mới nữa
*/
public void setNotAcceptConnect() {
this.isAcceptConnect = false;
}
/**
* @return the iNumOfClient
*/
public int getNumOfClient() {
return iNumOfClient;
}
// /**
// * Chỉ gọi đến hàm này khi có dữ liệu cần gửi đi
// * Dữ liệu tự động chuyển đổi về kiểu string
// */
//
// public void sendMesssage(CommandStruct cmdStruct, int iOrderOfClient)
// {
//
// //Nếu là thông điệp chat thì gửi đi tới tất cả
// if(cmdStruct.isChatMessage() && iOrderOfClient != -1)
// sendDataToOtherThread(cmdStruct.toString(), iOrderOfClient);
//
// //Nếu là lệnh thì gửi riêng đến client
// if(cmdStruct.isCommandMessage())
// sendDataToThreadNumber(iOrderOfClient, cmdStruct.toString());
//
// }
}
/**
* This client thread opens the input and the output streams for a particular client,
* ask the client's name, informs all the clients currently connected to the
* server about the fact that a new client has joined the chat room,
* and as long as it receive data, echos that data back to all other clients.
* When the client leaves the chat room this thread informs also all the
* clients about that and terminates.
*/
class clientThread extends Thread{
int iTimeToSleep = 50;//milis
public boolean closed = false;
MyObservable _observable = new MyObservable();
DataInputStream is = null;
PrintStream os = null;
Socket clientSocket = null;
clientThread threadPools[];
private int iOrderOfThread = -1;//Cho biết thread này là thread số mấy
private int iNumOfThread = 4;// This chat server can accept up to 4 clients' connections
CommandStruct clientCMDReceiver[] = null; //Cho biết dữ liệu sẽ từ client nào gửi tới
CommandStruct clientChatReceiver[] = new CommandStruct[iNumOfThread];
public String strTextReceived = null;
public clientThread(Socket clientSocket, clientThread[] t, int iNumOfThread,
CommandStruct clientCMDReceiver[], CommandStruct clientChatReceiver[], int iOrderOfThread){
this.clientSocket = clientSocket;
this.threadPools = t;
this.iNumOfThread = iNumOfThread;
this.iOrderOfThread = iOrderOfThread;
this.clientCMDReceiver = clientCMDReceiver;
this.clientChatReceiver = clientChatReceiver;
}
@Override
public void run()
{
try{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
//Mặc định theo kịch bản, connect xong là gửi ngay tên liền
//Gửi thông điệp lên trên cho biết là đã có kết nối tới người chơi
//Thông tin người chơi kết nối tới nằm trong strTextReceived
notifyRawTextHasArrived(is.readLine());
while (!this.closed) {
if((strTextReceived = is.readLine()) != null)
{
//Đọc dữ liệu từ bên dưới truyền lên, biết là của client nào.
notifyRawTextHasArrived(strTextReceived);
//Gửi dữ liệu cho tất cả các client còn lại...
//hàm sendDataToThreadNumber sẽ gửi dữ liệu acb đến thread số 1 hay client số 1
//Có tối đa 4 client: 0, 1, 2, 3.
//Chỉ cần kiểm tra ở đây thì sẽ biết dữ liệu mình sắp gửi cho lai
//sendDataToThreadNumber(1, "acb");
System.out.println("Dữ liệu nhận được từ client số " + iOrderOfThread + ": \"" + strTextReceived + "\"");
}
try {
this.sleep(this.iTimeToSleep);
} catch (InterruptedException ex) {
Logger.getLogger(clientThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Clean up:
// Set to null the current thread variable such that other client could
// be accepted by the server
for(int i = 0; i < iNumOfThread; i++)
if (threadPools[i] == this)
threadPools[i] = null;
// close the output stream
// close the input stream
// close the socket
is.close();
os.close();
clientSocket.close();
}
catch(IOException e){};
}
/*
* Thông báo cho biết dữ liệu đã được gửi đến
* Chuyển đổi thành CommandStruct để gửi lên bên trên
*/
public void notifyRawTextHasArrived(String rawText) {
int iMessageType = 0;//sử dụng trick ở đây, nếu là chat thì dữ liệu bên trên nhận được
//là iOrderOfThread * 10 + 0; còn nếu là dữ liệu cmd thì là * 10 + 1
if(this.clientCMDReceiver[this.iOrderOfThread] == null)
{
if( !CommandStruct.isChatMessage(rawText) )
{
this.clientCMDReceiver[this.iOrderOfThread] = new CommandStruct(rawText);
iMessageType = 1;
}
else
{
this.clientChatReceiver[this.iOrderOfThread] = new CommandStruct(rawText);
iMessageType = 0;
}
}
else
{
if( !CommandStruct.isChatMessage(rawText) )
{
if(this.clientCMDReceiver[this.iOrderOfThread] != null)
this.clientCMDReceiver[this.iOrderOfThread].changeCommand(rawText);
else
this.clientCMDReceiver[this.iOrderOfThread] = new CommandStruct(rawText);
iMessageType = 1;
}
else
{
if(this.clientChatReceiver[this.iOrderOfThread] != null)
this.clientChatReceiver[this.iOrderOfThread].changeCommand(rawText);
else
this.clientChatReceiver[this.iOrderOfThread] = new CommandStruct(rawText);
iMessageType = 0;
}
}
iMessageType = (this.iOrderOfThread + 1) * 10 + iMessageType;//trick để có thể liên lạc được với nhau
this._observable.setChanged(); // set changed flag
this._observable.notifyObservers(iMessageType); // do notification
}
public synchronized void addObserver(Observer o)
{
this._observable.addObserver(o);
}
} | Java |
package NetworkManager;
import MiddleLayer.OtherClass.CommandStruct;
import MiddleLayer.OtherClass.MyObservable;
import java.io.*;
import java.net.*;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MultiThreadChatClient extends Thread implements Runnable{
int iTimeToSleep = 50;//milis
MyObservable _observable = new MyObservable();
// Declaration section
// clientClient: the client socket
// os: the output stream
// is: the input stream
Socket clientSocket = null;
PrintStream os = null;
BufferedReader is = null;
BufferedReader inputLine = null;
public boolean closed = false;
public MultiThreadChatClient()
{
this.clientSocket = null;
this.os = null;
this.is = null;
}
public MultiThreadChatClient(Socket clientSocket, PrintStream os, BufferedReader is, MyObservable _observable)
{
this.clientSocket = clientSocket;
this.os = os;
this.is = is;
this._observable = _observable;
}
public void connectToServer(String hostName, int port_number)
{
// Initialization section:
// Try to open a socket on a given host and port
// Try to open input and output streams
try {
this.clientSocket = new Socket(hostName, port_number);
this.inputLine = new BufferedReader(new InputStreamReader(System.in));
this.os = new PrintStream(clientSocket.getOutputStream());
this.is = new BufferedReader (new InputStreamReader( clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
this.closed = true;
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host " + hostName);
this.closed = true;
}
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on port port_number
if (clientSocket.isConnected() && os != null && is != null) {
// Create a thread to read from the server
new Thread(new MultiThreadChatClient(this.clientSocket, this.os, this.is, this._observable)).start();
}
}
public void run() {
String responseLine;
// Keep on reading from the socket till we receive the "Bye" from the server,
// once we received that then we want to break.
try{
while ((responseLine = is.readLine()) != null) {
responseLine = is.readLine();
//Lấy dữ liệu raw text, thông báo cho phía trên biết là có dữ liệu tới
notifyRawTextHasArrived(responseLine);
//Kiểm tra xem có phải lệnh thoát hay không?
if(CommandStruct.isCommandQUIT(responseLine))
{
this.closed = true;
break;//thoát khỏi vòng lặp
}
System.out.println(responseLine);
try {
this.sleep(iTimeToSleep);
} catch (InterruptedException ex) {
Logger.getLogger(MultiThreadChatClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (IOException e) {
System.err.println("IOException: " + e);
}
if(closed == true)
{
if (clientSocket.isConnected() && os != null && is != null) {
try {
// Clean up:
// close the output stream
// close the input stream
// close the socket
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}
public MyObservable observable() {
return _observable;
}
/*
* Thông báo cho biết dữ liệu đã được gửi đến
* Chuyển đổi thành CommandStruct để gửi lên bên trên
*/
public void notifyRawTextHasArrived(String rawText) {
CommandStruct cmdStruct = new CommandStruct(rawText);
this._observable.setChanged(); // set changed flag
this._observable.notifyObservers(cmdStruct); // do notification
}
/*
* Chỉ gọi đến hàm này khi có dữ liệu cần gửi đi
* Dữ liệu tự động chuyển đổi về kiểu string
*/
public void sendMessage(CommandStruct cmdStruct) {
//Vẫn còn kết nối
if(!this.closed)
{
//Biến đổi dữ liệu để gửi đi
String sendData = cmdStruct.toString();
//Gửi dữ liệu đi
os.println(sendData);
os.flush();
}
}
public synchronized void addObserver(Observer o)
{
this._observable.addObserver(o);
}
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package heartgame;
import GUI.GameplayForm;
import MiddleLayer.ClientProcessing;
import MiddleLayer.OtherClass.CommandStruct.MessageType;
import MiddleLayer.ServerProcessing;
/**
*
* @author ThanhTri
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
TestClientServer server1 = new TestClientServer(true);
TestClientServer client1 = new TestClientServer(false);
TestClientServer client2 = new TestClientServer(false);
server1.start();
client1.start();
client2.start();
}
}
class TestClientServer extends Thread
{
ServerProcessing server = null;
ClientProcessing clientProcessing = null;
public TestClientServer(boolean bIsServer) {
if(bIsServer)
server = new ServerProcessing();
else
clientProcessing = new ClientProcessing();
}
@Override
public void run()
{
if(server != null)
{
server.initServer();
}
else
{
clientProcessing.initGame();
clientProcessing.sendMessageToServer(MessageType.Chat, "hello");
while(true)
{}
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MiddleLayer;
/**
*
* @author ThanhTri
* Kiễm tra luật và trạng thái bàn cờ trong game.
*/
public class GameRules {
private boolean bIsHeartBroken = false;//kiểm tra xem được đi quân Cơ chưa hay không?
private Card prevCardID = null;
private Card currCard = null;
/*
* Kiểm tra nước đi xem có thỏa luật chơi không
* Nếu người chơi được đi đầu trong lượt đi này
*/
public boolean isLeadMovingValid(int cardIDWillPlay)
{
boolean result = false;
//Nếu là bước đi đầu tiên: Hợp lệ khi chỉ là 2 chuồn
if(this.prevCardID == null)
{
//kiểm tra có phải là 2 chuồn không
if(Card.isTwoOfClubs(cardIDWillPlay))
{
result = true;
}
//Kiểm tra có phải là Q bích hay quân Cơ hay không: KHÔNG ĐƯỢC ĐI TRONG LẦN ĐẦU TIÊN
if(Card.isQueenOfSpades(cardIDWillPlay))
{
result = false;
}
if(Card.isHeartCard(cardIDWillPlay))
{
result = false;
}
}
else
{
//Nếu là quân Cơ, kiểm tra xem đã đi được chưa.
if(Card.isHeartCard(cardIDWillPlay))
{
if(this.isHeartBroken())
result = true;
else
result = false;
}
}
if(result == true)
{
if(this.prevCardID == null)
this.prevCardID = new Card(cardIDWillPlay);
else
this.prevCardID.setId(cardIDWillPlay);
}
return result;
}
/*
* Kiểm tra nước đi xem có thỏa luật chơi không
* Trường hợp người chơi không phải đi đầu mà chọn bài để ra
*/
public boolean isMovingValid(int cardIDWillPlay, int iCardIDWasPlayByOtherPlayer, Cards lstHoldCard)
{
boolean result = false;
//Kiểm tra xem có cùng loại không?
if (Card.isSameSuit(cardIDWillPlay, iCardIDWasPlayByOtherPlayer))
result = true;
else//Kiểm tra trường hợp coi còn bài cũng loại này trong các lá bài giữ trong tay không
{
//Còn quân bài cùng loại trong tay
if (lstHoldCard.stillHaveSameSuitCard(iCardIDWasPlayByOtherPlayer))
result = false;
else
{
//Trường hợp không còn, kiểm tra xem có đánh quân bài heart ko?
if(Card.isHeartCard(cardIDWillPlay))
this.bIsHeartBroken = true;//Nếu có, heart broken
result = true;
}
}
if(result == true)
this.prevCardID.setId(cardIDWillPlay);
return result;
}
/*
* trả về điểm số của người chơi
*/
public int getMarkForPlayer(Cards lstWinCard)
{
return lstWinCard.getScore();
}
/**
* @return the bIsHeartBroken
*/
public boolean isHeartBroken() {
return bIsHeartBroken;
}
/**
* @param bIsHeartBroken the bIsHeartBroken to set
*/
public void setHeartBroken() {
this.bIsHeartBroken = true;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MiddleLayer;
/**
*
* @author ThanhTri
*/
public class Card {
static String resources[] = {
"Images/Cards/2s.gif", //2 bích
"Images/Cards/2c.gif", //2 chuồn
"Images/Cards/2d.gif", //2 rô
"Images/Cards/2h.gif", //2 cơ
"Images/Cards/3s.gif",
"Images/Cards/3c.gif",
"Images/Cards/3d.gif",
"Images/Cards/3h.gif",
"Images/Cards/4s.gif",
"Images/Cards/4c.gif",
"Images/Cards/4d.gif",
"Images/Cards/4h.gif",
"Images/Cards/5s.gif",
"Images/Cards/5c.gif",
"Images/Cards/5d.gif",
"Images/Cards/5h.gif",
"Images/Cards/6s.gif",
"Images/Cards/6c.gif",
"Images/Cards/6d.gif",
"Images/Cards/6h.gif",
"Images/Cards/7s.gif",
"Images/Cards/7c.gif",
"Images/Cards/7d.gif",
"Images/Cards/7h.gif",
"Images/Cards/8s.gif",
"Images/Cards/8c.gif",
"Images/Cards/8d.gif",
"Images/Cards/8h.gif",
"Images/Cards/9s.gif",
"Images/Cards/9c.gif",
"Images/Cards/9d.gif",
"Images/Cards/9h.gif",
"Images/Cards/ts.gif",
"Images/Cards/tc.gif",
"Images/Cards/td.gif",
"Images/Cards/th.gif",
"Images/Cards/js.gif",
"Images/Cards/jc.gif",
"Images/Cards/jd.gif",
"Images/Cards/jh.gif",
"Images/Cards/qs.gif",
"Images/Cards/qc.gif",
"Images/Cards/qd.gif",
"Images/Cards/qh.gif",
"Images/Cards/ks.gif",
"Images/Cards/kc.gif",
"Images/Cards/kd.gif",
"Images/Cards/kh.gif",
"Images/Cards/as.gif", //Ace là quân có giá trị lớn nhất
"Images/Cards/ac.gif",
"Images/Cards/ad.gif",
"Images/Cards/ah.gif",
};
private int id = -1;
private int suit = -1;//Bích, chuồn, rô, cơ
private int type = -1;//2, 3, 4, .., Q, K, A
private boolean bIsUsed = false;
private String resourcePath = null;
/**
* Truyền vào id theo số thứ tự gốc
*/
Card(int id)
{
this.id = id;
this.suit = id % 4;
this.type = id / 4;
this.resourcePath = resources[id];
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
this.suit = id % 4;
this.type = id / 4;
this.resourcePath = resources[id];
}
/**
* @return the bIsUsed
*/
public boolean isbIsUsed() {
return bIsUsed;
}
/**
* @param bIsUsed the bIsUsed to set
*/
public void setbIsUsed() {
this.bIsUsed = true;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @return the suit
*/
public int getSuit() {
return suit;
}
/**
* @return the type
*/
public int getType() {
return type;
}
/**
* @return the resourcePath
*/
public String getResourcePath() {
return resourcePath;
}
//Trả về cho biết card kia có cùng loại (cơ, rô, chuồn, bích) với card này không
public boolean isSameSuit(int cardID)
{
if(cardID % 4 != this.suit)
return false;
return true;
}
static public boolean isSameSuit(int cardIDsrc, int cardIDdest)
{
if((cardIDsrc % 4) != (cardIDdest % 4))
return false;
return true;
}
//Trả về cho biết card kia có cùng type (Ace, 2, 3, ..., Q, K) với card này không
public boolean isSameType(int cardID)
{
if(cardID / 4 != this.type)
return false;
return true;
}
static public boolean isSameType(int cardIDsrc, int cardIDdest)
{
if((cardIDsrc / 4) != (cardIDdest / 4))
return false;
return true;
}
//Kiểm tra xem quân bài này có phải là quân Cơ hay không
static public boolean isHeartCard(int cardID)
{
if(cardID % 4 == 3)
return true;
return false;
}
//Kiểm tra xem quân bài này có phải là 2 chuồn hay không
static public boolean isTwoOfClubs(int cardID)
{
if(cardID % 4 == 1 && cardID / 4 == 0)
return true;
return false;
}
//Kiểm tra xem quân bài này có phải là 2 chuồn hay không
static public boolean isQueenOfSpades(int cardID)
{
if(cardID % 4 == 0 && cardID / 4 == 10)
return true;
return false;
}
//Kiểm tra xem quân bài này có phải là 2 chuồn hay không
static public boolean isTwoOfDiamonds(int cardID)
{
if(cardID % 4 == 0 && cardID / 4 == 2)
return true;
return false;
}
/**
* Chuyển đổi từ id cardGUI sang id của lớp card bên dưới
* @param iCardGUI_ID: ID của lớp cardGUI bên trên truyền xuống
*/
static public int convertCardGUI_IDToCard_ID(int iCardGUI_ID)
{
int iType = iCardGUI_ID % 13;
int iSuit = iCardGUI_ID / 13;
return iType * 4 + iSuit;
}
/**
* Chuyển đổi id của card này thành giống id của lớp CardGUI
*
* @param iCardID: ID của đối tượng thuộc lớp Card
* @return: ID tương ứng của đối tượng thuộc lớp CardGUI
*/
static public int convertToCardGUI_ID(int iCardID)
{
int iType = iCardID / 4;
int iSuit = iCardID % 4;
return iType + iSuit * 13;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MiddleLayer;
import MiddleLayer.OtherClass.CommandStruct;
import NetworkManager.MultiThreadChatServer;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
/**
*
* @author ThanhTri
* Lớp xử lý các sự kiện ở Server. Bao gồm:
* - Tạo kết nối client - server
* - Gửi và phản hồi thông tin với client
* - Kiểm tra trạng thái luật của trò chơi
*/
public class ServerProcessing implements Observer{
public boolean closed = false;
MultiThreadChatServer server = null;
int port_number = 2223;
List<Cards> lstPlayerCards = null;
List<Integer> lstPassCard = new ArrayList<Integer>(); //Đánh dấu người chơi pass
List<Integer> lstPlayCard = new ArrayList<Integer>(); //Đánh dấu dùng trong 1 lần ra bài.
List<Integer> lstMarks = new ArrayList<Integer>(); //danh sách điểm tính tới thời điểm hiện tại
int iFirstPlayerInRound = -1;//Người đi đầu tiên trong round đó
//int iCurrentPlayer = 0;
int iNumOfPlayers = -1;
int iNumOfCards = -1;//thay đổi tùy theo só người chơi
int iCurrPlayer = -1;//Người chơi hiện tại mới gửi dữ liệu lên server
int iOrderOfDeal = 0;//Cho biết hiện tại là ván bài thứ mấy
int iOrderOfRound = 0;//Cho biết hiện tại là lượt thứ mấy của ván này rồi, tối đa số nước đi bằng số quân bài
/*
* Khởi tạo server và chờ kết nối từ bên ngoài
* Đồng thời bắt đầu gửi dữ liệu luôn
*/
public void initServer()
{
this.server = new MultiThreadChatServer();
this.server.addObserver(this);
server.initServer(port_number);
//this.startGame();
//this.server.disconnectClients();
}
public void startGame()
{
this.iNumOfPlayers = this.server.getNumOfClient();
//Ngưng nhận kết nối
this.server.setNotAcceptConnect();
for(int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer)
{
this.lstPlayerCards.add(new Cards());
this.lstMarks.add( new Integer(0) );
}
this.generateCards();
//Send bài qua cho client sau khi tạo xong
for(int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer)
this.server.sendDataToThreadNumber(iPlayer, new CommandStruct(this.lstPlayerCards.get(iPlayer)));
// while(!this.closed)
// {
// }
}
/**
* Khởi tạo random các lá bài cho các đội chơi
* Đồng thời khởi tạo các giá trị khác để server handle trò chơi
*/
private void generateCards()
{
List<Integer> lstRandomCard = null;
int iRandomCard = 0;
this.iNumOfCards = 0;//thay đổi tùy theo só người chơi
for(int i = 0; i < 52; ++i)
{
lstRandomCard.add(0);
}
switch(this.iNumOfPlayers)
{
case 4:
iNumOfCards = 13;
for(int player = 0; player < iNumOfPlayers; ++ player)
{
Cards cards = this.lstPlayerCards.get(player);
//trường hợp chia cho các người chơi khác trước
if(player < iNumOfPlayers - 1)
{
for(int iCard = 0; iCard < iNumOfCards; ++iCard)
{
do{
iRandomCard = (int) ( Math.random()*51 + 0.5 );
}while(lstRandomCard.get(iRandomCard) != 0);
//Đánh dấu đã sử dụng lá bài này
lstRandomCard.set(iRandomCard, 1);
cards.addCard(iRandomCard);
}
}
else//Thêm các lá bài còn lại cho người chơi cuối cùng
{
for(int i = 0; i < lstRandomCard.size(); ++i)
{
if(lstRandomCard.get(i) != 1)
cards.addCard(i);
}
}
}
break;
case 3:
iNumOfCards = 17;
for(int player = 0; player < iNumOfPlayers; ++ player)
{
Cards cards = this.lstPlayerCards.get(player);
if(player < iNumOfPlayers - 1)
{
for (int iCard = 0; iCard < iNumOfCards; ++iCard)
{
do{
iRandomCard = (int) ( Math.random()*51 + 0.5 );
}while(lstRandomCard.get(iRandomCard) != 0 && !Card.isTwoOfDiamonds(iRandomCard));
//Đánh dấu đã sử dụng lá bài này
lstRandomCard.set(iRandomCard, 1);
cards.addCard(iRandomCard);
}
}
else//Thêm các lá bài còn lại cho người chơi cuối cùng
{
for(int i = 0; i < lstRandomCard.size(); ++i)
{
int id = lstRandomCard.get(i);
if(id != 1 && !Card.isTwoOfDiamonds(id))
cards.addCard(i);
}
}
}
break;
case 2:
iNumOfCards = 26;
Cards cards = this.lstPlayerCards.get(0);
for(int iCard = 0; iCard < iNumOfCards; ++iCard)
{
do{
iRandomCard = (int) ( Math.random()*51 + 0.5 );
}while(lstRandomCard.get(iRandomCard) != 0);
//Đánh dấu đã sử dụng lá bài này
lstRandomCard.set(iRandomCard, 1);
cards.addCard(iRandomCard);
}
cards = this.lstPlayerCards.get(1);
for(int i = 0; i < lstRandomCard.size(); ++i)
{
int id = lstRandomCard.get(i);
if(id != 1)
cards.addCard(i);
}
break;
};
//Khởi tạo giá trị cho 2 lstPassCard và lstPlayCard
setValueForLstCard(0);
}
void setValueForLstCard(int iValue)
{
this.lstPassCard.clear();
this.lstPlayCard.clear();
for(int i = 0; i < this.iNumOfPlayers; ++i)
{
this.lstPassCard.add(new Integer(iValue));
this.lstPlayCard.add(new Integer(iValue));
}
}
boolean isAllLstHasTheValue(int iValue, List<Integer> lst)
{
boolean bResult = true;
for(int i = 0; i < this.iNumOfPlayers; ++i)
{
if( (Integer) lst.get(i) != iValue)
bResult = false;
}
return bResult;
}
/**
* Người chơi được nhận thêm các lá bài trong lượt PASS
* @param iPlayer
* @param cmdStruct
*/
void addCardsToPlayer(int iPlayer, CommandStruct cmdStruct)
{
Cards cards = this.lstPlayerCards.get(iPlayer);
List<Integer> lstIDs = cmdStruct.getPassIDCards();
for(int i = 0; i < lstIDs.size(); ++i)
{
cards.addCard(lstIDs.get(i));
}
}
/**
* Người chơi được nhận thêm các lá bài trong lượt PASS
* @param iPlayer
* @param cmdStruct
*/
void removeCardsFromPlayer(int iPlayer, CommandStruct cmdStruct)
{
Cards cards = this.lstPlayerCards.get(iPlayer);
List<Integer> lstIDs = cmdStruct.getPassIDCards();
for(int i = 0; i < lstIDs.size(); ++i)
{
cards.removeCard(lstIDs.get(i));
}
}
/*
* Có dữ liệu tới
*/
public void update(Observable o, Object arg) {
//Đầu tiên cần biết dữ liệu đó là từ thằng nào
int iDataFromClientNumber = (Integer)arg;
//Xử lý dữ liệu nhận từ client này
this.iCurrPlayer = iDataFromClientNumber /10 - 1;
if(iDataFromClientNumber % 10 == 0)//Dữ liệu chat
processMessage(this.server.clientChatReceiver[this.iCurrPlayer]);
else
processMessage(this.server.clientCMDReceiver[this.iCurrPlayer]);
}
/*
* Tập trung các thông điệp về để xử lý
*/
private void processMessage(CommandStruct cmdStruct)
{
switch(cmdStruct.getMessageType())
{
case NewPlayer:
CommandStruct welcomeNewPlayer = new CommandStruct(
CommandStruct.MessageType.Chat, //Thông điệp được gửi sẽ là thông điệp chat
"Chào mừng người chơi " + cmdStruct.getContentOfMessage());
this.server.sendDataToAllThread(welcomeNewPlayer);
break;
case Chat:
this.server.sendDataToOtherThread(this.server.clientChatReceiver[iCurrPlayer], iCurrPlayer);
break;
case Pass:
this.lstPassCard.set(this.iCurrPlayer, new Integer(1));
//Nếu đã nhận được đầy đủ thông tin đổi bài từ các client
if(isAllLstHasTheValue(1, this.lstPassCard))
{
//PASS tùy theo số lượng người chơi
// <editor-fold defaultstate="collapsed" desc="Pass bài trên server tùy theo số lượng người chơi và số lượt đã chơi">
switch (this.iNumOfPlayers) {
case 2:
if (this.iOrderOfDeal % 2 == 0)//Lượt chẵn: Đổi bài cho nhau
{
this.removeCardsFromPlayer(0, this.server.clientCMDReceiver[0]);
this.addCardsToPlayer(1, this.server.clientCMDReceiver[0]);
this.removeCardsFromPlayer(1, this.server.clientCMDReceiver[1]);
this.addCardsToPlayer(0, this.server.clientCMDReceiver[1]);
} else//Lượt lẻ: Không đổi bài
{
}
break;
case 3:
switch (this.iOrderOfDeal % 3) {
case 0://Chia về bên trái
this.removeCardsFromPlayer(0, this.server.clientCMDReceiver[0]);
this.addCardsToPlayer(0, this.server.clientCMDReceiver[2]);
this.removeCardsFromPlayer(1, this.server.clientCMDReceiver[1]);
this.addCardsToPlayer(1, this.server.clientCMDReceiver[0]);
this.removeCardsFromPlayer(2, this.server.clientCMDReceiver[2]);
this.addCardsToPlayer(2, this.server.clientCMDReceiver[1]);
break;
case 1://Chia về bên phải
this.removeCardsFromPlayer(0, this.server.clientCMDReceiver[0]);
this.addCardsToPlayer(0, this.server.clientCMDReceiver[1]);
this.removeCardsFromPlayer(1, this.server.clientCMDReceiver[1]);
this.addCardsToPlayer(1, this.server.clientCMDReceiver[2]);
this.removeCardsFromPlayer(2, this.server.clientCMDReceiver[2]);
this.addCardsToPlayer(2, this.server.clientCMDReceiver[0]);
break;
case 2://Không làm gì cả
break;
}
break;
case 4:
switch (this.iOrderOfDeal % 4) {
case 0://chia qua bên tay trái
for (int iPlayer = 0; iPlayer < this.iNumOfPlayers - 1; ++iPlayer) {
this.removeCardsFromPlayer(iPlayer, this.server.clientCMDReceiver[iPlayer]);
this.addCardsToPlayer(iPlayer + 1, this.server.clientCMDReceiver[iPlayer]);
}
this.removeCardsFromPlayer(3, this.server.clientCMDReceiver[3]);
this.addCardsToPlayer(0, this.server.clientCMDReceiver[3]);
break;
case 1://chia qua bên tay phải
for (int iPlayer = 1; iPlayer < this.iNumOfPlayers; ++iPlayer) {
this.removeCardsFromPlayer(iPlayer, this.server.clientCMDReceiver[iPlayer]);
this.addCardsToPlayer(iPlayer - 1, this.server.clientCMDReceiver[iPlayer]);
}
this.removeCardsFromPlayer(0, this.server.clientCMDReceiver[0]);
this.addCardsToPlayer(3, this.server.clientCMDReceiver[0]);
break;
case 2://chia người đối diện.
for (int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer) {
this.removeCardsFromPlayer(iPlayer, this.server.clientCMDReceiver[iPlayer]);
}
this.addCardsToPlayer(0, this.server.clientCMDReceiver[2]);
this.addCardsToPlayer(1, this.server.clientCMDReceiver[3]);
this.addCardsToPlayer(2, this.server.clientCMDReceiver[0]);
this.addCardsToPlayer(3, this.server.clientCMDReceiver[1]);
break;
case 3://Không làm gì cả
break;
}
break;
}// </editor-fold>
//Cập nhật lại trạng thái các lá bài cho client.
for(int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer)
{
this.server.sendDataToThreadNumber(iPlayer, new CommandStruct(this.lstPlayerCards.get(iPlayer)));
}
}
break;
case StartPlaying://Được nhận từ client nào đó không cần biết. Mặc định là chỉ client tạo server mới được thực hiện chức năng này
this.startGame();
break;
case PlayCard://Trường hợp người chơi chọn lá bài để đi
if(iFirstPlayerInRound != -1)
iFirstPlayerInRound = this.iCurrPlayer;
this.lstPlayCard.set(this.iCurrPlayer, 1);
//Đẩy thông tin cho các client khác biết player này đã đi nước này
this.server.sendDataToOtherThread(cmdStruct, iCurrPlayer);
//server nhận đủ thông tin từ phía client
//Bắt đầu tính điểm và gửi lại thông tin cập nhật bộ bài cho client nếu cần
if(isAllLstHasTheValue(1, this.lstPlayCard))
{
this.iOrderOfRound++;
//Kết thúc 1 lượt đi, cập nhật danh sách lá bài của các client đã đi
if (this.iOrderOfRound < this.iNumOfCards) {
//Tính xem ai là người ăn hết các lá bài (Người điểm cao nhất)
//Cho người đó đi trước
int iNextFirstPlayer = checkWhenEndRound();
//Gửi thông báo đến cho client để bắt đầu lượt đấu mới(vẫn trong vòng đấu này)
this.server.sendDataToAllThread(
new CommandStruct(
CommandStruct.MessageType.NewRound,
Integer.toString(iNextFirstPlayer)
)
);
iFirstPlayerInRound = -1;
}
else
{
//Tính điểm
calScoreWhenEndDeal();
int idWinnerPlayer = this.findTheWinner();
if(idWinnerPlayer == -1)
{
//Gửi thông báo đến cho client để bắt đầu vòng đấu mới
this.server.sendDataToAllThread(new CommandStruct(CommandStruct.MessageType.NewDeal, ""));
this.iOrderOfDeal++;
this.iOrderOfRound = 0;
this.iFirstPlayerInRound = -1;
//gọi lại hàm generateCard để phân phối lại các quân bài cho phía client
this.generateCards();
for(int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer)
this.server.sendDataToThreadNumber(iPlayer, new CommandStruct(this.lstPlayerCards.get(iPlayer)));
//this.processMessage(new CommandStruct(CommandStruct.MessageType.StartPlaying, ""));
}
else
{
//Gửi thông báo chúc mừng đến cho client
this.server.sendDataToAllThread(new CommandStruct(CommandStruct.MessageType.Chat, "Hết game."));
}
}
}
break;
case Quit:
this.closed = true;
break;
}
}
/**
* Được gọi để cập nhật lại điểm số sau mỗi vòng thi đấu (vòng thì đấu nhiều lượt)
*/
private void calScoreWhenEndDeal()
{
//Tính điểm tổng kết xem 100 chưa?
int iIsShootingTheMoon = -1;
for(int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer)
{
Cards cards = this.lstPlayerCards.get(iPlayer);
//Kiểm tra trường hợp shooting the moon
if(cards.isShootingTheMoon())
{
iIsShootingTheMoon = iPlayer;
}
}
//Có shooting the moon
if(iIsShootingTheMoon > -1)
{
for(int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer)
{
int iScore = this.lstMarks.get(iPlayer);
//Người chơi shooting the moon + 0
if(iIsShootingTheMoon == iPlayer)
iScore += 0;
else//Không thì cộng tận 26 điểm
iScore += 26;
this.lstMarks.set(iPlayer, iScore);
}
}
else
{
for(int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer)
{
Cards cards = this.lstPlayerCards.get(iPlayer);
int iScore = this.lstMarks.get(iPlayer);
iScore += cards.getScore();
this.lstMarks.set(iPlayer, iScore);
}
}
}
/**
*
* @return
* Trả về id của client là người chiến thắng:
* - Thắng khi có số điểm nhỏ nhất
*/
private int findTheWinner()
{
int idPlayer = -1;
boolean bIsOver100 = false;
int iSmallestScore = 200;
for(int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer)
{
int score = (Integer) this.lstMarks.get(iPlayer);
if(score > 100)
bIsOver100 = true;
if(score < iSmallestScore)
{
iSmallestScore = score;
idPlayer = iPlayer;
}
}
//Chưa có người nào quá 100 điểm thì chơi tiếp
idPlayer = bIsOver100 ? idPlayer : -1;
return idPlayer;
}
/**
* Tính toán ai sẽ ăn được quân bài khi một lượt kết thúc (vòng có nhiều lượt)
* @return
* Người sẽ đi nước đầu tiên ở lượt tiếp theo
*/
private int checkWhenEndRound()
{
List<Card> lstCardInRound = new ArrayList<Card>();
for(int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer)
{
lstCardInRound.add(new Card(Integer.parseInt(this.server.clientCMDReceiver[iPlayer].getContentOfMessage())));
}
int iResult = this.iFirstPlayerInRound;
Card firstCard = lstCardInRound.get(iResult);
Card otherCard = null;
for(int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer)
{
if(iResult != iPlayer)
{
otherCard = lstCardInRound.get(iPlayer);
if(firstCard.isSameSuit(otherCard.getId()))//Có cùng suite hay không
{
if(firstCard.getId() < otherCard.getId())//Kiểm tra xem giá trị lá bài có nhỏ hơn hay không
{
iResult = iPlayer;
}
}
}
}
//Thêm tất cả các lá bài vào cho client này
Cards cards = this.lstPlayerCards.get(iResult);
for(int iCard = 0; iCard < lstCardInRound.size(); ++iCard)
{
cards.addWinCard(lstCardInRound.get(iCard).getId());
}
//Loại bỏ các lá bài này ra khỏi cuộc chơi
for(int iPlayer = 0; iPlayer < this.iNumOfPlayers; ++iPlayer)
{
this.lstPlayerCards.get(iPlayer).playThisCard(
lstCardInRound.get(iPlayer).getId()
);
}
return iResult;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MiddleLayer;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author ThanhTri
* Lớp quản lý toàn bộ những lá bài mà client hay server đang giữ.
*/
public class Cards {
List lstOfCards = new ArrayList(); //danh sách các lá bài của người chơi
List lstWinCards = new ArrayList();//danh sách các lá bài mà người chơi thắng
// Cards()
// {
// for(int card = 0; card < 52; ++card)
// {
// this.lstOfCards.add(new Card(card));
// }
// }
/**
* Thêm lá bài mới mà người chơi có thể sử dụng
*/
public void addCard(int id)
{
lstOfCards.add(new Card(id));
}
/**
* Xóa sạch dữ liệu, import lại từ đầu
*/
public void clearCards()
{
this.lstOfCards.clear();
this.lstWinCards.clear();
}
/**
* Thường chỉ sử dụng hàm này trong việc trao đổi bài. Cân nhắc cẩn thận khi sử dụng
* @param id ID của lá bài sẽ bị bỏ
* @return Kết quả trả về cho biết có loại bỏ được hay không
*/
public boolean removeCard(int id)
{
boolean bResult = false;
for(int i = 0; i < this.lstOfCards.size(); ++i)
{
if((Integer) this.lstOfCards.get(i) == id)
{
this.lstOfCards.remove(i);
bResult = true;
}
}
return bResult;
}
/**
* Lá bài này đã được sử dụng --> Bỏ đi
*/
public boolean playThisCard(int id)
{
for(int iCard = 0; iCard < lstOfCards.size(); ++ iCard)
{
Card card = (Card) lstOfCards.get(iCard);
if(card.getId() == id)
{
card.setbIsUsed();
return true;
}
}
return false;
}
/**
* Trả về danh sách các lá bài có thể còn chơi được
*/
public List<Integer> getCardLst()
{
List<Integer> lstResults = null;
for(int iCard = 0; iCard < lstOfCards.size(); ++ iCard)
{
Card card = (Card) lstOfCards.get(iCard);
if(!card.isbIsUsed())
{
lstResults.add(card.getId());
}
}
return lstResults;
}
//Thêm lá bài thắng được vào danh sách
public void addWinCard(int id)
{
lstWinCards.add(new Card(id));
}
//Trả về danh sách các lá bài có thể còn chơi được
public List<Integer> getWinCardLst()
{
List<Integer> lstResults = null;
for(int iCard = 0; iCard < lstWinCards.size(); ++ iCard)
{
Card card = (Card) lstWinCards.get(iCard);
lstResults.add(card.getId());
}
return lstResults;
}
/*
* kiểm tra trong danh sách các lá bài còn lại trong tay
* xem còn lá nào cùng loại hay không
*/
public boolean stillHaveSameSuitCard(int iCardID)
{
boolean result = false;
for(int iCard = 0; iCard < lstOfCards.size(); ++ iCard)
{
Card card = (Card) lstOfCards.get(iCard);
if(!card.isbIsUsed())
{
result = Card.isSameSuit(iCardID, card.getId());
}
}
return result;
}
/*
*Trả về điểm số hiện tại: Được tính theo công thức:
* Lá bài cơ: 1 điểm
* Q bích: 13 điểm.
*/
public int getScore()
{
int iScore = 0;
for(int iCard = 0; iCard < lstWinCards.size(); ++ iCard)
{
Card card = (Card) lstWinCards.get(iCard);
if(Card.isHeartCard(card.getId()))
iScore += 1;
if(Card.isQueenOfSpades(card.getId()))
iScore += 13;
}
//trường hợp shooting the moon
if(iScore == 26)
iScore = 0;
return iScore;
}
/*
* Kiếm tra xem có đạt được Shooting the Moon hay không
*
*/
public boolean isShootingTheMoon()
{
boolean bIsShootingTheMoon = false;
boolean bHaveQueenOfSpades = false;
int iNumOfHeartCard = 0;
for(int iCard = 0; iCard < lstWinCards.size(); ++ iCard)
{
Card card = (Card) lstWinCards.get(iCard);
if(Card.isHeartCard(card.getId()))
iNumOfHeartCard += 1;
if(Card.isQueenOfSpades(card.getId()))
bHaveQueenOfSpades = true;
}
//trường hợp shooting the moon
if(bHaveQueenOfSpades == true && iNumOfHeartCard == 13)
bIsShootingTheMoon = true;
return bIsShootingTheMoon;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MiddleLayer.OtherClass;
import MiddleLayer.Cards;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author ThanhTri
* - Lớp dùng để chứa dữ liệu đi lên đi xuống giữa các middle và network
*/
public class CommandStruct {
static public String commandCode = "CMD";
static public String chatCode = "CHA";
static public String newPlayer = "NPL";//Có người chơi mới
static public String quitCode = "QUI";
static public String passCode = "PAS";
static public String updateCardsCode = "UPC";//cập nhật toàn bộ danh sách bài
static public String startPlayingCode = "PLA";//bắt đầu chơi
static public String playCardCode = "PLC";//client chọn lá bài này để đi
static public String newRoundCode = "NRC";//Lượt đi mới, client có id này sẽ đi đầu
static public String newDealCode = "NDC";//Vòng đi mới, mỗi vòng gồm có nhiều lượt đi nhỏ
/**
* @return the iType
*/
public MessageType getMessageType() {
return iType;
}
public enum MessageType {
Command,
Chat,
NewPlayer,//Thông điệp string sẽ chứa tên người chơi
Quit,
Pass,//các id sẽ cách nhau bởi 1 khoảng trắng
UpdateCards,//Các id sẽ cách nhau bởi 1 khoảng trắng
StartPlaying,//bắt đầu chơi
PlayCard,//phía sau là id của lá bài sẽ đi
NewRound,//Lượt đi mới, mỗi vòng gồm nhiều lượt đi
NewDeal,//vòng đi mới
};
/*
* Type 0: Command
* Type 1: Chat
*/
private MessageType iType = MessageType.Command;
private String strContentOfMessage = null;
private String seperateCharacter = " ";
public CommandStruct(MessageType messageType, String content) {
strContentOfMessage = content;
iType = messageType;
}
/**
* Thường gọi khi có lệnh PASS
* @param id1
* @param id2
* @param id3
*/
public CommandStruct(int id1, int id2, int id3)
{
this.iType = MessageType.Pass;
this.strContentOfMessage = id1 + seperateCharacter + id2 + seperateCharacter + id3;
}
/**
* Thường gọi khi có lệnh update cả bộ bài cho phía client
* Tuy lớp cards có danh sách các lá ăn được
* Nhưng không đưa xuống cho client biết mà chỉ giữ ở phía trên server sử dụng
* @param id1
* @param id2
* @param id3
*/
public CommandStruct(Cards cards)
{
this.iType = MessageType.Pass;
List<Integer> cardLst = cards.getCardLst();
for(int i = 0; i < cardLst.size() - 1; ++i)
{
this.strContentOfMessage += cardLst.get(i) + seperateCharacter;
}
this.strContentOfMessage += cardLst.get(cardLst.size() - 1);
}
public CommandStruct(String rawText)
{
if(rawText.startsWith(CommandStruct.chatCode))
iType = MessageType.Chat;
if(rawText.startsWith(CommandStruct.commandCode))
iType = MessageType.Command;
if(rawText.startsWith(CommandStruct.newPlayer))
iType = MessageType.NewPlayer;
if(rawText.startsWith(CommandStruct.quitCode))
iType = MessageType.Quit;
if(rawText.startsWith(CommandStruct.passCode))
iType = MessageType.Pass;
if(rawText.startsWith(CommandStruct.updateCardsCode))
iType = MessageType.UpdateCards;
if(rawText.startsWith(CommandStruct.startPlayingCode))
iType = MessageType.StartPlaying;
if(rawText.startsWith(CommandStruct.playCardCode))
iType = MessageType.PlayCard;
if(rawText.startsWith(CommandStruct.newDealCode))
iType = MessageType.NewDeal;
if(rawText.startsWith(CommandStruct.newRoundCode))
iType = MessageType.NewRound;
this.strContentOfMessage = rawText.substring(CommandStruct.chatCode.length());
}
/*
* Thay đổi nội dung của gói tin command
* Tương tự như hàm tạo public
*/
public void changeCommand(String rawText)
{
if(rawText.startsWith(CommandStruct.chatCode))
iType = MessageType.Chat;
if(rawText.startsWith(CommandStruct.commandCode))
iType = MessageType.Command;
if(rawText.startsWith(CommandStruct.newPlayer))
iType = MessageType.NewPlayer;
if(rawText.startsWith(CommandStruct.quitCode))
iType = MessageType.Quit;
if(rawText.startsWith(CommandStruct.passCode))
iType = MessageType.Pass;
if(rawText.startsWith(CommandStruct.updateCardsCode))
iType = MessageType.UpdateCards;
if(rawText.startsWith(CommandStruct.playCardCode))
iType = MessageType.PlayCard;
if(rawText.startsWith(CommandStruct.newDealCode))
iType = MessageType.NewDeal;
if(rawText.startsWith(CommandStruct.newRoundCode))
iType = MessageType.NewRound;
this.strContentOfMessage = rawText.substring(CommandStruct.chatCode.length());
}
/**
* @return Nội dung của gói lệnh
*/
public String getContentOfMessage() {
return strContentOfMessage;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.strContentOfMessage = message;
}
/**
* Kiểm tra loại của Message 1 cách tổng quát
*/
public boolean isMessageType(MessageType messageType)
{
if(getMessageType() == messageType)
return true;
return false;
}
//Thông điệp này có phải là thông điệp chat không?
public boolean isChatMessage()
{
if(getMessageType() == MessageType.Chat)
return true;
return false;
}
//Thông điệp này có phải là thông điệp chat không?
public boolean isCommandMessage()
{
if(getMessageType() == MessageType.Command)
return true;
return false;
}
static public CommandStruct createNewPlayerCMDStruct(String clientName)
{
CommandStruct cmdStruct = new CommandStruct(MessageType.NewPlayer, clientName);
return cmdStruct;
}
/**
* @return Kiểu chuỗi chứa mã lệnh và nội dung của lệnh
*/
@Override
public String toString()
{
String result = "";
switch(this.getMessageType())
{
case Chat:
result = CommandStruct.chatCode;
break;
case Command:
result = CommandStruct.commandCode;
break;
case NewPlayer:
result = CommandStruct.newPlayer;
break;
case Quit:
result = CommandStruct.quitCode;
break;
case Pass:
result = CommandStruct.passCode;
break;
case PlayCard:
result = CommandStruct.playCardCode;
break;
case StartPlaying:
result = CommandStruct.startPlayingCode;
break;
case UpdateCards:
result = CommandStruct.updateCardsCode;
break;
case NewDeal:
result = CommandStruct.newDealCode;
break;
case NewRound:
result = CommandStruct.newRoundCode;
break;
}
return result + this.strContentOfMessage;
}
//Kiểm tra xem dữ liệu thô này có phải dữ liệu chat không
static public boolean isChatMessage(String rawData)
{
if(rawData.startsWith(CommandStruct.chatCode))
return true;
return false;
}
//Kiểm tra xem dữ liệu thô này có phải dữ liệu chỉ thị không
static public boolean isCommandMessage(String rawData)
{
if(rawData.startsWith(CommandStruct.commandCode))
return true;
return false;
}
//Kiểm tra xem dữ liệu thô này có phải lệnh quit hay không
static public boolean isQuitMessage(String rawData)
{
if(rawData.startsWith(CommandStruct.quitCode))
return true;
return false;
}
//lấy ra mã code của thông điệp được gửi đến server
static public String parseGetCode(String data){
String result = new String();
//result = String.copyValueOf(data.toCharArray(), 0, 3);
result = data.substring(0, CommandStruct.quitCode.length());
return result;
}
//Thông điệp được gửi đến có chứa mã kết thúc không?
static public boolean isCommandQUIT(String data){
if(data.startsWith(CommandStruct.quitCode, 0))
return true;
return false;
}
// trả về dữ liệu gốc ban đầu
static public String getClearText(String data){
return data.substring(CommandStruct.commandCode.length());
}
/**
* Trả về các card sẽ được pass trong lượt chơi
* @return
*/
public List<Integer> getPassIDCards()
{
List<Integer> Result = new ArrayList<Integer>();
if(this.iType == MessageType.Pass)
{
String tmp = this.strContentOfMessage;
while(!tmp.equals(""))
{
int iIndex = tmp.indexOf(seperateCharacter);
String number = tmp.substring(0, iIndex);
tmp = tmp.substring(iIndex);
Result.add(Integer.getInteger(number));
}
}
return Result;
}
/**
* Trả về các card được nhận mới từ phía server trong lượt chơi
* Thường gọi khi bắt đầu ván bài hoặc sau khi PASS bài
* @return
*/
public List<Integer> getUpdateIDCards()
{
List<Integer> Result = new ArrayList<Integer>();
if(this.iType == MessageType.UpdateCards)
{
String tmp = this.strContentOfMessage;
while(!tmp.equals(""))
{
int iIndex = tmp.indexOf(seperateCharacter);
String number = tmp.substring(0, iIndex);
tmp = tmp.substring(iIndex);
Result.add(Integer.getInteger(number));
}
}
return Result;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MiddleLayer.OtherClass;
import java.util.Observable;
/**
*
* @author ThanhTri
*/
public class MyObservable extends Observable {
@Override
public void clearChanged() {
super.clearChanged();
}
@Override
public void setChanged() {
super.setChanged();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MiddleLayer;
/**
*
* @author ThanhTri
*/
public class HeartGame {
//Kiểm tra trạng thái kết nối vào server hay chưa? Nếu chưa không cho bắt đầu chơi
private boolean isStillConnectToServer = false;
private ClientProcessing client = new ClientProcessing();
private ServerProcessing server = new ServerProcessing();
/*
* khởi tạo trạng thái game: GUI, luật chơi
*/
public void initGameState()
{
//Tạo GUI
//Cho chọn làm server hay tìm server trong mạng
//Chọn xong kết nối server rồi bắt đầu chơi
}
/*
* Chỉ chơi game nếu đã có kết nói client - server
*
*/
public void playGame()
{
//Vòng lặp game
while(true)
{
//Kiểm tra trạng thái kết nối
}
}
/*
* Tìm kiếm server kết nối trong mạng LAN
*/
public void findServer()
{
client.findServer();
}
/*
* Kết nối vào server
*/
public void connectToServer()
{
//client.;
}
/*
* Tạo server
*/
public void initServer()
{
server.initServer();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MiddleLayer;
import GUI.Hearts;
import MiddleLayer.OtherClass.CommandStruct;
import MiddleLayer.OtherClass.CommandStruct.MessageType;
import NetworkManager.MultiThreadChatClient;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JPanel;
/**
*
* @author ThanhTri
* Lớp xử lý các sự kiện ở Client. Bao gồm:
* - GUI
* - Gửi và nhận dữ liệu với client.
* - Kiểm tra nước đi có hợp lệ hay không
*/
public class ClientProcessing implements Observer{
Hearts heartGame = null;
public GameRules gameRules = new GameRules();
protected Cards lstCard = new Cards();
MultiThreadChatClient client = new MultiThreadChatClient();;
int port_number = 2223;
int iFirstPlayerInThisRound = -1;
private Hearts game;// game của mình
private JPanel pnlInfo;//panel chứa control chat và hiển thị thông tin
/*
* Tìm kiếm client kết nối trong mạng LAN
*/
public void findServer()
{
}
/**
* @param info là panel chứa thông tin, chat
* @param game game mình đang chạy
*/
public void setup(JPanel info, Hearts game) {
this.game = game;
this.pnlInfo = info;
this.gameRules = new GameRules();
}
/*
* Kết nối vào client
*/
public void connectToServer(String clientName)
{
client.connectToServer("localHost", port_number);
//Sau khi kết nối lập tức gửi ngay tên lên
client.sendMessage(CommandStruct.createNewPlayerCMDStruct(clientName));
}
/*
* Kiểm tra nước đi xem có thỏa luật chơi không
* Truyền vào tham số của lá bài định đi
* Và cho biết là sẽ đi lượt đầu tiên hay ra bài chờ người khác
*/
private boolean isTheMoveValid(int iCardIDWillPlay, int iCardIDWasPlayByOtherPlayer, boolean bIsLeadMove)
{
boolean result = false;
if(bIsLeadMove)
result = gameRules.isLeadMovingValid(iCardIDWillPlay);
else
result = gameRules.isMovingValid(iCardIDWillPlay, iCardIDWasPlayByOtherPlayer, this.lstCard);
return result;
}
/*
* Khởi tạo GUI
*/
public void initGUI()
{
}
/*
* Khởi tạo game
*/
public void initGame()
{
this.client.addObserver(this);
//Truyền con trỏ this vào Hearts
//heartGame = new Hearts();
//Sau đó có thể dùng GUI để gọi đến hàm connectToServer
//v`i cái game gắn với cái form? l`am sao đ^ay
this.connectToServer("client1");
}
public void startGame()
{
//Vòng lặp game
// while(!client.closed){
// }
}
//Có dữ liệu đến, lấy dữ liệu (CommandStruct) ra xử lý cho game
public void update(Observable o, Object arg) {
CommandStruct cmdStruct = (CommandStruct)arg;
processMessageFromServer(cmdStruct);
}
/**
* Tập trung các thông điệp về để xử lý
*/
private void processMessageFromServer(CommandStruct cmdStruct)
{
switch(cmdStruct.getMessageType())
{
case NewPlayer:
//Hiện khung chat
System.out.println(cmdStruct.getContentOfMessage());
break;
case Chat:
//Hiện khung chat
System.out.println(cmdStruct.getContentOfMessage());
break;
case Pass://Client sẽ nhận được từ server danh sách bài mới
List<Integer> lstNewIDs = cmdStruct.getUpdateIDCards();
this.lstCard.clearCards();
for(int i = 0; i < lstNewIDs.size(); ++i)
{
this.lstCard.addCard(lstNewIDs.get(i));
}
break;
case StartPlaying://Được nhận từ client nào đó không cần biết. Mặc định là chỉ client tạo server mới được thực hiện chức năng này
this.startGame();
break;
case PlayCard://Cho biết người chơi khác đã đi nước này
//Hiển thị lên màn hình rồi ngồi chò
Card cardPlayed = new Card(Integer.parseInt(cmdStruct.getContentOfMessage()));
//Client sau khi chọn xong sẽ dùng hàm khác gửi nội dung lên server
break;
case NewRound://Cho biết ai sẽ là người đi trước
iFirstPlayerInThisRound = Integer.parseInt(cmdStruct.getContentOfMessage());
break;
case NewDeal://Lượt thi đấu mới
System.out.println("Vòng đấu mới sắp bắt đầu");
//Gọi hàm để hiển thị cho người chơi biết
break;
case Quit:
break;
}
}
public void sendMessageToServer(MessageType messageType, String content)
{
switch(messageType)
{
case Chat:
this.client.sendMessage(new CommandStruct(messageType, content));
break;
case PlayCard:
this.client.sendMessage(new CommandStruct(messageType, content));
break;
case StartPlaying://bắt đầu kết nối tới server để chơi
this.client.sendMessage(new CommandStruct(messageType, ""));
break;
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MiddleLayer;
import GUI.*;
import GUI.Hearts.GameState;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
/**
*
* @author Green
*/
public class ClientServerMessenger {
Socket socketClient;//socket kết nối với server
ClientReceiver receiver;//cái này là tiểu trình lắng nghe server
Hearts game;//game của mình.
GameRules gameRules;
JPanel pnlInfo;//panel chứa control chat và hiển thị thông tin
boolean exit = false;//cái này là cờ để thoát
boolean commandfinish = false;
GUICard played;
public ClientServerMessenger() {
receiver = new ClientReceiver();
receiver.start();//bắt đầu tiểu trình lắng nghe server
}
//info là panel chứa thông tin, chat
//game là cái game mình đang chạy
public void setup(JPanel info, Hearts game) {
this.game = game;
this.pnlInfo = info;
this.gameRules = new GameRules();
}
//gửi thông tin đến server
public void sendToServer(String name, int guiCardID) {
System.out.println(name + " % " + guiCardID);
this.game.setPlayerState(Hearts.PlayerState.DoNothing);
this.played = this.client.findCardInAvailList(guiCardID % 13, guiCardID / 13);
this.finishTask(GameState.Playing);
this.commandfinish = true;
}
//gửi thông tin chat đến server
public void sendChatMessage(String m) {
System.out.println(m);
}
public void finishTask(GameState state) {
System.out.println(state.toString() + " completed ");
this.commandfinish = true;
}
public boolean checkRules(int nextguicardid, int firstcardonboard, Cards playersCards) {
int id = Card.convertCardGUI_IDToCard_ID(nextguicardid);
int fisrt = Card.convertCardGUI_IDToCard_ID(firstcardonboard);
return this.gameRules.isMovingValid(nextguicardid, fisrt, playersCards);
}
public boolean checkRules_FirstTurn(int nextguicardid) {
int id = Card.convertCardGUI_IDToCard_ID(nextguicardid);
return this.gameRules.isLeadMovingValid(id);
}
//Lớp chuyên lắng nghe server
private class ClientReceiver extends Thread {
@Override
public void run() {
boolean start = false;
int i = 0;
while (!exit) {
//cái này tui đang dùng để test
System.out.println("i=" + i + "Command : ");
String command = readInputFromConsole();
if (command.compareTo(".") == 0) {
start = true;
commandfinish = true;
testInitClients();
}
if (command.compareToIgnoreCase("exit") == 0) {
exit = true;
}
if (start) {
//processCommand(command);
if (commandfinish) {
runTest(i);
i++;
}
}
}
}
private String readInputFromConsole() {
String s = "";
try {
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
s = bufferRead.readLine();
System.out.println(s);
} catch (IOException e) {
System.err.println(e);
}
return s;
}
}
private class MethodResult {
Method method;
Object obj;
}
//Phần dưới là để test
private GamblerManager manager;
private Gambler client;
private String clientHas2OfClub;
private void processCommand(String command) {
String methodName = "";
// methodName = "testInitClients";
// MethodResult result = getMethodByName(methodName);
// result.method.invoke(result.obj, new Object[]{});
if (command.compareTo("0") == 0) {
testInitClients();
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(ClientServerMessenger.class.getName()).log(Level.SEVERE, null, ex);
}
testDealCard();
}
if (command.compareTo("1") == 0) {
testRequestPassLeft();
}
if (command.compareTo("2") == 0) {
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(ClientServerMessenger.class.getName()).log(Level.SEVERE, null, ex);
}
testSelectCardToPass_Left();
}
}
private void runTest(int i) {
if (i == 0) {
testDealCard();
}
if (i == 1) {
this.testRequestPassLeft();
}
if (i == 2) {
this.testSelectCardToPass_Left();
}
if (i == 3) {
this.testDoPass();
}
if (i == 4) {
this.testRequestPlayCard();
this.playLoop();
}
if (i == 5) {
}
}
private void playLoop() {
System.out.println("Begin play loop");
int turn = 0, firstPlayerIndx = 0;
int count = 0;
boolean isFirstTurn = true;
ArrayList<GUICard> lstPlayedCards = new ArrayList<GUICard>();
while (count < 13) {
if (!commandfinish) {
continue;
}
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(ClientServerMessenger.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Begin turn " + turn);
if (played != null) {
System.out.println("Allow Client play this card");
this.client.lstAvailableCards.remove(played);
this.testDoPlayCard(played.rank, played.suit, this.client.getName());
lstPlayedCards.add(played);
played = null;
continue;
}
if (turn > 3) {
firstPlayerIndx = KillLoser(lstPlayedCards);
lstPlayedCards.clear();
turn = 0;
count++;
continue;
}
if (isFirstTurn) {
if (this.clientHas2OfClub == this.client.getName()) {
this.testRequestPlayerPlayCard();
firstPlayerIndx = this.manager.getArrayIndexOfGambler(client);
} else {
Gambler cpu = this.manager.getGambler(clientHas2OfClub);
firstPlayerIndx = this.manager.getArrayIndexOfGambler(cpu);
GUICard card = this.CPU(cpu, lstPlayedCards, isFirstTurn);
lstPlayedCards.add(card);
this.testDoPlayCard(card.rank, card.CLUBS, clientHas2OfClub);
}
System.out.println(String.format("turn,first=%d,%d", turn, firstPlayerIndx));
isFirstTurn = false;
} else {
int temp = (turn + firstPlayerIndx) % 4;
System.out.println(String.format("temp,turn,first=%d,%d,%d", temp, turn, firstPlayerIndx));
if (temp == this.client.getID()) {
this.testRequestPlayerPlayCard();
} else {
Gambler cpu = this.manager.getGamblerByArrayIndex(temp);
GUICard card = this.CPU(cpu, lstPlayedCards, isFirstTurn);
lstPlayedCards.add(card);
this.testDoPlayCard(card.rank, card.suit, cpu.getName());
}
}
turn++;
}
System.out.println("Finished play loop");
}
public ClientServerMessenger(Socket socketClient, ClientReceiver receiver, Hearts game, GameRules gameRules, JPanel pnlInfo, GUICard played, GamblerManager manager, Gambler client, String clientHas2OfClub) {
this.socketClient = socketClient;
this.receiver = receiver;
this.game = game;
this.gameRules = gameRules;
this.pnlInfo = pnlInfo;
this.played = played;
this.manager = manager;
this.client = client;
this.clientHas2OfClub = clientHas2OfClub;
}
private GUICard CPU(Gambler cpu, ArrayList<GUICard> list, boolean isFirstTurn) {
GUICard him = null;
int firstCardId;
int id;
if (isFirstTurn) {
him = cpu.findCardInAvailList(0, GUICard.CLUBS);
cpu.lstAvailableCards.remove(him);
id = Card.convertCardGUI_IDToCard_ID(him.toCardID());
this.gameRules.isLeadMovingValid(id);
return him;
}
ArrayList<GUICard> suitList;
ArrayList<GUICard> applicants;
if (list.isEmpty()) {
suitList = cpu.findCardsInAvailListExcept(GUICard.HEARTS);
if (suitList.isEmpty()) {
suitList = (ArrayList<GUICard>) cpu.lstAvailableCards.clone();
}
applicants = suitList;
Collections.sort(applicants);
him = applicants.get(0);
cpu.lstAvailableCards.remove(him);
//hợp thức hóa thủ tục
id = Card.convertCardGUI_IDToCard_ID(him.toCardID());
boolean flag = this.gameRules.isLeadMovingValid(id);
if(!flag) System.out.println("Hỏng bét");
return him;
}
int sign = 1;
GUICard firstCard = list.get(0);
suitList = cpu.findCardsInAvailList(firstCard.suit);
applicants = new ArrayList<GUICard>();
if (suitList.isEmpty()) {
//tìm bộ khác bất kỳ
suitList.addAll(cpu.findCardsInAvailListExcept(firstCard.suit));
sign = -1;
}
for (int i = 0; i < suitList.size(); i++) {
GUICard card = suitList.get(i);
if (card.compareTo(firstCard) * sign < 0) {
applicants.add(card);
}
}
if(applicants.isEmpty())
applicants = suitList;
Collections.sort(applicants);
him = applicants.get(0);
cpu.lstAvailableCards.remove(him);
//hợp thức hóa thủ tục
id = Card.convertCardGUI_IDToCard_ID(him.toCardID());
firstCardId = Card.convertCardGUI_IDToCard_ID(firstCard.toCardID());
this.gameRules.isMovingValid(id, firstCardId, cpu.getGamblerCards());
return him;
}
private MethodResult getMethodByName(String methodname) {
MethodResult result = new MethodResult();
try {
Class c = Class.forName("MiddleLayer.ClientServerMessenger");
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
if (m[i].getName().compareToIgnoreCase(methodname) == 0) {
result.method = m[i];
result.obj = c.newInstance();
ClientServerMessenger messenger = (ClientServerMessenger) result.obj;
messenger.game = this.game;
messenger.pnlInfo = this.pnlInfo;
messenger.socketClient = this.socketClient;
return result;
}
System.out.println(m[i].toString());
}
} catch (Throwable e) {
System.err.println(e);
}
return result;
}
private void testInitClients() {
System.out.println("InitClients");
commandfinish = false;
String clientName = "so0";
ArrayList<String> list = new ArrayList<String>(4);
list.add("so1");
list.add("so0");
list.add("so2");
list.add("so3");
this.manager = new GamblerManager(1024, 540);
this.manager.initPlayers(clientName, list);
this.client = this.manager.getMainPlayer();
this.game.initAllsClients(clientName, list);
this.game.prepareForNextGame();
}
private void testDealCard() {
System.out.println("DealCards");
commandfinish = false;
Deck deck = new Deck();
deck.loadNewCards();
String clientName = "so0";
this.game.prepareToDeal();
deck.shuffle();
int j = 0;
for (int i = 0; i < 52; i++) {
j = j % 4;
GUICard card = deck.lstCards.get(i);
assert card == null;
Gambler gambler = this.manager.getGamblerByArrayIndex(j);
card.owner = j;
gambler.receiveCard(card);
if (card.isTwoOfClub()) {
this.clientHas2OfClub = gambler.getName();
}
this.game.dealCardToGambler(card.rank, card.suit, gambler.getName());
j++;
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(ClientServerMessenger.class.getName()).log(Level.SEVERE, null, ex);
}
}
for (int i = 0; i < 4; i++) {
Gambler gambler = this.manager.getGamblerByArrayIndex(i);
gambler.sortAvailCards();
}
}
private void testRequestPassLeft() {
System.out.println("Request Pass");
commandfinish = false;
this.game.prepareToPass(0);//pass left
}
private void testSelectCardToPass_Left() {
System.out.println("Do pass left-other client");
commandfinish = false;
for (int i = 1; i < 4; i++) {
Gambler gambler = this.manager.getGamblerByArrayIndex(i);
Cards cards = gambler.getGamblerCards();
for (int j = 0; j < 3; j++) {
Card c = (Card) cards.lstOfCards.get(j);
gambler.selectCardToPass(c.getType(), c.getSuit());
this.game.selectCardsToPass(c.getType(), c.getSuit(), gambler.getName());
}
}
commandfinish = true;
}
private void testDoPass() {
System.out.println("Do pass left");
commandfinish = false;
this.game.passSelectedCards(0);//left
this.manager.passCards(0);
}
private void testRequestPlayCard() {
System.out.println("Play Mode");
commandfinish = false;
this.game.prepareToPlay();
}
private void testRequestPlayerPlayCard() {
System.out.println("wait client for playing card");
commandfinish = false;
this.game.waitClientAction();
}
private void testDoPlayCard(int rank, int suit, String name) {
System.out.println(String.format("Server said Client %s play card rank=%d, suit=%d.", name, rank, suit));
commandfinish = false;
this.game.playCard(rank, suit, name);
}
private void testTakenCard(ArrayList<Integer> guiIDList, String name) {
commandfinish = false;
this.game.sendTakenCardsToGambler(guiIDList, name);
}
private int KillLoser(ArrayList<GUICard> lstPlayedCards) {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(ClientServerMessenger.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList<Integer> result = new ArrayList<Integer>();
GUICard losercard = this.findLoserCard(lstPlayedCards);
String loser = this.manager.getGamblerByArrayIndex(losercard.owner).getName();
for (int i = 0; i < lstPlayedCards.size(); i++) {
GUICard card = lstPlayedCards.get(i);
int guiID = card.toCardID();
result.add(guiID);
System.out.println(String.format("Server said Client %s receive card rank=%d, suit=%d.", loser, card.rank, card.suit));
}
testTakenCard(result, loser);
return losercard.owner;
}
private GUICard findLoserCard(ArrayList<GUICard> input) {
ArrayList<GUICard> list = (ArrayList<GUICard>) input.clone();
ArrayList<GUICard> result = new ArrayList<GUICard>();
GUICard first = list.get(0);
for (int i = 0; i < list.size(); i++) {
GUICard card = list.get(i);
if (card.suit == first.suit) {
result.add(card);
}
}
Collections.sort(result);
return result.get(result.size() - 1);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
/**
*
* @author Green
*/
public class MotionManager {
ArrayList<Motion> lstMotions = new ArrayList<Motion>();
public void addMotion_DealCard(GUICard card, Gambler targetGambler) {
card.owner = targetGambler.getID();
Point target = targetGambler.getNextPosition();
Motion motion = new Motion(card, target, targetGambler, Motion.MType.Deal);
this.lstMotions.add(motion);
}
public void addMotion_PlayCard(GUICard card, Gambler gambler, Banker banker) {
card.owner = -1;
Motion motion = new Motion(card, banker.nextPosition(gambler.getID()), banker, Motion.MType.Play);
this.lstMotions.add(motion);
}
public void addMotion_TakenCard(GUICard card, Gambler targetGambler) {
card.owner = targetGambler.getID();
Point target = targetGambler.getNextPosition_TakenCard();
Motion motion = new Motion(card, target, targetGambler, Motion.MType.Lose);
this.lstMotions.add(motion);
}
public void update() {
for (int i = 0; i < this.lstMotions.size(); i++) {
Motion motion = this.lstMotions.get(i);
motion.update();
if (motion.isFinished()) {
this.lstMotions.remove(motion);
motion.notifyReceiver();
}
}
}
public void draw(Graphics g) {
for (int i = 0; i < this.lstMotions.size(); i++) {
Motion motion = this.lstMotions.get(i);
motion.draw(g);
}
}
public void clear() {
this.lstMotions.clear();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Server.java
*
* Created on Jun 26, 2011, 10:00:34 PM
*/
package GUI;
/**
*
* @author Green
*/
public class Server extends javax.swing.JFrame {
/** Creates new form Server */
public Server() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Server().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import MiddleLayer.Card;
import MiddleLayer.Cards;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
/**
*
* @author Green
*/
public class Gambler implements IMotionFinish {
//public static
private String strName;
private int iID;
public ArrayList<GUICard> lstAvailableCards;
public ArrayList<GUICard> lstTakenCards;
int nAvailCardsOnTheWay = 0;
int nTakenCardsOnTheWay = 0;
public ArrayList<GUICard> lstCardsToPass;
//Vị trí góc trên trái của quân bài đầu tiên.
//Dùng để sắp xếp bài bắt đầu từ vị trí này
public Point position;
//Hướng để xếp bài
public Point direction;
//Hướng đến banker
public Point bankerDirection;
//Vị trí đặt tên
public Point namePosition;
//Khoảng cách chồng lên nhau giữa 2 lá bài liên tiếp
public Point overlap = new Point(20, 66);
public Point noname = new Point(GUICard.width / 2, 20);
Font font = new Font("Arial", Font.BOLD, 16);
//Tên của người chơi được cấp bởi Server.
//Chỉ dùng để hiển thị cho người chơi thấy tên của những người khác.
public String getName() {
return this.strName;
}
public void setName(String name) {
this.strName = name;
}
//ID của người chơi được cấp bởi Server
//Dùng phân biệt người chơi trong quá trình xử lý,truyền nhận Client-Server
public int getID() {
return iID;
}
public void setID(int id) {
this.iID = id;
}
public boolean isReadyToPass() {
return this.lstCardsToPass.size() == 3;
}
public Gambler(int id, String name) {
this.strName = name;
this.iID = id;
this.lstAvailableCards = new ArrayList<GUICard>();
this.lstTakenCards = new ArrayList<GUICard>();
this.lstCardsToPass = new ArrayList<GUICard>();
}
public void receiveCard(GUICard card) {
this.lstAvailableCards.add(card);
}
//Xui bị dính
public void receiveLostCards(ArrayList<GUICard> list) {
for (int i = 0; i < list.size(); i++) {
GUICard card = list.get(i);
if (card.suit == GUICard.HEARTS || card.isQueenOfSpade()) {
this.lstTakenCards.add(card);
continue;
}
}
this.sortTakenCards();
}
//Kiểm tra card có hợp lệ ko (chỉ đầm bích và bộ cơ)
public void receiveLostCard(GUICard card) {
if (card.suit == GUICard.HEARTS || card.isQueenOfSpade()) {
this.lstTakenCards.add(card);
this.sortTakenCards();
}
}
public void receivePassedCards(ArrayList<GUICard> list) {
this.lstAvailableCards.addAll(list);
this.sortAvailCards();
this.lstCardsToPass.clear();
}
private void removedPassedCards() {
this.lstAvailableCards.removeAll(this.lstCardsToPass);
}
public void selectCardToPass(Point mousePosition) {
GUICard card = this.getHitCard(mousePosition);
if (card == null) {
return;
}
//Nếu card này được chọn và nếu nó đã co trong ds được chọn
//thì việc click thêm cai nữa vào nó sẽ được hiểu là ko chọn nó nữa
int index = this.lstCardsToPass.indexOf(card);
if (index != -1) {
this.lstCardsToPass.remove(card);
this.moveDown(card);
} else {
if (this.lstCardsToPass.size() < 3) {
this.lstCardsToPass.add(card);
this.moveUp(card);
}
}
}
public void selectCardToPass(ArrayList<GUICard> list) {
for (int i = this.lstAvailableCards.size() - 1; i >= 0; i--) {
GUICard card = this.lstAvailableCards.get(i);
for (int j = 0; j < list.size(); j++) {
GUICard fake = list.get(j);
if (card.compareTo(fake) == 0) {
int index = this.lstCardsToPass.indexOf(card);
if (index != -1) {
this.moveDown(card);
} else {
this.lstCardsToPass.add(card);
this.moveUp(card);
}
break;
}
}
}
}
public void selectCardToPass(int rank, int suit) {
GUICard card = this.findCardInAvailList(rank, suit);
assert card == null : "selectCardToPass: card == null";
if(card == null)
return;
//Nếu card này được chọn và nếu nó đã co trong ds được chọn
//thì việc click thêm cai nữa vào nó sẽ được hiểu là ko chọn nó nữa
int index = this.lstCardsToPass.indexOf(card);
if (index != -1) {
this.moveDown(card);
} else {
this.lstCardsToPass.add(card);
this.moveUp(card);
}
}
public GUICard findCardInAvailList(int rank, int suit) {
for (int i = 0; i < this.lstAvailableCards.size(); i++) {
GUICard card = this.lstAvailableCards.get(i);
if (card.rank == rank && card.suit == suit) {
return card;
}
}
return null;
}
public ArrayList<GUICard> findCardsInAvailList(int suit) {
ArrayList<GUICard> result = new ArrayList<GUICard>();
for (int i = 0; i < this.lstAvailableCards.size(); i++) {
GUICard card = this.lstAvailableCards.get(i);
if (card.suit == suit) {
result.add(card);
}
}
return result;
}
public ArrayList<GUICard> findCardsInAvailListExcept(int suit) {
ArrayList<GUICard> result = new ArrayList<GUICard>();
for (int i = 0; i < this.lstAvailableCards.size(); i++) {
GUICard card = this.lstAvailableCards.get(i);
if (card.suit != suit) {
result.add(card);
}
}
return result;
}
public ArrayList<GUICard> popAllsSelectedCards() {
this.moveDown3SelectedCards();
ArrayList<GUICard> list = (ArrayList<GUICard>) this.lstCardsToPass.clone();
this.removedPassedCards();
return list;
// from.moveDown3SelectedCards();
// to.moveDown3SelectedCards();
//
// ArrayList<GUICard> list_from = (ArrayList<GUICard>) from.lstCardsToPass.clone();
// ArrayList<GUICard> list_to = (ArrayList<GUICard>) to.lstCardsToPass.clone();
// from.removedPassedCards();
// from.receivePassedCards(list_to);
// to.removedPassedCards();
// to.receivePassedCards(list_from);
}
public void moveDown3SelectedCards() {
for (int i = 0; i < this.lstCardsToPass.size(); i++) {
GUICard card = this.lstCardsToPass.get(i);
this.moveDown(card);
}
}
private void moveUp(GUICard card) {
int x = card.position.x + this.noname.x * this.bankerDirection.x;
int y = card.position.y + this.noname.y * this.bankerDirection.y;
card.position.x = x;
card.position.y = y;
}
private void moveDown(GUICard card) {
if (this.bankerDirection.x != 0) {
card.position.x = this.position.x;
}
if (this.bankerDirection.y != 0) {
card.position.y = this.position.y;
}
}
public void playCard(int rank, int suit, Banker banker) {
GUICard card = this.findCardInAvailList(rank, suit);
assert card == null : "Card is not exist in Gambler's list";
card.setSide(true);
Hearts.motionManager.addMotion_PlayCard(card, this, banker);
this.lstAvailableCards.remove(card);
this.sortAvailCards();
}
public GUICard getHitCard(Point mousePosition) {
for (int i = this.lstAvailableCards.size() - 1; i >= 0; i--) {
GUICard card = this.lstAvailableCards.get(i);
if (card.hit(mousePosition)) {
return card;
}
}
return null;
}
public void sortAvailCards() {
Collections.sort(this.lstAvailableCards);
this.rearrangePosition(this.lstAvailableCards);
}
public void sortTakenCards() {
Collections.sort(this.lstTakenCards);
this.rearrangePosition(this.lstTakenCards);
}
private void rearrangePosition(ArrayList<GUICard> list) {
for (int i = 0; i < list.size(); i++) {
int x = this.position.x + (GUICard.width - this.overlap.x) * i * this.direction.x;
int y = this.position.y + (GUICard.height - this.overlap.y) * i * this.direction.y;
GUICard card = list.get(i);
card.position = new Point(x, y);
}
}
public Point getNextPosition() {
Point p = new Point();
int i = this.nAvailCardsOnTheWay;
this.nAvailCardsOnTheWay++;
p.x = this.position.x + i * (GUICard.width - this.overlap.x) * this.direction.x;
p.y = this.position.y + i * (GUICard.height - this.overlap.y) * this.direction.y;
return p;
}
public Point getNextPosition_TakenCard() {
Point p = new Point();
int i = this.nTakenCardsOnTheWay;
this.nTakenCardsOnTheWay++;
p.x = this.position.x + i * (GUICard.width - this.overlap.x) * this.direction.x;
p.y = this.position.y + i * (GUICard.height - this.overlap.y) * this.direction.y;
return p;
}
/**
*
* @return Trả về giá trị id theo CardID (Lớp bên dưới)
*/
public Cards getGamblerCards() {
Cards c = new Cards();
for (int i = 0; i < this.lstAvailableCards.size(); i++) {
GUICard guicard = this.lstAvailableCards.get(i);
c.addCard(Card.convertCardGUI_IDToCard_ID(guicard.toCardID()));
}
return c;
}
public void showAllsAvailsCard() {
for (int i = 0; i < this.lstAvailableCards.size(); i++) {
GUICard card = this.lstAvailableCards.get(i);
card.setSide(true);
}
}
public void hideAllsAvailsCard() {
for (int i = 0; i < this.lstAvailableCards.size(); i++) {
GUICard card = this.lstAvailableCards.get(i);
card.setSide(false);
}
}
public void drawAllsCards(Graphics g) {
for (int i = 0; i < this.lstAvailableCards.size(); i++) {
GUICard card = this.lstAvailableCards.get(i);
card.draw(g);
}
}
public void drawTakenCard(Graphics g) {
for (int i = 0; i < this.lstTakenCards.size(); i++) {
GUICard card = this.lstTakenCards.get(i);
card.draw(g);
}
}
public void drawName(Graphics g) {
Color oldColor = g.getColor();
Font oldFont = g.getFont();
g.setColor(Color.RED);
g.setFont(font);
g.drawString(strName, this.namePosition.x, this.namePosition.y);
g.setColor(oldColor);
g.setFont(oldFont);
}
public void reset() {
this.lstAvailableCards.clear();
this.lstCardsToPass.clear();
this.lstTakenCards.clear();
this.nAvailCardsOnTheWay = 0;
this.nTakenCardsOnTheWay = 0;
}
public void end(Motion motion) {
Motion.MType type = motion.getType();
GUICard card = motion.getCard();
if (type == Motion.MType.Lose) {
this.receiveLostCard(card);
return;
}
if (type == Motion.MType.Deal) {
this.receiveCard(card);
if (this.lstAvailableCards.size() == 13) {
this.nAvailCardsOnTheWay = 0;
this.sortAvailCards();
if (this.iID == 0)//player)
{
this.showAllsAvailsCard();
}
}
return;
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.Random;
/**
*
* @author Green
*/
public class Deck {
public static BufferedImage cardsuittexture;
public static BufferedImage backfacetexture;
private static ArrayList<GUICard> lstSampleCards = new ArrayList<GUICard>();
public ArrayList<GUICard> lstCards = new ArrayList<GUICard>();
private static int width;
private static int height;
public static void setWidth(int w) {
width = w;
}
public static void setHeight(int h) {
height = h;
}
public Deck() {
this.loadSampleCards();
this.loadNewCards();
}
// public static loadResource() {
// width = 71;
// height = 96;
// cardsuittexture = Toolkit.getDefaultToolkit().getImage((getClass().getResource("Images/StandardDeck.gif")));
// backfacetexture = Toolkit.getDefaultToolkit().getImage((getClass().getResource("Images/backfacecard.png")));
// Card.width = width;
// Card.height = height;
// }
private void loadSampleCards() {
lstSampleCards.clear();
for (int i = 0; i < 4; i++) {
ArrayList<GUICard> cardSuit = this.loadCardSuit(i);
lstSampleCards.addAll(i * 13, cardSuit);
}
}
public void loadNewCards() {
this.reset();
}
private ArrayList<GUICard> loadCardSuit(int suit) {
ArrayList<GUICard> cardSuit = new ArrayList<GUICard>();
int yPos = suit;
switch (suit) {
case 0:
yPos = 3;
break;
case 1:
yPos = 0;
break;
case 2:
yPos = 1;
break;
case 3:
yPos = 2;
break;
}
for (int i = 0; i < 13; i++) {
int k = i;
if (i == 0) {
BufferedImage bImg = cardsuittexture.getSubimage(12 * (GUICard.width + 1), yPos * (GUICard.height + 1), GUICard.width, GUICard.height);
GUICard card = new GUICard(suit, 12, bImg, backfacetexture);// rank = i + 1 nhé
cardSuit.add(card);
} else {
k = i - 1;
BufferedImage bImg = cardsuittexture.getSubimage(i * (GUICard.width + 1), yPos * (GUICard.height + 1), GUICard.width, GUICard.height);
GUICard card = new GUICard(suit, k, bImg, backfacetexture);// rank = i + 1 nhé
cardSuit.add(card);
}
}
return cardSuit;
}
public void shuffle() {
Calendar calendar = new GregorianCalendar();
long seed = calendar.getTime().getSeconds();
Random rand = new Random(seed);
Collections.shuffle(lstCards, rand);
}
public void reset() {
this.lstCards.clear();
for (int i = 0; i < 52; i++) {
GUICard card = lstSampleCards.get(i).clone();
this.lstCards.add(card);
}
}
public GUICard getCard(int rank, int suit) {
for (int i = 0; i < 52; i++) {
GUICard card = this.lstCards.get(i);
if (card.rank == rank && card.suit == suit) {
this.lstCards.remove(card);
return card;
}
}
return null;
}
public void drawBackFace(Graphics g, int x, int y) {
g.drawImage(backfacetexture, x, y, null);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import java.awt.Graphics;
import java.awt.Point;
/**
*
* @author Green
*/
public class Motion {
public enum MType {
Deal, Play, Lose
};
private GUICard card;
private Point target;
private boolean finished = false;
private int speed = 12;
private MType type;
private IMotionFinish receiver;
public GUICard getCard() {
return card;
}
public MType getType() {
return type;
}
public Motion(GUICard card, Point target, IMotionFinish receiver, MType type) {
this.card = card;
this.target = target;
this.type = type;
this.receiver = receiver;
}
public boolean isFinished() {
return this.finished;
}
public void update() {
if (this.finished) {
return;
}
int dx = this.target.x - this.card.position.x;
int dy = this.target.y - this.card.position.y;
int steps;
float xIncre, yIncre;
if (Math.abs(dx) > Math.abs(dy)) {
steps = Math.abs(dx);
} else {
steps = Math.abs(dy);
}
xIncre = (dx / (float) steps) * speed;
yIncre = (dy / (float) steps) * speed;
this.card.position.x += xIncre;
this.card.position.y += yIncre;
double l = Point.distance(this.card.position.x, this.card.position.y, this.target.x, this.target.y);
if (l < speed) {
this.card.position = (Point)this.target.clone();
this.finished = true;
}
}
public void draw(Graphics g) {
if (this.finished) {
return;
}
this.card.draw(g);
}
public void notifyReceiver() {
this.receiver.end(this);
}
}
| Java |
package GUI;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class GamePanel extends JPanel {
// private GameApplet ga;
private Game game;
private boolean paused = false;
UpdateThread thread;
//the time in miliseconds between every repaint.
private int sleeptime = 40;
public JButton button = new JButton();
public GamePanel(Game g) {
game = g;
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
game.mousePressed(e);
}
@Override
public void mouseClicked(MouseEvent e) {
game.mouseClicked(e);
}
@Override
public void mouseReleased(MouseEvent e) {
game.mouseReleased(e);
}
@Override
public void mouseEntered(MouseEvent e) {
game.mouseEntered(e);
}
@Override
public void mouseExited(MouseEvent e) {
game.mouseExited(e);
}
});
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
game.keyPressed(e);
}
@Override
public void keyTyped(KeyEvent e) {
game.keyTyped(e);
}
@Override
public void keyReleased(KeyEvent e) {
game.keyReleased(e);
}
});
this.setLayout(null);
ImageIcon icon = new ImageIcon(ImageUtility.loadImageFromResource_("Images/pass_arrow_small.png"));
button.setIcon(icon);
button.setVisible(true);
this.add(button);
button.setMargin(new Insets(0, 0, 0, 0));
button.setBounds(500, 360, 54, 32);
this.validate();
this.button.addActionListener(this.game);
}
public void setPause(boolean p) {
paused = p;
}
public void start() {
thread = new UpdateThread(this);
thread.start();
this.paused = false;
}
public void setSleepTime(int ms) {
sleeptime = ms;
}
public void stop() {
game.stop();
}
public boolean isPaused() {
return paused;
}
@Override
public void paint(Graphics g) {
// System.out.println(Thread.currentThread().getId());
//Fills everything with background color.
//You might want to skip this part if you do not need to clear the panel every frame
//To do this, add an abstract method to Game, called "public boolean clearPanel()" that
//will tell whether the panel should be cleared.
Color c = game.getBackgroundColor();
if (c != null) {
g.setColor(c);
g.fillRect(0, 0, getWidth(), getHeight());
}
game.paintGame(g);
this.paintComponents(g);
}
public void showPassButton(boolean flag) {
if (flag != this.button.isVisible()) {
this.button.setVisible(flag);
}
}
public void enablePassButton(boolean flag) {
if (flag != this.button.isEnabled()) {
this.button.setEnabled(flag);
}
}
public boolean isPassButtonEnable() {
return this.button.isEnabled();
}
public boolean isPassButtonVisible() {
return this.button.isVisible();
}
class UpdateThread extends Thread {
private GamePanel gp;
UpdateThread(GamePanel g) {
gp = g;
}
@Override
public void run() {
while (true) {
try {
sleep(sleeptime);
} catch (Exception e) {
e.printStackTrace(System.err);
}
if (!gp.isPaused()) {
gp.game.updateGame();
gp.repaint();
}
}
}
}
}
| Java |
package GUI;
import MiddleLayer.ClientProcessing;
import MiddleLayer.ClientServerMessenger;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.image.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
public abstract class Game implements ActionListener {
GamePanel gp;
ClientProcessing clientMessenger;
public final void setup(GamePanel g, ClientProcessing mess) {
gp = g;
this.clientMessenger = mess;
init();
}
//Override this method if you want to do something before the game starts.
public void init() {
}
//Override this method for updating game logic.
public abstract void updateGame();
//You must override this method. In it, you should first update the game status,
//And then paint in the screen using Graphics g.
public abstract void paintGame(Graphics g);
//This method will be called whenver the aplet is closed. Override it if you want to do
//something before closing the applet.
public void stop() {
}
//Use this method to set the time that will pass between every frame refresh.
//It is in milliseconds
public final void setSleepTime(int ms) {
gp.setSleepTime(ms);
}
//Use this method to set the width and height of your game panel. I recommend to use this
//method only in the beggining of the game, because resizing the dimensions can mess up
//some game variables.
public final void resize(int w, int h) {
// applet.resize(w, h);
gp.setSize(w, h);
}
//Use this method to import images you made into the game. I would reccomend using
//.png images if you need transparency, and .jpg images if you need to save storage space
//and decrease loading times.
//Null will be returned if the program will not find the image.
public final Image readBufferedImage(String name) {
try {
// Image i = applet.getImage(applet.getCodeBase(), name);
Image i = Toolkit.getDefaultToolkit().getImage((getClass().getResource(name)));
return i;
} catch (Exception e) {
e.printStackTrace(System.err);
}
return null;
}
//Override this method if you want to set the background color yourself.
//The default color is black. This method is being called every time the
//screen is redrawn. If null will be returned, no background will be drawn.
//Ise this to save efficiency.
public Color getBackgroundColor() {
return Color.black;
}
//A useful method to determine the mouse position. Note that null will be returned
//if the mouse is not in the GamPanel, so check it before you use it.
public final Point getMousePosition() {
return gp.getMousePosition();
}
//The next five are mouse input methods. Override them to handle mouse input.
//Use the methods of MouseEvent to find information about the mouse position
//and what button was clicked.
public void mousePressed(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
//The next three are keyboard input methods. Override them to handle keyboard input
//use KeyEvent methods to find out what key was pressed
public void keyPressed(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
//A method for setting mouse cursors. You need to supply the image you want to use as
//cursor, the hotspot (the actual point in the image which is where the mouse points. For
//regular cursors (0,0) will be fine, but use the cnter of the image for a crosshair cursor),
// and the cursor name (I do not think that it affects anything)
//If there will be a problem with the image, a transparent cursor will be set.
//You can also use the setTransparentCursor method, and then use getMousePosition in
//the paint method to draw something wherever the cursor is. I would reccomend this option
//if you want the mouse cursor to change (animated cursor).
public final void setCursor(Image i, Point hotspot, String name) {
if (i == null) {
setTransparentCursor();
return;
}
gp.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(i, hotspot, name));
}
//Sets a transparent mouse cursor (making it invisible).
public final void setTransparentCursor() {
int[] pixels = new int[16 * 16];
Image image = Toolkit.getDefaultToolkit().createImage(
new MemoryImageSource(16, 16, pixels, 0, 16));
gp.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisiblecursor"));
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
/**
*
* @author Green
*/
public class GUICard implements Comparable<GUICard> {
public static final int SPADES = 0;//bích
public static final int HEARTS = 3;//cơ
public static final int DIAMONDS = 2;//rô
public static final int CLUBS = 1;//chuồn
public static int width;
public static int height;
public int suit;//Spades,Clubs...
public int rank;//1,2,3,..,10,11,12,13.
public boolean isUpSide;//true = ngửa
public Point position;
public int owner;
private boolean isVisible = true;
private BufferedImage texture;
private BufferedImage backSide;
public void setVisible(boolean b) {
this.isVisible = b;
}
public boolean getSide() {
return this.isUpSide;
}
public void setSide(boolean up) {
this.isUpSide = up;
}
public GUICard(int suit, int rank, BufferedImage texture, BufferedImage backside) {
this.suit = suit;
this.rank = rank;
this.isUpSide = false;//ko ngửa
this.position = new Point(0, 0);
this.texture = texture;
this.backSide = backside;
}
public void draw(Graphics g) {
if(!this.isVisible)
return;
if(isUpSide)
g.drawImage(texture, position.x, position.y, null);
else
g.drawImage(backSide, position.x, position.y, null);
}
public int compareTo(GUICard o) {
if (this.suit > o.suit) {
return 1;
} else if (this.suit < o.suit) {
return -1;
}
if(this.rank == 0)//ace
return 1;
if(o.rank == 0)//ace
return -1;
if (this.rank > o.rank) {
return 1;
}
if(this.rank < o.rank) {
return -1;
}
return 0;
}
public boolean isSameSuit(GUICard another){
return this.suit == another.suit;
}
public boolean isQueenOfSpade() {
return this.suit == GUICard.SPADES && this.rank == 12;
}
public boolean isTwoOfClub() {
return this.suit == GUICard.CLUBS && this.rank == 0;
}
public boolean hit(Point mousePosition) {
if(this.position.x < mousePosition.x && this.position.x + GUICard.width > mousePosition.x)
{
if(this.position.y < mousePosition.y && this.position.y + GUICard.height > mousePosition.y)
{
return true;
}
}
return false;
}
public int toCardID() {
int id = this.suit * 13 + this.rank;
return id;
}
public GUICard clone() {
GUICard card = new GUICard(suit, rank, texture, backSide);
return card;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
/**
*
* @author Green
*/
public class GamblerManager {
ArrayList<Gambler> lstGamblers;
Gambler player;
int screenWidth = 0;
int screenHeight = 0;
//Lấy thằng do client điều khiển ra
public Gambler getMainPlayer() {
return this.player;
}
public GamblerManager(int width, int height) {
this.screenWidth = width;
this.screenHeight = height;
this.lstGamblers = new ArrayList<Gambler>(4);
this.initGamblers();
this.player = this.lstGamblers.get(0);
}
private void initGamblers() {
Gambler gambler = new Gambler(0, "");
gambler.position = new Point();
gambler.position.x = (this.screenWidth - (GUICard.width - gambler.overlap.x) * 12 - GUICard.width) / 2;
gambler.position.y = this.screenHeight - GUICard.height - 20;
gambler.namePosition = new Point();
gambler.namePosition.x = gambler.position.x;
gambler.namePosition.y = gambler.position.y - 10;
gambler.direction = new Point(1, 0);
gambler.bankerDirection = new Point(0, -1);
this.lstGamblers.add(gambler);
gambler = new Gambler(1, "");
gambler.position = new Point();
gambler.position.x = 40;
gambler.position.y = (this.screenHeight - (GUICard.height - gambler.overlap.y) * 12 - GUICard.height) / 2;
gambler.namePosition = new Point();
gambler.namePosition.x = gambler.position.x;
gambler.namePosition.y = gambler.position.y - 4;
gambler.direction = new Point(0, 1);
gambler.bankerDirection = new Point(1, 0);
this.lstGamblers.add(gambler);
gambler = new Gambler(2, "");
gambler.position = new Point();
gambler.position.x = (this.screenWidth - (GUICard.width - gambler.overlap.x) * 12 - GUICard.width) / 2;
gambler.position.y = 20;
gambler.namePosition = new Point();
gambler.namePosition.x = gambler.position.x;
gambler.namePosition.y = gambler.position.y - 4;
gambler.direction = new Point(1, 0);
gambler.bankerDirection = new Point(0, 1);
this.lstGamblers.add(gambler);
gambler = new Gambler(3, "");
gambler.position = new Point();
gambler.position.x = this.screenWidth - GUICard.width - 40;
gambler.position.y = (this.screenHeight - (GUICard.height - gambler.overlap.y) * 12 - GUICard.height) / 2;
gambler.namePosition = new Point();
gambler.namePosition.x = gambler.position.x;
gambler.namePosition.y = gambler.position.y - 4;
gambler.direction = new Point(0, 1);
gambler.bankerDirection = new Point(-1, 0);
this.lstGamblers.add(gambler);
}
public void initPlayers(String clientName, ArrayList<String> allsClientsName) {
int playerIndex = allsClientsName.indexOf(clientName);
assert playerIndex == -1 : "Invalid client's name";
int i = 0;
ArrayList<String> list = (ArrayList<String>) allsClientsName.clone();
while (list.size() > 1) {
Gambler gambler = this.lstGamblers.get(i);
gambler.setName(list.get(playerIndex));
list.remove(playerIndex);
i++;
}
// i = playerIndex;
for (int j = 0; j < list.size(); j++) {
i = i % 4;
Gambler gambler = this.lstGamblers.get(i);
gambler.setName(list.get(j));
list.remove(j);
i++;
}
i = playerIndex;
}
public Gambler getGambler(String name) {
for (int i = 0; i < this.lstGamblers.size(); i++) {
Gambler gambler = this.lstGamblers.get(i);
if (gambler.getName() == name) {
return gambler;
}
}
return null;
}
public Gambler getGamblerByArrayIndex(int arrayIndex) {
if(arrayIndex < 0 || arrayIndex >= this.lstGamblers.size()) {
return null;
}
return this.lstGamblers.get(arrayIndex);
}
public int getArrayIndexOfGambler(Gambler gambler) {
return this.lstGamblers.indexOf(gambler);
}
public void passCards(int direction) {
switch (direction) {
case 0: {
passLeft();
break;
}
case 1: {
passRight();
break;
}
case 2: {
passUp();
break;
}
}
}
private void passLeft() {
ArrayList<GUICard> list = new ArrayList<GUICard>();
ArrayList<GUICard> anotherlist = new ArrayList<GUICard>();
ArrayList<Gambler> glist = new ArrayList<Gambler>(this.lstGamblers);
glist.remove(0);
list = player.popAllsSelectedCards();
for (int i = 0; i < 3; i++) {
Gambler from = glist.get(i);
anotherlist = from.popAllsSelectedCards();
from.receivePassedCards(list);
list = anotherlist;
from.hideAllsAvailsCard();
}
player.receivePassedCards(list);
player.showAllsAvailsCard();
}
private void passRight() {
ArrayList<GUICard> list = new ArrayList<GUICard>();
ArrayList<GUICard> anotherlist = new ArrayList<GUICard>();
ArrayList<Gambler> glist = new ArrayList<Gambler>(this.lstGamblers);
glist.remove(0);
list = player.popAllsSelectedCards();
for (int i = 3; i >= 0; i--) {
Gambler from = glist.get(i);
anotherlist = from.popAllsSelectedCards();
from.receivePassedCards(list);
list = anotherlist;
from.hideAllsAvailsCard();
}
player.receivePassedCards(list);
player.showAllsAvailsCard();
}
private void passUp() {
ArrayList<Gambler> glist = new ArrayList<Gambler>(this.lstGamblers);
for (int i = 0; i < 4; i += 2) {
Gambler from = this.lstGamblers.get(i);
Gambler to = this.lstGamblers.get(i);
ArrayList<GUICard> list_from = from.popAllsSelectedCards();
ArrayList<GUICard> list_to = to.popAllsSelectedCards();
from.receivePassedCards(list_to);
to.receivePassedCards(list_from);
if(i == 0) {
from.showAllsAvailsCard();
to.hideAllsAvailsCard();
} else {
from.hideAllsAvailsCard();
to.hideAllsAvailsCard();
}
}
}
public void turnUpPlayersCards() {
this.player.showAllsAvailsCard();
}
public void drawAllsCards(Graphics g) {
for (int i = 0; i < this.lstGamblers.size(); i++) {
Gambler gambler = this.lstGamblers.get(i);
gambler.drawAllsCards(g);
}
}
public void drawAllsNames(Graphics g) {
for (int i = 0; i < this.lstGamblers.size(); i++) {
Gambler gambler = this.lstGamblers.get(i);
gambler.drawName(g);
}
}
public void drawAllsTakenCards(Graphics g) {
for (int i = 0; i < this.lstGamblers.size(); i++) {
Gambler gambler = this.lstGamblers.get(i);
gambler.drawTakenCard(g);
}
}
public void resetAllsGamblers() {
for (int i = 0; i < this.lstGamblers.size(); i++) {
Gambler gambler = this.lstGamblers.get(i);
gambler.reset();
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
/**
*
* @author Green
*/
public class Banker implements IMotionFinish {
private Deck deck;
public Point position;
public ArrayList<GUICard> lstCardsOnTable;
private ArrayList<Point> lstPlayedCardPosition;
int nCardOnTheWay = 0;
private GamePanel gp;
public Banker(GamePanel gp) {
this.deck = new Deck();
this.gp = gp;
this.position = new Point();
this.position.x = gp.getWidth() / 2 - GUICard.width / 2;
this.position.y = gp.getHeight() / 2 - GUICard.height / 2;
this.lstCardsOnTable = new ArrayList<GUICard>(4);
this.lstPlayedCardPosition = new ArrayList<Point>(4);
this.initCardPosition();
}
private void initCardPosition() {
Point begPoint = new Point(gp.getWidth() / 2 - GUICard.width / 2, gp.getHeight() / 2 - GUICard.height);
Point p = new Point();
p.x = begPoint.x;
p.y = begPoint.y + GUICard.height - 10;
this.lstPlayedCardPosition.add(p);
p = new Point();
p.x = begPoint.x - GUICard.width + 10;
p.y = begPoint.y + GUICard.height / 2;
this.lstPlayedCardPosition.add(p);
p = new Point();
p.x = begPoint.x;
p.y = begPoint.y + 10;
this.lstPlayedCardPosition.add(p);
p = new Point();
p.x = begPoint.x + GUICard.width - 10;
p.y = begPoint.y + GUICard.height / 2;
this.lstPlayedCardPosition.add(p);
}
public void dealCard(int rank, int suit, Gambler gambler) {
GUICard card = this.deck.getCard(rank, suit);
Hearts.motionManager.addMotion_DealCard(card, gambler);
}
public void sendCardToLostGambler(int rank, int suit, Gambler gambler) {
GUICard card = this.getCardOnTable(rank, suit);
assert card == null : "whyyyyyyyyyyy";
if (card == null) {
return;
}
Hearts.motionManager.addMotion_TakenCard(card, gambler);
this.nCardOnTheWay--;
}
private GUICard getCardOnTable(int rank, int suit) {
for (int i = 0; i < this.lstCardsOnTable.size(); i++) {
GUICard card = this.lstCardsOnTable.get(i);
if (card.rank == rank && card.suit == suit) {
return card;
}
}
return null;
}
public GUICard getFirstCardOnBoard() {
if(this.lstCardsOnTable.size() == 0)
return null;
return this.lstCardsOnTable.get(0);
}
public boolean isCardAvailable(int rank, int suit) {
GUICard card = this.deck.getCard(rank, suit);
return card == null;
}
//Kiểm tra card này đánh ra có hợp lệ ko-cái này là demo thôi,cần phải có GameRule
//mới chính xác
public boolean isAcceptableCard( GUICard card) {
if(this.lstCardsOnTable.size() == 0) {
return true;
}
GUICard first = this.lstCardsOnTable.get(0);
if(card.isSameSuit(first))
return true;
return false;
}
public Point nextPosition(int id) {
// int i = this.nCardOnTheWay;
// this.nCardOnTheWay++;
Point p;
// if (i > 0) {
// i--;
// }
p = this.lstPlayedCardPosition.get(id);
return p;
}
public int countAvailableCard() {
return this.deck.lstCards.size();
}
public void drawOnBoardCards(Graphics g) {
for (int i = 0; i < this.lstCardsOnTable.size(); i++) {
GUICard card = this.lstCardsOnTable.get(i);
card.draw(g);
}
}
public void drawDecksBackFace(Graphics g) {
if (!this.deck.lstCards.isEmpty()) {
this.deck.drawBackFace(g, this.position.x, this.position.y);
}
}
public void reset() {
this.lstCardsOnTable.clear();
this.nCardOnTheWay = 0;
this.deck.reset();
for(int i = 0;i < 52;i++) {
GUICard card = this.deck.lstCards.get(i);
card.position = (Point)this.position.clone();
}
}
public void end(Motion motion) {
GUICard card = motion.getCard();
this.lstCardsOnTable.add(card);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* HeartsForm.java
*
* Created on Jun 26, 2011, 10:00:56 PM
*/
package GUI;
import MiddleLayer.HeartGame;
/**
*
* @author Green
*/
public class HeartsForm extends javax.swing.JFrame {
HeartGame app;
/** Creates new form HeartsForm */
public HeartsForm() {
initComponents();
app = new HeartGame();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btnCreateServer = new javax.swing.JButton();
btnJoin = new javax.swing.JButton();
btnExit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Hearts");
setResizable(false);
btnCreateServer.setText("Create Server");
btnCreateServer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCreateServerActionPerformed(evt);
}
});
btnJoin.setText("Join");
btnJoin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnJoinActionPerformed(evt);
}
});
btnExit.setText("Exit");
btnExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExitActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnCreateServer, javax.swing.GroupLayout.PREFERRED_SIZE, 319, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(130, 130, 130)
.addComponent(btnExit, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)
.addGap(126, 126, 126))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnJoin, javax.swing.GroupLayout.DEFAULT_SIZE, 319, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnCreateServer)
.addGap(18, 18, 18)
.addComponent(btnJoin)
.addGap(18, 18, 18)
.addComponent(btnExit)
.addContainerGap(15, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
// TODO add your handling code here:
System.exit(0);
}//GEN-LAST:event_btnExitActionPerformed
private void btnCreateServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateServerActionPerformed
// TODO add your handling code here:
Thread thread = new Thread(new Runnable() {
public void run() {
app.initServer();
}
}, "HeartGameMainThread");
this.setVisible(false);
thread.start();
}//GEN-LAST:event_btnCreateServerActionPerformed
private void btnJoinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnJoinActionPerformed
// TODO add your handling code here:
Thread thread = new Thread(new Runnable() {
public void run() {
app.connectToServer();
}
}, "HeartGameMainThread");
this.setVisible(false);
thread.start();
}//GEN-LAST:event_btnJoinActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new HeartsForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCreateServer;
private javax.swing.JButton btnExit;
private javax.swing.JButton btnJoin;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* @author Green
*/
public class ImageUtility {
private static ImageUtility instance = null;
public static ImageUtility getInstance() {
if(instance == null)
instance = new ImageUtility();
return instance;
}
public static BufferedImage loadImageFromResource(String path) {
ImageIcon imgi = new ImageIcon(new ImageUtility().getClass().getResource(path));
BufferedImage b = new BufferedImage(imgi.getIconWidth(), imgi.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = b.getGraphics();
g.drawImage(imgi.getImage(), imgi.getIconWidth(), imgi.getIconHeight(), null);
return b;
}
public static BufferedImage loadImageFromResource_(String path) {
URL url = ImageUtility.getInstance().getClass().getResource(path);
BufferedImage img = null;
try {
img = ImageIO.read(url);
} catch (IOException ex) {
Logger.getLogger(ImageUtility.class.getName()).log(Level.SEVERE, null, ex);
}
return img;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
/**
*
* @author Green
*/
public interface IMotionFinish {
public void end(Motion motion);
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* GameplayForm.java
*
* Created on Jun 18, 2011, 12:24:39 AM
*/
package GUI;
import MiddleLayer.ClientProcessing;
import MiddleLayer.ClientServerMessenger;
/**
*
* @author Green
*/
public class GameplayForm extends javax.swing.JFrame {
//cái game nó phụ thuộc vào panel này
private GamePanel gamePanel;
private Game game;
/** Creates new form GameplayForm */
public GameplayForm(ClientProcessing clientMessenger) {
initComponents();
this.setSize(1024, 760);
game = new Hearts();
gamePanel = new GamePanel(game);
game.setup(gamePanel, clientMessenger);
clientMessenger.setup(BottomPanel, (Hearts)game);//BottomPanel chứa cả khung chat và khung hiển thị thông tin
this.MainContent.add(gamePanel);
this.validate();
gamePanel.repaint();
gamePanel.requestFocus();
gamePanel.start();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
MainContent = new javax.swing.JPanel();
BottomPanel = new javax.swing.JPanel();
pnlChatting = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
ChatContent = new javax.swing.JTextArea();
txtMessageInput = new javax.swing.JTextField();
btnSend = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
pnlClientInfo = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
MainMenu = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Hearts");
setResizable(false);
MainContent.setName("MainContent"); // NOI18N
MainContent.setPreferredSize(new java.awt.Dimension(1024, 600));
javax.swing.GroupLayout MainContentLayout = new javax.swing.GroupLayout(MainContent);
MainContent.setLayout(MainContentLayout);
MainContentLayout.setHorizontalGroup(
MainContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1024, Short.MAX_VALUE)
);
MainContentLayout.setVerticalGroup(
MainContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 609, Short.MAX_VALUE)
);
BottomPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
BottomPanel.setName("BottomPanel"); // NOI18N
pnlChatting.setName("pnlChatting"); // NOI18N
ChatContent.setColumns(20);
ChatContent.setEditable(false);
ChatContent.setRows(4);
jScrollPane1.setViewportView(ChatContent);
btnSend.setText("Send");
javax.swing.GroupLayout pnlChattingLayout = new javax.swing.GroupLayout(pnlChatting);
pnlChatting.setLayout(pnlChattingLayout);
pnlChattingLayout.setHorizontalGroup(
pnlChattingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlChattingLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlChattingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 524, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlChattingLayout.createSequentialGroup()
.addComponent(txtMessageInput, javax.swing.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnSend)))
.addContainerGap())
);
pnlChattingLayout.setVerticalGroup(
pnlChattingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlChattingLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlChattingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtMessageInput, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnSend)))
);
BottomPanel.add(pnlChatting);
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
BottomPanel.add(jSeparator1);
pnlClientInfo.setName("pnlClientInfo"); // NOI18N
pnlClientInfo.setPreferredSize(new java.awt.Dimension(440, 100));
jLabel1.setText("jLabel1");
jLabel2.setText("jLabel2");
jLabel3.setText("jLabel3");
jLabel4.setText("jLabel4");
jLabel5.setText("jLabel5");
jLabel6.setText("jLabel6");
jLabel7.setText("jLabel7");
jLabel8.setText("jLabel8");
javax.swing.GroupLayout pnlClientInfoLayout = new javax.swing.GroupLayout(pnlClientInfo);
pnlClientInfo.setLayout(pnlClientInfoLayout);
pnlClientInfoLayout.setHorizontalGroup(
pnlClientInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlClientInfoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlClientInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlClientInfoLayout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel5))
.addGroup(pnlClientInfoLayout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jLabel6))
.addGroup(pnlClientInfoLayout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(jLabel7))
.addGroup(pnlClientInfoLayout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jLabel8)))
.addContainerGap(344, Short.MAX_VALUE))
);
pnlClientInfoLayout.setVerticalGroup(
pnlClientInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlClientInfoLayout.createSequentialGroup()
.addGroup(pnlClientInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlClientInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlClientInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlClientInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel8))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
BottomPanel.add(pnlClientInfo);
jMenu1.setText("File");
MainMenu.add(jMenu1);
jMenu2.setText("Edit");
MainMenu.add(jMenu2);
setJMenuBar(MainMenu);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(MainContent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(BottomPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 1024, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(MainContent, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BottomPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ClientProcessing clientMessenger = new ClientProcessing();
new GameplayForm(clientMessenger).setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel BottomPanel;
private javax.swing.JTextArea ChatContent;
private javax.swing.JPanel MainContent;
private javax.swing.JMenuBar MainMenu;
private javax.swing.JButton btnSend;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JPanel pnlChatting;
private javax.swing.JPanel pnlClientInfo;
private javax.swing.JTextField txtMessageInput;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import MiddleLayer.Card;
import MiddleLayer.GameRules;
import MiddleLayer.OtherClass.CommandStruct.MessageType;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
/**
*
* @author Green
*/
public class Hearts extends Game {
//private BufferedImage background;
//private BufferedImage img;
// private ClientProcessing client = new ClientProcessing();
//Những trạng thái theo từng giai đoạn:
//khởi đầu(thiết lập các biến cần thiết cho 1 ván mới),
//chia bài,
//pass bài,
//chơi bài(đang trong quá trình chơi),
//kết thúc (hiện điểm,hiện bài bị nhận,hiện người thua nếu có).
public enum GameState {
Begining, Dealing, Passing, Playing, Ending
};
public enum PlayerState {
DoNothing, Pass, PlayCard
};
private Banker banker;
private GameState currentState;
private PlayerState playerState;
private GamblerManager gManager;
public static MotionManager motionManager = new MotionManager();
public boolean isFirstTurn = false;
private boolean isFinishedTask = true;
ArrayList<ImageIcon> lstIconForPassButton = new ArrayList<ImageIcon>();
public GameState getCurrentState() {
return currentState;
}
public void setCurrentState(GameState currentState) {
this.currentState = currentState;
this.isFinishedTask = false;
if (currentState == GameState.Passing) {
this.playerState = PlayerState.Pass;
} else {
if (currentState == GameState.Playing) {
this.playerState = PlayerState.PlayCard;
} else {
this.playerState = PlayerState.DoNothing;
}
}
}
public PlayerState getPlayerState() {
return playerState;
}
public void setPlayerState(PlayerState playerState) {
this.playerState = playerState;
}
public Hearts() {
motionManager.clear();
}
@Override
public void init() {
this.gp.setSize(1024, 540);
this.loadResources();
this.gManager = new GamblerManager(this.gp.getWidth(), this.gp.getHeight());
this.banker = new Banker(this.gp);
this.currentState = GameState.Begining;
this.playerState = PlayerState.DoNothing;
this.gp.showPassButton(false);
}
@Override
public void updateGame() {
motionManager.update();
if (this.currentState == GameState.Begining) {
}
if (this.currentState == GameState.Dealing) {
if (this.isFinishedTask) {
return;
}
System.out.println("Dealing : " + banker.countAvailableCard());
if (banker.countAvailableCard() == 0) {
//this.clientMessenger.finishTask(currentState);
this.isFinishedTask = true;
}
}
if (this.currentState == GameState.Passing) {
if (this.isFinishedTask) {
return;
}
if (this.gManager.getMainPlayer().isReadyToPass()) {
if (!this.gp.isPassButtonEnable()) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
gp.enablePassButton(true);
}
});
}
} else {
if (this.gp.isPassButtonEnable()) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
gp.enablePassButton(false);
}
});
}
}
}
if (this.currentState == GameState.Playing) {
if (this.isFinishedTask) {
return;
}
}
if (this.currentState == GameState.Ending) {
if (this.isFinishedTask) {
return;
}
}
}
@Override
public void paintGame(Graphics g) {
// throw new UnsupportedOperationException("Not supported yet.");
Color c = new Color(0, 160, 0);
Color oldColor = g.getColor();
g.setColor(c);
g.fillRect(0, 0, this.gp.getWidth(), this.gp.getHeight());
g.setColor(oldColor);
if (this.currentState == GameState.Begining) {
}
if (this.currentState == GameState.Dealing) {
this.banker.drawDecksBackFace(g);
this.gManager.drawAllsCards(g);
}
if (this.currentState == GameState.Passing) {
this.gManager.drawAllsCards(g);
}
if (this.currentState == GameState.Playing) {
this.banker.drawOnBoardCards(g);
this.gManager.drawAllsCards(g);
}
if (this.currentState == GameState.Ending) {
this.gManager.drawAllsTakenCards(g);
}
this.gManager.drawAllsNames(g);
motionManager.draw(g);
}
//Bắt sự kiện chuột xảy ra với game
@Override
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
// super.mouseClicked(e);
//nêu server có lệnh là pass
if (this.playerState == PlayerState.Pass) {
//cho phép player tương tác với card.
Gambler player = this.gManager.getMainPlayer();
player.selectCardToPass(p);
}
//nếu server có lệnh là đánh 1 lá bài
if (this.playerState == PlayerState.PlayCard) {
Gambler player = this.gManager.getMainPlayer();
GUICard selected = player.getHitCard(p);
if(selected == null)
return;
if (isFirstTurn) {
//Kiểm tra xem có hợp lệ ko
int cardID = Card.convertCardGUI_IDToCard_ID(selected.toCardID());
if(this.clientMessenger.gameRules.isLeadMovingValid(
cardID)
)
{
//this.clientMessenger.sendToServer(this.gManager.player.getName(), selected.toCardID());
String content = Integer.toString(cardID);
this.clientMessenger.sendMessageToServer(MessageType.PlayCard, content);
isFirstTurn = false;
}
} else {
int iCurrCardID = Card.convertCardGUI_IDToCard_ID(selected.toCardID());
int iFirstCardID = Card.convertCardGUI_IDToCard_ID(banker.getFirstCardOnBoard().toCardID());
if(this.clientMessenger.gameRules.isMovingValid(iCurrCardID, iFirstCardID, player.getGamblerCards()))
{
this.clientMessenger.sendMessageToServer(MessageType.PlayCard, Integer.toString(iCurrCardID));
}
// if (this.clientMessenger.checkRules(selected.toCardID(), banker.getFirstCardOnBoard().toCardID(), player.getGamblerCards())) {
// this.clientMessenger.sendToServer(this.gManager.player.getName(), selected.toCardID());
// }
}
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
//this.clientMessenger.finishTask(currentState);
this.setPlayerState(PlayerState.DoNothing);
this.isFinishedTask = true;
//hoàn thành nhiệm vụ thì disable nó đi
JButton button = (JButton) e.getSource();
button.setEnabled(false);
}
}
//Lấy ảnh cho việc tạo card
public void loadResources() {
BufferedImage cardsuittexture = ImageUtility.loadImageFromResource_("Images/StandardDeck.gif");
BufferedImage backfacetexture = ImageUtility.loadImageFromResource_("Images/backfacecard.png");//Toolkit.getDefaultToolkit().getImage((getClass().getResource("Images/backfacecard.png")));
GUICard.width = 71;
GUICard.height = 96;
Deck.setWidth(GUICard.width);
Deck.setHeight(GUICard.height);
Deck.backfacetexture = backfacetexture;
Deck.cardsuittexture = cardsuittexture;
for (int i = 0; i < 3; i++) {
ImageIcon icon = new ImageIcon(ImageUtility.getInstance().loadImageFromResource_("Images/pass_arrow_small_" + i + ".png"));
this.lstIconForPassButton.add(icon);
}
}
public void initAllsClients(String clientName, ArrayList<String> lstNames) {
this.gManager.initPlayers(clientName, lstNames);
}
//Thục hiện chia bài
public void dealCardToGambler(int rank, int suit, String name) {
Gambler gambler = this.gManager.getGambler(name);
this.banker.dealCard(rank, suit, gambler);
}
public void sendTakenCardToGambler(int rank, int suit, String name) {
Gambler gambler = this.gManager.getGambler(name);
this.banker.sendCardToLostGambler(rank, suit, gambler);
}
public void sendTakenCardsToGambler(ArrayList<Integer> guiIDList,String name) {
Gambler gambler = this.gManager.getGambler(name);
for (int i = 0; i < guiIDList.size(); i++) {
Integer guiID = guiIDList.get(i);
int rank = guiID % 13;
int suit = guiID / 13;
this.banker.sendCardToLostGambler(rank, suit, gambler);
}
//this.clientMessenger.finishTask(currentState);
}
public void selectCardsToPass(int rank, int suit, String name) {
Gambler gambler = this.gManager.getGambler(name);
if (gambler == this.gManager.player) {
return;
}
gambler.selectCardToPass(rank, suit);
}
public void passSelectedCards(int direction) {
this.gManager.passCards(direction);
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
gp.showPassButton(false);
}
});
//this.clientMessenger.finishTask(currentState);
}
public void playCard(int rank, int suit, String name) {
Gambler gambler = this.gManager.getGambler(name);
gambler.playCard(rank, suit, banker);
this.isFirstTurn = false;
//this.clientMessenger.finishTask(currentState);
}
public void prepareForNextGame() {
this.banker.reset();
this.gManager.resetAllsGamblers();
this.setCurrentState(GameState.Begining);
//this.clientMessenger.finishTask(currentState);
}
public void prepareToDeal() {
this.setCurrentState(GameState.Dealing);
//this.clientMessenger.finishTask(currentState);
}
//direction = 0,1,2 <-> trái,phải,trên
public void prepareToPass(int direction) {
if (direction < 0 || direction > 2) {
return;
}
this.setCurrentState(GameState.Passing);
this.gp.button.setIcon(this.lstIconForPassButton.get(direction));
this.gp.showPassButton(true);
// switch (direction) {
// case 0:{
// break;
// }
// case 1:
// break;
// case 2:
// break;
// }
//clientMessenger.finishTask(currentState);
}
public void prepareToPlay() {
this.setCurrentState(GameState.Playing);
this.gp.showPassButton(false);
this.isFirstTurn = true;
//this.clientMessenger.finishTask(currentState);
}
public void prepareToEnd() {
this.setCurrentState(GameState.Ending);
//this.clientMessenger.finishTask(currentState);
}
public void waitClientAction() {
this.isFinishedTask = false;
this.playerState = PlayerState.PlayCard;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package doan_totalcommander_002;
/**
*
* @author Administrator
*/
public enum jEnum_CacEnumTrongBai {
BangTrai (1),
BangPhai (2),
KB (1024),
MB (1024 * 1024),
GB (1024 * 1024 * 1024),
SuaFile (2),
XemFile (3),
SoSanhBang (0),
SoSanhLonHon (1),
SoSanhNhoHon (2);
private final int value;
jEnum_CacEnumTrongBai(int value) {
this.value = value;
}
public int value(){
return this.value;
}
}
| Java |
/*
* DoAn_TatalCommande_002View.java
*/
package doan_totalcommander_002;
import QuanLyFile.BoQuanLyFile;
import QuanLyFile.Dialog_Xem_ChinhSuaFile;
import QuanLyFile.Dialog_SoSanhFile;
import DuyetFile.EventListener_ClickChuotVaoBangDuyetFile;
import DuyetFile.BangDuyetFile;
import DuyetFile.CayDuyetFile;
import DuyetFile.DroppableTable;
import DuyetFile.EventListener_ClickChuotVaoCayDuyetFile;
import QuanLyFile.Dialog_CatNho;
import QuanLyFile.Dialog_Copy;
import QuanLyFile.Dialog_GhepNoi;
import QuanLyFile.Dialog_Move;
import QuanLyFile.Dialog_ReMove;
import QuanLyFile.Dialog_TimFile;
import QuanLyFileNen.BoQuanLyFileZip;
import QuanLyFileNen.Dialog_AppendZip;
import java.awt.Desktop;
import java.beans.PropertyChangeEvent;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import ch.randelshofer.quaqua.QuaquaManager;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import net.infonode.gui.laf.InfoNodeLookAndFeel;
/**
* The application's main frame.
*/
public class DoAn_TatalCommande_002View extends FrameView {
private BangDuyetFile bangTrai;
private BangDuyetFile bangPhai;
// private jEnum_CacBang _enum_BangHienTai;
private BangDuyetFile bangHienTai;
private CayDuyetFile cayDuyetFile;
private boolean bKhoiTaoXong = false;
public DoAn_TatalCommande_002View(SingleFrameApplication app) {
super(app);
initComponents();
/*---------------------Khởi tạo menu item cho LAF-------------------------------------------*/
UIManager.LookAndFeelInfo[] infos= UIManager.getInstalledLookAndFeels();
JMenuItem []items=new JMenuItem[infos.length];
for (int i=0; i<infos.length; i++){
items[i]=new JMenuItem(infos[i].getName());
items[i].setActionCommand(infos[i].getClassName());
items[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clickMenu(e);
}
});
this.LaF.add(items[i]);
}
/*---------------------Khởi tạo các ScrollPane-------------------------------------------*/
jScrollPane_PhanChinh_BangTrai.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("ToolTipText"))
jTabbedPane_PhanChinh_BangTrai.setTitleAt(0, jScrollPane_PhanChinh_BangTrai.getToolTipText());
}
});
jScrollPane_PhanChinh_BangPhai.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("ToolTipText"))
jTabbedPane_PhanChinh_BangPhai.setTitleAt(0, jScrollPane_PhanChinh_BangPhai.getToolTipText());
}
});
/*---------------------------------------------------------------------------------------*/
/*---------------------Khởi tạo các bảng duyệt thư mục-----------------------------------*/
bangTrai = new BangDuyetFile("C:", jScrollPane_PhanChinh_BangTrai);
bangPhai = new BangDuyetFile("D:", jScrollPane_PhanChinh_BangPhai);
// _enum_BangHienTai = jEnum_CacBang.BangTrai;
bangHienTai = bangTrai;
bangPhai.getTable().clearSelection();
//System.setProperty("user.dir", _bangHienTai.getTenFile());
//Khi nguoi dung thay doi thu muc cua bang ben phai
bangTrai.themEventListener_ClickChuotVaoBangDuyetFile(new EventListener_ClickChuotVaoBangDuyetFile() {
public void Event_ClickChuotVaoBangDuyetFile_Occurred(String str_TenFileDuocChon, int iSoLanClick) {
//jLabel1.setText("Ban chon cua so trai");
//bangPhai.getTable().clearSelection();
// _enum_BangHienTai = jEnum_CacBang.BangTrai;
if (!bKhoiTaoXong)//nếu chưa khởi tạo xong thì return
return;
bangHienTai = bangTrai;
if (iSoLanClick == 1)
return;
String str_PhanVung;
if (bangTrai.getTenFile().contains("\\"))
str_PhanVung = bangTrai.getTenFile().substring(0, "C:\\".length());
else
str_PhanVung = bangTrai.getTenFile() + "\\";
if (!bangTrai.getTenFile().substring(0,1).equalsIgnoreCase(str_PhanVung.substring(0, 1)))
jComboBox_PhanChinh_BangTrai.setSelectedItem(str_PhanVung);
//System.setProperty("user.dir", _bangHienTai.getTenFile());
//JOptionPane.showMessageDialog(null, System.getProperty("user.dir"));
//Goi ham cap nhat cay
int viTriThanhCuon = cayDuyetFile.capNhatCay(str_TenFileDuocChon);
jScrollPane_PhanChinh_Tree.getVerticalScrollBar().setValue(viTriThanhCuon);
}
});
//Khi nguoi dung thay doi thu muc cua bang ben phai
bangPhai.themEventListener_ClickChuotVaoBangDuyetFile(new EventListener_ClickChuotVaoBangDuyetFile() {
public void Event_ClickChuotVaoBangDuyetFile_Occurred(String str_TenFileDuocChon, int iSoLanClick) {
//jLabel1.setText("Ban chon cua so phai");
//bangTrai.getTable().clearSelection();
//_enum_BangHienTai = jEnum_CacBang.BangPhai;
bangHienTai = bangPhai;
if (iSoLanClick == 1)
return;
String str_PhanVung;
if (bangPhai.getTenFile().contains("\\"))
str_PhanVung = bangPhai.getTenFile().substring(0, "C:\\".length());
else
str_PhanVung = bangPhai.getTenFile() + "\\";
if (!bangPhai.getTenFile().substring(0,1).equalsIgnoreCase(str_PhanVung.substring(0, 1)))
jComboBox_PhanChinh_BangPhai.setSelectedItem(str_PhanVung);
//Goi ham cap nhat cay
int viTriThanhCuon = cayDuyetFile.capNhatCay(str_TenFileDuocChon);
jScrollPane_PhanChinh_Tree.getVerticalScrollBar().setValue(viTriThanhCuon);
}
});
/*---------------------------------------------------------------------------------------*/
/*---------Khởi tạo treeview và 2 combo box hiện thị các ổ đĩa----------------------------*/
/*---------Khởi tạo treeview và 2 combo box hiện thị các ổ đĩa----------------------------*/
cayDuyetFile = new CayDuyetFile(jScrollPane_PhanChinh_Tree);
cayDuyetFile.addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() {
public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon) {
if (!bKhoiTaoXong)//nếu chưa khởi tạo xong thì return
return;
if ((bangHienTai.getTenFile().replace("\\\\", "\\")).equalsIgnoreCase(str_fileduocchon))
return;
if (bangHienTai == bangPhai){
bangPhai.capNhatBangDuyetThuMuc(str_fileduocchon, jScrollPane_PhanChinh_BangPhai);
}
else
bangTrai.capNhatBangDuyetThuMuc(str_fileduocchon, jScrollPane_PhanChinh_BangTrai);
}
}
) ;
jComboBox_PhanChinh_BangPhai.removeAllItems();
jComboBox_PhanChinh_BangTrai.removeAllItems();
for (File file : File.listRoots()){
jComboBox_PhanChinh_BangPhai.addItem(file.getPath());
jComboBox_PhanChinh_BangTrai.addItem(file.getPath());
}
jComboBox_PhanChinh_BangPhai.setSelectedItem(bangTrai.getTenFile());
jComboBox_PhanChinh_BangTrai.setSelectedItem(bangPhai.getTenFile());
//jTree1 = new JTree(root);
//jScrollPane_PhanChinh_Tree.setViewportView(jTree1);
/*---------------------------------------------------------------------------------------*/
//bangTrai.capNhatBangDuyetThuMuc("C:", jScrollPane_PhanChinh_BangTrai);
//String strThuMucHienHanh = System.getProperty("user.dir");
bangPhai.capNhatBangDuyetThuMuc("C:", jScrollPane_PhanChinh_BangPhai);
Timer timer = new Timer(10 * 1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (bangHienTai == bangTrai){
bangPhai.capNhatBangDuyetThuMuc(jScrollPane_PhanChinh_BangPhai.getToolTipText()
, jScrollPane_PhanChinh_BangPhai);
bangTrai.capNhatBangDuyetThuMuc(jScrollPane_PhanChinh_BangTrai.getToolTipText()
, jScrollPane_PhanChinh_BangTrai);
bangTrai.getTable().requestFocusInWindow();
}
if (bangHienTai == bangPhai){
bangTrai.capNhatBangDuyetThuMuc(jScrollPane_PhanChinh_BangTrai.getToolTipText()
, jScrollPane_PhanChinh_BangTrai);
bangPhai.capNhatBangDuyetThuMuc(jScrollPane_PhanChinh_BangPhai.getToolTipText()
, jScrollPane_PhanChinh_BangPhai);
bangPhai.getTable().requestFocusInWindow();
}
}
});
timer.start();
bKhoiTaoXong = true;
//
//jTabbedPane1.addTab("C:", jTabbedPane1.getTabComponentAt(0));
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
}// dong view
@Action
public void clickMenu(ActionEvent e){
String laf=e.getActionCommand();
try{
UIManager.setLookAndFeel(laf);
SwingUtilities.updateComponentTreeUI(DoAn_TatalCommande_002App.getApplication().getMainFrame());
}catch(Exception ex){
}
}
public void showAboutBox() {
if (aboutBox == null) {
JFrame mainFrame = DoAn_TatalCommande_002App.getApplication().getMainFrame();
aboutBox = new DoAn_TatalCommande_002AboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
DoAn_TatalCommande_002App.getApplication().show(aboutBox);
}
/**
* Cập nhật lại các bảng trái, phải sau khi có hành động như tạo, xóa thư mục/tập tin
*/
private void capNhatCacBang(File thuMucVuaCapNhat) {
if (bangHienTai.getTenFile().equals(bangPhai.getTenFile())) {
bangPhai.capNhatBangDuyetThuMuc(bangPhai.getTenFile(), jScrollPane_PhanChinh_BangPhai);
}
if(bangHienTai.getTenFile().equals(bangTrai.getTenFile())) {
bangTrai.capNhatBangDuyetThuMuc(bangTrai.getTenFile(), jScrollPane_PhanChinh_BangTrai);
}
if(bangTrai.getTenFile().equalsIgnoreCase(thuMucVuaCapNhat.getPath()))
bangTrai.capNhatBangDuyetThuMuc(bangTrai.getTenFile(), jScrollPane_PhanChinh_BangTrai);
if(bangPhai.getTenFile().equalsIgnoreCase(thuMucVuaCapNhat.getPath()))
bangPhai.capNhatBangDuyetThuMuc(bangPhai.getTenFile(), jScrollPane_PhanChinh_BangPhai);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
mainPanel = new javax.swing.JPanel();
jPanel_PhanDau = new javax.swing.JPanel();
jToolBar1 = new javax.swing.JToolBar();
jButton_destop = new javax.swing.JButton();
jButton_myDocuments = new javax.swing.JButton();
jButton_find = new javax.swing.JButton();
jButton_newFile = new javax.swing.JButton();
jButton_zip = new javax.swing.JButton();
jButton_unzip = new javax.swing.JButton();
jButton_sosanhfile = new javax.swing.JButton();
jPanel_PhanChan = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jSeparator1 = new javax.swing.JSeparator();
jSeparator2 = new javax.swing.JSeparator();
jSeparator3 = new javax.swing.JSeparator();
jSeparator6 = new javax.swing.JSeparator();
jSeparator7 = new javax.swing.JSeparator();
jButton_View = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton_Edit = new javax.swing.JButton();
jButton_NewFolder = new javax.swing.JButton();
jButton_Move = new javax.swing.JButton();
jButton_Copy = new javax.swing.JButton();
jButton_Delete = new javax.swing.JButton();
jComboBox_ThucThiCommandLine = new javax.swing.JComboBox();
jButton_ThucThiCommandLine = new javax.swing.JButton();
jSplitPane1 = new javax.swing.JSplitPane();
jSplitPane2 = new javax.swing.JSplitPane();
jScrollPane_PhanChinh_Tree = new javax.swing.JScrollPane();
jTree1 = new javax.swing.JTree();
jPanel1 = new javax.swing.JPanel();
jComboBox_PhanChinh_BangTrai = new javax.swing.JComboBox();
jTabbedPane_PhanChinh_BangTrai = new javax.swing.JTabbedPane();
jScrollPane_PhanChinh_BangTrai = new javax.swing.JScrollPane();
jPanel2 = new javax.swing.JPanel();
jTabbedPane_PhanChinh_BangPhai = new javax.swing.JTabbedPane();
jScrollPane_PhanChinh_BangPhai = new javax.swing.JScrollPane();
jComboBox_PhanChinh_BangPhai = new javax.swing.JComboBox();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu jMenu_File = new javax.swing.JMenu();
jMenuItem_File_XemFile = new javax.swing.JMenuItem();
jMenuItem_File_ChinhSuaTapTin = new javax.swing.JMenuItem();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem_File_NewFolder = new javax.swing.JMenuItem();
jMenuItem_TaoFileMoi = new javax.swing.JMenuItem();
jMenuItem_File_Xoa = new javax.swing.JMenuItem();
jMenuItem_File_SoSanh = new javax.swing.JMenuItem();
jMenuItem_File_DoiTen = new javax.swing.JMenuItem();
jMenuItem_File_DiChuyen = new javax.swing.JMenuItem();
jSeparator9 = new javax.swing.JSeparator();
jMenuItem_File_TimKiem = new javax.swing.JMenuItem();
jSeparator4 = new javax.swing.JSeparator();
jMenuItem_Zip = new javax.swing.JMenuItem();
jMenuItem_File_AppendZip = new javax.swing.JMenuItem();
jMenuItem_File_ViewZip = new javax.swing.JMenuItem();
jMenuItem_unZip = new javax.swing.JMenuItem();
jSeparator5 = new javax.swing.JSeparator();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
jMenu_Edit = new javax.swing.JMenu();
jMenuItem_Edit_Back = new javax.swing.JMenuItem();
jMenu_Expect = new javax.swing.JMenu();
jMenuItem_CatTapTin = new javax.swing.JMenuItem();
jMenuItem_NoiTapTin = new javax.swing.JMenuItem();
jSeparator8 = new javax.swing.JSeparator();
jMenuItem_KetNoiFTP = new javax.swing.JMenuItem();
jMenuItem_KetNoiLan = new javax.swing.JMenuItem();
jMenu_View_Tree = new javax.swing.JMenu();
jCheckBoxMenuItem_TreeView = new javax.swing.JCheckBoxMenuItem();
jCheckBoxMenuItem_fullView = new javax.swing.JCheckBoxMenuItem();
jCheckBoxMenuItem_Brief = new javax.swing.JCheckBoxMenuItem();
jCheckBoxMenuItem_Thumbnail = new javax.swing.JCheckBoxMenuItem();
LaF = new javax.swing.JMenu();
MacLAF = new javax.swing.JMenuItem();
InfoNodeLAF = new javax.swing.JMenuItem();
TinyLAF = new javax.swing.JMenuItem();
SquarenessLAF = new javax.swing.JMenuItem();
smoothLAF = new javax.swing.JMenuItem();
EaSynthLAF = new javax.swing.JMenuItem();
jSeparator10 = new javax.swing.JSeparator();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
jMenuItem_HienThiJavaDoc = new javax.swing.JMenuItem();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu2 = new javax.swing.JMenu();
jMenu3 = new javax.swing.JMenu();
jButton13 = new javax.swing.JButton();
mainPanel.setName("mainPanel"); // NOI18N
mainPanel.setLayout(new java.awt.BorderLayout());
jPanel_PhanDau.setName("jPanel_PhanDau"); // NOI18N
jPanel_PhanDau.setPreferredSize(new java.awt.Dimension(932, 42));
jToolBar1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jToolBar1.setRollover(true);
jToolBar1.setName("jToolBar1"); // NOI18N
jToolBar1.setPreferredSize(new java.awt.Dimension(100, 38));
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getResourceMap(DoAn_TatalCommande_002View.class);
jButton_destop.setIcon(resourceMap.getIcon("jButton_destop.icon")); // NOI18N
jButton_destop.setText(resourceMap.getString("jButton_destop.text")); // NOI18N
jButton_destop.setToolTipText(resourceMap.getString("jButton_destop.toolTipText")); // NOI18N
jButton_destop.setFocusable(false);
jButton_destop.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_destop.setName("jButton_destop"); // NOI18N
jButton_destop.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jButton_destop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_destopActionPerformed(evt);
}
});
jToolBar1.add(jButton_destop);
jButton_myDocuments.setIcon(resourceMap.getIcon("jButton_myDocuments.icon")); // NOI18N
jButton_myDocuments.setText(resourceMap.getString("jButton_myDocuments.text")); // NOI18N
jButton_myDocuments.setToolTipText(resourceMap.getString("jButton_myDocuments.toolTipText")); // NOI18N
jButton_myDocuments.setFocusable(false);
jButton_myDocuments.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_myDocuments.setName("jButton_myDocuments"); // NOI18N
jButton_myDocuments.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jButton_myDocuments.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_myDocumentsActionPerformed(evt);
}
});
jToolBar1.add(jButton_myDocuments);
jButton_find.setIcon(resourceMap.getIcon("jbutton_find.icon")); // NOI18N
jButton_find.setText(resourceMap.getString("jbutton_find.text")); // NOI18N
jButton_find.setToolTipText(resourceMap.getString("jbutton_find.toolTipText")); // NOI18N
jButton_find.setFocusable(false);
jButton_find.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_find.setName("jbutton_find"); // NOI18N
jButton_find.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(jButton_find);
jButton_newFile.setIcon(resourceMap.getIcon("jButton_newFlie.icon")); // NOI18N
jButton_newFile.setText(resourceMap.getString("jButton_newFlie.text")); // NOI18N
jButton_newFile.setToolTipText(resourceMap.getString("jButton_newFlie.toolTipText")); // NOI18N
jButton_newFile.setFocusable(false);
jButton_newFile.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_newFile.setName("jButton_newFlie"); // NOI18N
jButton_newFile.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(jButton_newFile);
jButton_zip.setIcon(resourceMap.getIcon("jButton_zipFile.icon")); // NOI18N
jButton_zip.setText(resourceMap.getString("jButton_zipFile.text")); // NOI18N
jButton_zip.setToolTipText(resourceMap.getString("jButton_zipFile.toolTipText")); // NOI18N
jButton_zip.setFocusable(false);
jButton_zip.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_zip.setName("jButton_zipFile"); // NOI18N
jButton_zip.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(jButton_zip);
jButton_unzip.setIcon(resourceMap.getIcon("jButton_unZip.icon")); // NOI18N
jButton_unzip.setText(resourceMap.getString("jButton_unZip.text")); // NOI18N
jButton_unzip.setToolTipText(resourceMap.getString("jButton_unZip.toolTipText")); // NOI18N
jButton_unzip.setFocusable(false);
jButton_unzip.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_unzip.setName("jButton_unZip"); // NOI18N
jButton_unzip.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(jButton_unzip);
jButton_sosanhfile.setIcon(resourceMap.getIcon("jButton_sosanhfile.icon")); // NOI18N
jButton_sosanhfile.setText(resourceMap.getString("jButton_sosanhfile.text")); // NOI18N
jButton_sosanhfile.setToolTipText(resourceMap.getString("jButton_sosanhfile.toolTipText")); // NOI18N
jButton_sosanhfile.setFocusable(false);
jButton_sosanhfile.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_sosanhfile.setName("jButton_sosanhfile"); // NOI18N
jButton_sosanhfile.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jButton_sosanhfile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_sosanhfileActionPerformed(evt);
}
});
jToolBar1.add(jButton_sosanhfile);
javax.swing.GroupLayout jPanel_PhanDauLayout = new javax.swing.GroupLayout(jPanel_PhanDau);
jPanel_PhanDau.setLayout(jPanel_PhanDauLayout);
jPanel_PhanDauLayout.setHorizontalGroup(
jPanel_PhanDauLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 932, Short.MAX_VALUE)
);
jPanel_PhanDauLayout.setVerticalGroup(
jPanel_PhanDauLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_PhanDauLayout.createSequentialGroup()
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
mainPanel.add(jPanel_PhanDau, java.awt.BorderLayout.PAGE_START);
jPanel_PhanChan.setName("jPanel_PhanChan"); // NOI18N
jPanel_PhanChan.setPreferredSize(new java.awt.Dimension(900, 70));
jPanel4.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jPanel4.setName("jPanel4"); // NOI18N
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator1.setName("jSeparator1"); // NOI18N
jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator2.setName("jSeparator2"); // NOI18N
jSeparator3.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator3.setName("jSeparator3"); // NOI18N
jSeparator6.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator6.setName("jSeparator6"); // NOI18N
jSeparator7.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator7.setName("jSeparator7"); // NOI18N
jButton_View.setText(resourceMap.getString("jButton_f3view.text")); // NOI18N
jButton_View.setMaximumSize(new java.awt.Dimension(1024, 23));
jButton_View.setMinimumSize(new java.awt.Dimension(0, 23));
jButton_View.setName("jButton_f3view"); // NOI18N
jButton_View.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ViewActionPerformed(evt);
}
});
jButton3.setText(resourceMap.getString("jButton_alf4Exit.text")); // NOI18N
jButton3.setMaximumSize(new java.awt.Dimension(1024, 23));
jButton3.setMinimumSize(new java.awt.Dimension(0, 23));
jButton3.setName("jButton_alf4Exit"); // NOI18N
jButton_Edit.setText(resourceMap.getString("jButton_f4Edit.text")); // NOI18N
jButton_Edit.setMaximumSize(new java.awt.Dimension(1024, 23));
jButton_Edit.setMinimumSize(new java.awt.Dimension(0, 23));
jButton_Edit.setName("jButton_f4Edit"); // NOI18N
jButton_Edit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_EditActionPerformed(evt);
}
});
jButton_NewFolder.setText(resourceMap.getString("jButton_f7NewFolder.text")); // NOI18N
jButton_NewFolder.setMaximumSize(new java.awt.Dimension(1024, 23));
jButton_NewFolder.setMinimumSize(new java.awt.Dimension(0, 23));
jButton_NewFolder.setName("jButton_f7NewFolder"); // NOI18N
jButton_NewFolder.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_NewFolderActionPerformed(evt);
}
});
jButton_Move.setText(resourceMap.getString("jButton_f6Move.text")); // NOI18N
jButton_Move.setMaximumSize(new java.awt.Dimension(1024, 23));
jButton_Move.setMinimumSize(new java.awt.Dimension(0, 23));
jButton_Move.setName("jButton_f6Move"); // NOI18N
jButton_Move.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_MoveActionPerformed(evt);
}
});
jButton_Copy.setText(resourceMap.getString("jButton_f5Copy.text")); // NOI18N
jButton_Copy.setMaximumSize(new java.awt.Dimension(1024, 23));
jButton_Copy.setMinimumSize(new java.awt.Dimension(0, 23));
jButton_Copy.setName("jButton_f5Copy"); // NOI18N
jButton_Copy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_CopyActionPerformed(evt);
}
});
jButton_Delete.setText(resourceMap.getString("jButton_f8Delete.text")); // NOI18N
jButton_Delete.setMaximumSize(new java.awt.Dimension(1024, 23));
jButton_Delete.setMinimumSize(new java.awt.Dimension(0, 23));
jButton_Delete.setName("jButton_f8Delete"); // NOI18N
jButton_Delete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_DeleteActionPerformed(evt);
}
});
jComboBox_ThucThiCommandLine.setEditable(true);
jComboBox_ThucThiCommandLine.setName("jComboBox_ThucThiCommandLine"); // NOI18N
jComboBox_ThucThiCommandLine.setNextFocusableComponent(jButton_ThucThiCommandLine);
jComboBox_ThucThiCommandLine.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox_ThucThiCommandLineActionPerformed(evt);
}
});
jButton_ThucThiCommandLine.setText(resourceMap.getString("jButton_ThucThiCommandLine.text")); // NOI18N
jButton_ThucThiCommandLine.setName("jButton_ThucThiCommandLine"); // NOI18N
jButton_ThucThiCommandLine.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ThucThiCommandLineActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(404, 404, 404)
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 526, Short.MAX_VALUE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jButton_View, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Edit, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Copy, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jSeparator7, javax.swing.GroupLayout.PREFERRED_SIZE, 3, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(59, 59, 59)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(201, 201, 201)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
.addComponent(jButton_ThucThiCommandLine)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBox_ThucThiCommandLine, 0, 498, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jButton_Move, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_NewFolder, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Delete, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE))))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(5, 5, 5))
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox_ThucThiCommandLine, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_ThucThiCommandLine))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
.addComponent(jButton_View, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_Edit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_NewFolder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_Move, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_Copy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_Delete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
javax.swing.GroupLayout jPanel_PhanChanLayout = new javax.swing.GroupLayout(jPanel_PhanChan);
jPanel_PhanChan.setLayout(jPanel_PhanChanLayout);
jPanel_PhanChanLayout.setHorizontalGroup(
jPanel_PhanChanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel_PhanChanLayout.setVerticalGroup(
jPanel_PhanChanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
mainPanel.add(jPanel_PhanChan, java.awt.BorderLayout.PAGE_END);
jSplitPane1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jSplitPane1.setDividerLocation(600);
jSplitPane1.setName("jSplitPane1"); // NOI18N
jSplitPane2.setDividerLocation(150);
jSplitPane2.setLastDividerLocation(150);
jSplitPane2.setName("jSplitPane2"); // NOI18N
jScrollPane_PhanChinh_Tree.setName("jScrollPane_PhanChinh_Tree"); // NOI18N
jTree1.setName("jTree1"); // NOI18N
jScrollPane_PhanChinh_Tree.setViewportView(jTree1);
jSplitPane2.setLeftComponent(jScrollPane_PhanChinh_Tree);
jPanel1.setName("jPanel1"); // NOI18N
jComboBox_PhanChinh_BangTrai.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox_PhanChinh_BangTrai.setName("jComboBox_PhanChinh_BangTrai"); // NOI18N
jComboBox_PhanChinh_BangTrai.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox_PhanChinh_BangTraiActionPerformed(evt);
}
});
jTabbedPane_PhanChinh_BangTrai.setName("jTabbedPane_PhanChinh_BangTrai"); // NOI18N
jScrollPane_PhanChinh_BangTrai.setName("jScrollPane_PhanChinh_BangTrai"); // NOI18N
jTabbedPane_PhanChinh_BangTrai.addTab(resourceMap.getString("jScrollPane_PhanChinh_BangTrai.TabConstraints.tabTitle"), jScrollPane_PhanChinh_BangTrai); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane_PhanChinh_BangTrai, javax.swing.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jComboBox_PhanChinh_BangTrai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(387, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jComboBox_PhanChinh_BangTrai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTabbedPane_PhanChinh_BangTrai, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE))
);
jSplitPane2.setRightComponent(jPanel1);
jSplitPane1.setLeftComponent(jSplitPane2);
jPanel2.setName("jPanel2"); // NOI18N
jTabbedPane_PhanChinh_BangPhai.setName("jTabbedPane_PhanChinh_BangPhai"); // NOI18N
jScrollPane_PhanChinh_BangPhai.setName("jScrollPane_PhanChinh_BangPhai"); // NOI18N
jTabbedPane_PhanChinh_BangPhai.addTab(resourceMap.getString("jScrollPane_PhanChinh_BangPhai.TabConstraints.tabTitle"), jScrollPane_PhanChinh_BangPhai); // NOI18N
jComboBox_PhanChinh_BangPhai.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox_PhanChinh_BangPhai.setName("jComboBox_PhanChinh_BangPhai"); // NOI18N
jComboBox_PhanChinh_BangPhai.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox_PhanChinh_BangPhaiActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane_PhanChinh_BangPhai, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jComboBox_PhanChinh_BangPhai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jComboBox_PhanChinh_BangPhai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTabbedPane_PhanChinh_BangPhai, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE))
);
jSplitPane1.setRightComponent(jPanel2);
mainPanel.add(jSplitPane1, java.awt.BorderLayout.CENTER);
menuBar.setName("menuBar"); // NOI18N
jMenu_File.setText(resourceMap.getString("jMenu_File.text")); // NOI18N
jMenu_File.setName("jMenu_File"); // NOI18N
jMenuItem_File_XemFile.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F3, 0));
jMenuItem_File_XemFile.setText(resourceMap.getString("jMenuItem_File_XemFile.text")); // NOI18N
jMenuItem_File_XemFile.setName("jMenuItem_File_XemFile"); // NOI18N
jMenuItem_File_XemFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_File_XemFileActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_File_XemFile);
jMenuItem_File_ChinhSuaTapTin.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, 0));
jMenuItem_File_ChinhSuaTapTin.setText(resourceMap.getString("jMenuItem_File_ChinhSuaTapTin.text")); // NOI18N
jMenuItem_File_ChinhSuaTapTin.setName("jMenuItem_File_ChinhSuaTapTin"); // NOI18N
jMenuItem_File_ChinhSuaTapTin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_File_ChinhSuaTapTinActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_File_ChinhSuaTapTin);
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
jMenuItem1.setName("jMenuItem1"); // NOI18N
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem1);
jMenuItem_File_NewFolder.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F7, 0));
jMenuItem_File_NewFolder.setText(resourceMap.getString("jMenuItem_File_NewFolder.text")); // NOI18N
jMenuItem_File_NewFolder.setName("jMenuItem_File_NewFolder"); // NOI18N
jMenuItem_File_NewFolder.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_File_NewFolderActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_File_NewFolder);
jMenuItem_TaoFileMoi.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.SHIFT_MASK));
jMenuItem_TaoFileMoi.setText(resourceMap.getString("jMenuItem_TaoFileMoi.text")); // NOI18N
jMenuItem_TaoFileMoi.setName("jMenuItem_TaoFileMoi"); // NOI18N
jMenuItem_TaoFileMoi.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_TaoFileMoiActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_TaoFileMoi);
jMenuItem_File_Xoa.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DELETE, 0));
jMenuItem_File_Xoa.setText(resourceMap.getString("jMenuItem_File_Xoa.text")); // NOI18N
jMenuItem_File_Xoa.setName("jMenuItem_File_Xoa"); // NOI18N
jMenuItem_File_Xoa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_File_XoaActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_File_Xoa);
jMenuItem_File_SoSanh.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_File_SoSanh.setText(resourceMap.getString("jMenuItem_File_SoSanh.text")); // NOI18N
jMenuItem_File_SoSanh.setName("jMenuItem_File_SoSanh"); // NOI18N
jMenuItem_File_SoSanh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_File_SoSanhActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_File_SoSanh);
jMenuItem_File_DoiTen.setText(resourceMap.getString("jMenuItem_File_DoiTen.text")); // NOI18N
jMenuItem_File_DoiTen.setName("jMenuItem_File_DoiTen"); // NOI18N
jMenuItem_File_DoiTen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_File_DoiTenActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_File_DoiTen);
jMenuItem_File_DiChuyen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F6, 0));
jMenuItem_File_DiChuyen.setText(resourceMap.getString("jMenuItem_File_DiChuyen.text")); // NOI18N
jMenuItem_File_DiChuyen.setName("jMenuItem_File_DiChuyen"); // NOI18N
jMenuItem_File_DiChuyen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_File_DiChuyenActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_File_DiChuyen);
jSeparator9.setName("jSeparator9"); // NOI18N
jMenu_File.add(jSeparator9);
jMenuItem_File_TimKiem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F7, java.awt.event.InputEvent.ALT_MASK));
jMenuItem_File_TimKiem.setText(resourceMap.getString("jMenuItem_File_TimKiem.text")); // NOI18N
jMenuItem_File_TimKiem.setName("jMenuItem_File_TimKiem"); // NOI18N
jMenuItem_File_TimKiem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_File_TimKiemActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_File_TimKiem);
jSeparator4.setName("jSeparator4"); // NOI18N
jMenu_File.add(jSeparator4);
jMenuItem_Zip.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, java.awt.event.InputEvent.ALT_MASK));
jMenuItem_Zip.setText(resourceMap.getString("jMenuItem_Zip.text")); // NOI18N
jMenuItem_Zip.setName("jMenuItem_Zip"); // NOI18N
jMenuItem_Zip.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_ZipActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_Zip);
jMenuItem_File_AppendZip.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.SHIFT_MASK));
jMenuItem_File_AppendZip.setText(resourceMap.getString("jMenuItem_File_AppendZip.text")); // NOI18N
jMenuItem_File_AppendZip.setName("jMenuItem_File_AppendZip"); // NOI18N
jMenuItem_File_AppendZip.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_File_AppendZipActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_File_AppendZip);
jMenuItem_File_ViewZip.setText(resourceMap.getString("jMenuItem_File_ViewZip.text")); // NOI18N
jMenuItem_File_ViewZip.setName("jMenuItem_File_ViewZip"); // NOI18N
jMenuItem_File_ViewZip.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_File_ViewZipActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_File_ViewZip);
jMenuItem_unZip.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F9, java.awt.event.InputEvent.ALT_MASK));
jMenuItem_unZip.setText(resourceMap.getString("jMenuItem_unZip.text")); // NOI18N
jMenuItem_unZip.setName("jMenuItem_unZip"); // NOI18N
jMenuItem_unZip.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_unZipActionPerformed(evt);
}
});
jMenu_File.add(jMenuItem_unZip);
jSeparator5.setName("jSeparator5"); // NOI18N
jMenu_File.add(jSeparator5);
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getActionMap(DoAn_TatalCommande_002View.class, this);
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
jMenu_File.add(exitMenuItem);
menuBar.add(jMenu_File);
jMenu_Edit.setText(resourceMap.getString("jMenu_Edit.text")); // NOI18N
jMenu_Edit.setName("jMenu_Edit"); // NOI18N
jMenuItem_Edit_Back.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_BACK_SPACE, 0));
jMenuItem_Edit_Back.setText(resourceMap.getString("jMenuItem_Edit_Back.text")); // NOI18N
jMenuItem_Edit_Back.setName("jMenuItem_Edit_Back"); // NOI18N
jMenuItem_Edit_Back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_Edit_BackActionPerformed(evt);
}
});
jMenu_Edit.add(jMenuItem_Edit_Back);
menuBar.add(jMenu_Edit);
jMenu_Expect.setText(resourceMap.getString("jMenu_Expect.text")); // NOI18N
jMenu_Expect.setName("jMenu_Expect"); // NOI18N
jMenuItem_CatTapTin.setText(resourceMap.getString("jMenuItem_CatTapTin.text")); // NOI18N
jMenuItem_CatTapTin.setName("jMenuItem_CatTapTin"); // NOI18N
jMenuItem_CatTapTin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_CatTapTinActionPerformed(evt);
}
});
jMenu_Expect.add(jMenuItem_CatTapTin);
jMenuItem_NoiTapTin.setText(resourceMap.getString("jMenuItem_NoiTapTin.text")); // NOI18N
jMenuItem_NoiTapTin.setName("jMenuItem_NoiTapTin"); // NOI18N
jMenuItem_NoiTapTin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_NoiTapTinActionPerformed(evt);
}
});
jMenu_Expect.add(jMenuItem_NoiTapTin);
jSeparator8.setName("jSeparator8"); // NOI18N
jMenu_Expect.add(jSeparator8);
jMenuItem_KetNoiFTP.setText(resourceMap.getString("jMenuItem_KetNoiFTP.text")); // NOI18N
jMenuItem_KetNoiFTP.setName("jMenuItem_KetNoiFTP"); // NOI18N
jMenu_Expect.add(jMenuItem_KetNoiFTP);
jMenuItem_KetNoiLan.setText(resourceMap.getString("jMenuItem_KetNoiLan.text")); // NOI18N
jMenuItem_KetNoiLan.setName("jMenuItem_KetNoiLan"); // NOI18N
jMenu_Expect.add(jMenuItem_KetNoiLan);
menuBar.add(jMenu_Expect);
jMenu_View_Tree.setText(resourceMap.getString("jMenu_View_Tree.text")); // NOI18N
jMenu_View_Tree.setName("jMenu_View_Tree"); // NOI18N
jCheckBoxMenuItem_TreeView.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F8, java.awt.event.InputEvent.CTRL_MASK));
jCheckBoxMenuItem_TreeView.setSelected(true);
jCheckBoxMenuItem_TreeView.setText(resourceMap.getString("jCheckBoxMenuItem_TreeView.text")); // NOI18N
jCheckBoxMenuItem_TreeView.setName("jCheckBoxMenuItem_TreeView"); // NOI18N
jCheckBoxMenuItem_TreeView.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMenuItem_TreeViewActionPerformed(evt);
}
});
jMenu_View_Tree.add(jCheckBoxMenuItem_TreeView);
jCheckBoxMenuItem_fullView.setSelected(true);
jCheckBoxMenuItem_fullView.setText(resourceMap.getString("jCheckBoxMenuItem_fullView.text")); // NOI18N
jCheckBoxMenuItem_fullView.setName("jCheckBoxMenuItem_fullView"); // NOI18N
jMenu_View_Tree.add(jCheckBoxMenuItem_fullView);
jCheckBoxMenuItem_Brief.setSelected(true);
jCheckBoxMenuItem_Brief.setText(resourceMap.getString("jCheckBoxMenuItem_Brief.text")); // NOI18N
jCheckBoxMenuItem_Brief.setName("jCheckBoxMenuItem_Brief"); // NOI18N
jMenu_View_Tree.add(jCheckBoxMenuItem_Brief);
jCheckBoxMenuItem_Thumbnail.setSelected(true);
jCheckBoxMenuItem_Thumbnail.setText(resourceMap.getString("jCheckBoxMenuItem_Thumbnail.text")); // NOI18N
jCheckBoxMenuItem_Thumbnail.setName("jCheckBoxMenuItem_Thumbnail"); // NOI18N
jMenu_View_Tree.add(jCheckBoxMenuItem_Thumbnail);
menuBar.add(jMenu_View_Tree);
LaF.setText(resourceMap.getString("LaF.text")); // NOI18N
LaF.setName("LaF"); // NOI18N
MacLAF.setText(resourceMap.getString("MacLAF.text")); // NOI18N
MacLAF.setName("MacLAF"); // NOI18N
MacLAF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MacLAFActionPerformed(evt);
}
});
LaF.add(MacLAF);
InfoNodeLAF.setText(resourceMap.getString("InfoNodeLAF.text")); // NOI18N
InfoNodeLAF.setName("InfoNodeLAF"); // NOI18N
InfoNodeLAF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InfoNodeLAFActionPerformed(evt);
}
});
LaF.add(InfoNodeLAF);
TinyLAF.setText(resourceMap.getString("TinyLAF.text")); // NOI18N
TinyLAF.setName("TinyLAF"); // NOI18N
TinyLAF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
TinyLAFActionPerformed(evt);
}
});
LaF.add(TinyLAF);
SquarenessLAF.setText(resourceMap.getString("SquarenessLAF.text")); // NOI18N
SquarenessLAF.setName("SquarenessLAF"); // NOI18N
SquarenessLAF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SquarenessLAFActionPerformed(evt);
}
});
LaF.add(SquarenessLAF);
smoothLAF.setText(resourceMap.getString("smoothLAF.text")); // NOI18N
smoothLAF.setName("smoothLAF"); // NOI18N
smoothLAF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
smoothLAFActionPerformed(evt);
}
});
LaF.add(smoothLAF);
EaSynthLAF.setText(resourceMap.getString("EaSynthLAF.text")); // NOI18N
EaSynthLAF.setName("EaSynthLAF"); // NOI18N
EaSynthLAF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EaSynthLAFActionPerformed(evt);
}
});
LaF.add(EaSynthLAF);
jSeparator10.setName("jSeparator10"); // NOI18N
LaF.add(jSeparator10);
menuBar.add(LaF);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
jMenuItem_HienThiJavaDoc.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
jMenuItem_HienThiJavaDoc.setText(resourceMap.getString("jMenuItem_HienThiJavaDoc.text")); // NOI18N
jMenuItem_HienThiJavaDoc.setName("jMenuItem_HienThiJavaDoc"); // NOI18N
jMenuItem_HienThiJavaDoc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_HienThiJavaDocActionPerformed(evt);
}
});
helpMenu.add(jMenuItem_HienThiJavaDoc);
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
statusPanel.setName("statusPanel"); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(statusPanelLayout.createSequentialGroup()
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)
.addGap(207, 207, 207)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(statusMessageLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 762, Short.MAX_VALUE)
.addComponent(statusAnimationLabel)
.addGap(160, 160, 160))
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(statusPanelLayout.createSequentialGroup()
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(statusMessageLabel)
.addComponent(statusAnimationLabel))
.addGap(3, 3, 3))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
.addContainerGap(13, Short.MAX_VALUE)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jMenuBar1.setName("jMenuBar1"); // NOI18N
jMenu2.setText(resourceMap.getString("jMenu2.text")); // NOI18N
jMenu2.setName("jMenu2"); // NOI18N
jMenuBar1.add(jMenu2);
jMenu3.setText(resourceMap.getString("jMenu3.text")); // NOI18N
jMenu3.setName("jMenu3"); // NOI18N
jMenuBar1.add(jMenu3);
jButton13.setText(resourceMap.getString("jButton13.text")); // NOI18N
jButton13.setName("jButton13"); // NOI18N
setComponent(mainPanel);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>//GEN-END:initComponents
private void jMenuItem_Edit_BackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_Edit_BackActionPerformed
// TODO add your handling code here:
if (bangHienTai == bangTrai)
bangTrai.quayVeThuMucCha();
else
bangPhai.quayVeThuMucCha();
}//GEN-LAST:event_jMenuItem_Edit_BackActionPerformed
private void jMenuItem_File_NewFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_File_NewFolderActionPerformed
// TODO add your handling code here:
/*
String thuMucHienTai = _bangPhai.getTenFile();
String tenThuMucCanTao = "NewFolder";
String tenDayDuThuMucCanTao = thuMucHienTai + "\\" + tenThuMucCanTao;
for (int i = 1; i < 1025; i++){
File file = new File(tenDayDuThuMucCanTao + String.valueOf(i));
if (!file.exists() && !file.isDirectory()){
tenDayDuThuMucCanTao += String.valueOf(i);
break;
}
}
File file = new File(tenDayDuThuMucCanTao);
file.mkdir();
*/
String str_TenThuMucMoi =
JOptionPane.showInputDialog("Nhập tên thư mục mới:", BoQuanLyFile.taoTenThuMucMoiMacDinh(bangHienTai.getTenFile()));
if (!str_TenThuMucMoi.contains("\\"))
str_TenThuMucMoi = bangHienTai.getTenFile() + str_TenThuMucMoi;
//File file = new File(str_TenThuMucMoi).
//String str_DuongDanDayDuThuMucMoi = _bangHienTai.getTenFile() + "\\";
//System.setProperty(str_TenThuMucMoi, str_TenThuMucMoi)
BoQuanLyFile.taoThuMucMoi(str_TenThuMucMoi);
capNhatCacBang(new File(str_TenThuMucMoi).getParentFile());
}//GEN-LAST:event_jMenuItem_File_NewFolderActionPerformed
/**
* đặt trạng thái của tree view thành hiện thị hoặc ẩn
* @param hienThi true_hiện thị tree view, fasle không hiện thị
*/
private void datTrangTraiHienThiTreeView(boolean b_HienThi){
if (!b_HienThi){
jScrollPane_PhanChinh_Tree.setVisible(false);
jSplitPane2.setDividerLocation(0);
}
else{
jScrollPane_PhanChinh_Tree.setVisible(true);
jSplitPane2.setDividerLocation(150);
}
}
//hiện thị tree view
private void jCheckBoxMenuItem_TreeViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuItem_TreeViewActionPerformed
// TODO add your handling code here:
datTrangTraiHienThiTreeView(jCheckBoxMenuItem_TreeView.getState());
}//GEN-LAST:event_jCheckBoxMenuItem_TreeViewActionPerformed
private void jMenuItem_File_XoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_File_XoaActionPerformed
// TODO add your handling code here:
ArrayList<String> str_CacDuongDan = bangHienTai.layDuongDanDayDuFileDangDuocChon();
//Nếu không đang chọn thư mục nào hoặc không xác nhận xóa
if (str_CacDuongDan.size() == 0)
{
JOptionPane.showMessageDialog(null, "Chọn file để xóa");
return;
}
Dialog_ReMove dialog = new Dialog_ReMove(null, false);
dialog.getJTextField_Nguon().setText(str_CacDuongDan.get(0));
dialog.setVisible(true);
}//GEN-LAST:event_jMenuItem_File_XoaActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
// TODO add your handling code here:
//Kiểm tra xem người dùng có chọn file nào không?
ArrayList<String> astr_CacDuongDan = bangHienTai.layDuongDanDayDuFileDangDuocChon();
if (astr_CacDuongDan.size() == 0){
JOptionPane.showMessageDialog(null, "Xin chọn file để copy!");
return;
}
String str_DuongDanFileDangChon = astr_CacDuongDan.get(0);
//tạo file các file nguồn và đích
File f1 = new File(str_DuongDanFileDangChon);
File f2 = bangHienTai != bangPhai ? new File(bangPhai.getTenFile()) : new File(bangPhai.getTenFile());
Dialog_Copy dialog = new Dialog_Copy(null, false);
dialog.getJTextField_Dich().setText(f2.getAbsolutePath());
dialog.getJTextField_Nguon().setText(f1.getAbsolutePath());
dialog.setVisible(true);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jComboBox_PhanChinh_BangPhaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_PhanChinh_BangPhaiActionPerformed
// TODO add your handling code here:
if (!bKhoiTaoXong)//nếu chưa khởi tạo xong thì return
return;
if (jComboBox_PhanChinh_BangPhai.getSelectedItem() != null && bangPhai.getTenFile() != null
&& jComboBox_PhanChinh_BangPhai.getSelectedItem().toString().charAt(0) != bangPhai.getTenFile().charAt(0)){
//Nếu jCombox đã được khởi tạo và ổ đĩa được chọn khác ổ đỉa hiện tại
bangPhai.capNhatBangDuyetThuMuc(jComboBox_PhanChinh_BangPhai.getSelectedItem().toString(), jScrollPane_PhanChinh_BangPhai);
jTabbedPane_PhanChinh_BangPhai.setTitleAt(0, bangPhai.getTenFile());
}
}//GEN-LAST:event_jComboBox_PhanChinh_BangPhaiActionPerformed
private void jMenuItem_HienThiJavaDocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_HienThiJavaDocActionPerformed
// TODO add your handling code here:
File file_JavaDoc = new File("javadoc\\index.html");
if (file_JavaDoc.exists())
try {
Desktop.getDesktop().open(file_JavaDoc);
} catch (IOException ex) {
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex);
}
else
JOptionPane.showMessageDialog(null, "Không tìm thấy file \".\\javadoc\\index.html\" trong thư mục cài đặt!");
}//GEN-LAST:event_jMenuItem_HienThiJavaDocActionPerformed
/**
*
* Khởi tạo vào hiện thị dialog cho phép xem hoặc chỉnh sửa tập tin
* @param str_DuongDan đường dẫn file cần xem
* @param enumLoaiTruyXuat xem hoặc chỉnh sửa ví dụ:jEnum_CacEnumTrongBai.XemFile
* @throws java.io.IOException
*/
private void hienThiDialogXemFile(String str_DuongDan, jEnum_CacEnumTrongBai enumLoaiTruyXuat) throws IOException {
// TODO add your handling code here:
if (new File(str_DuongDan).isFile()) {
//Nếu là file thì khởi tạo dialog
Dialog_Xem_ChinhSuaFile dialog_Xem_ChinhSuaFile = new Dialog_Xem_ChinhSuaFile();
BoQuanLyFile.hienThiFile(str_DuongDan, dialog_Xem_ChinhSuaFile.getJTextPane_HienThiFile()
, enumLoaiTruyXuat);
//Đặt title là đường dẫn file đang xem
dialog_Xem_ChinhSuaFile.setTitle(str_DuongDan);
//setEnable phù hợp cho button Save
dialog_Xem_ChinhSuaFile.getJButton_Luu().setEnabled(enumLoaiTruyXuat == jEnum_CacEnumTrongBai.SuaFile);
//hiện thị dialog
dialog_Xem_ChinhSuaFile.setVisible(true);
}
}
private void jMenuItem_File_XemFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_File_XemFileActionPerformed
try {
hienThiDialogXemFile(bangHienTai.layDuongDanDayDuFileDangDuocChon().get(0),
jEnum_CacEnumTrongBai.XemFile);
} catch (IOException ex) {
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jMenuItem_File_XemFileActionPerformed
private void jMenuItem_File_ChinhSuaTapTinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_File_ChinhSuaTapTinActionPerformed
// TODO add your handling code here:
/*try {
hienThiDialogXemFile(_bangHienTai.layDuongDanDayDuFileDangDuocChon().get(0),
jEnum_CacEnumTrongBai.SuaFile);
} catch (IOException ex) {
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex);
}*/
File file = new File(bangHienTai.layDuongDanDayDuFileDangDuocChon().get(0));
if (file.isFile())
thucThiCommandLine("notepad " + file.getPath());
}//GEN-LAST:event_jMenuItem_File_ChinhSuaTapTinActionPerformed
private void jComboBox_ThucThiCommandLineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_ThucThiCommandLineActionPerformed
// TODO add your handling code here:
jButton_ThucThiCommandLineActionPerformed(evt);
}//GEN-LAST:event_jComboBox_ThucThiCommandLineActionPerformed
private void jButton_ThucThiCommandLineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ThucThiCommandLineActionPerformed
// TODO add your handling code here:
String str_Command = jComboBox_ThucThiCommandLine.getSelectedItem().toString();
if (jComboBox_ThucThiCommandLine.getSelectedIndex() == -1)
jComboBox_ThucThiCommandLine.addItem(str_Command);
if(thucThiCommandLine(str_Command) == 1)
//Nếu không gọi được commandline
JOptionPane.showMessageDialog(null, "Không thể thực thi commandline");
}//GEN-LAST:event_jButton_ThucThiCommandLineActionPerformed
/**
* Thực thi command line
* @param str_Command command cần thực thi
*/
private int thucThiCommandLine(String str_Command){
File file = new File(str_Command + "\\");//trường hợp người dùng đánh thiếu ký tự \
if (file.isDirectory()){//Nếu là thư mục khác
if(bangHienTai == bangPhai)
bangPhai.capNhatBangDuyetThuMuc(file.getPath(), jScrollPane_PhanChinh_BangPhai);
else
bangTrai.capNhatBangDuyetThuMuc(file.getPath(), jScrollPane_PhanChinh_BangTrai);
return 0;
}
file = new File(bangHienTai.getTenFile() + "\\" + str_Command + "\\");
if (file.isDirectory()){//Nếu là thư mục con của bảng hiện tại
if(bangHienTai == bangPhai)
bangPhai.capNhatBangDuyetThuMuc(file.getPath(), jScrollPane_PhanChinh_BangPhai);
else
bangTrai.capNhatBangDuyetThuMuc(file.getPath(), jScrollPane_PhanChinh_BangTrai);
return 0;
}
file = new File(bangHienTai.getTenFile() + "\\" + str_Command + "\\");
if(file.exists())
try {//Thử mở file trong thư mục hiện tại
Desktop.getDesktop().open(file);
return 0;
} catch (IOException ex) {
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex);
}
//tìm thư mục windows/system32.
String str_FileTrongThuMucSystem32DuDoan = System.getProperty("user.home").
substring(0, "C:\\".length()) + "Windows\\System32\\" + str_Command;
file = new File(str_FileTrongThuMucSystem32DuDoan);
if (!file.exists())
file = new File(str_FileTrongThuMucSystem32DuDoan + ".exe");//Đề phòng trường hợp đánh thiếu .exe
if (file.exists())
try {//thử tìm trong thư mục windows/system32.
Desktop.getDesktop().open(file);
return 0;
} catch (IOException ex1) {
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex1);
}
//Chạy commandline
try {
Runtime.getRuntime().exec(str_Command);
return 0;
} catch (IOException ex2) {
//JOptionPane.showMessageDialog(null, "Có lỗi khi thực thi command: " + str_Command, "Lỗi!", JOptionPane.ERROR_MESSAGE);
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex2);
}
return 1;
}
private void jMenuItem_File_SoSanhActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_File_SoSanhActionPerformed
// TODO add your handling code here:
try {
Dialog_SoSanhFile dialog_SoSanhFile = new Dialog_SoSanhFile("C:\\temp.txt","C:\\temp.txt");
dialog_SoSanhFile.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jMenuItem_File_SoSanhActionPerformed
//copy click//rename click
private void jMenuItem_CatTapTinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_CatTapTinActionPerformed
// TODO add your handling code here:
//Lấy file đầu tiên được chọn
ArrayList<String> astr_CacDuongDan = bangHienTai.layDuongDanDayDuFileDangDuocChon();
if (astr_CacDuongDan.size() == 0){
JOptionPane.showMessageDialog(null, "Xin chọn file để cắt!");
return;
}
String str_DuongDanFileDangChon = astr_CacDuongDan.get(0);
if (new File(str_DuongDanFileDangChon).isFile()){//nếu là file
//Lấy đường dẫn thư mục đích (là đường dẫn hiện tại của bảng ko được chọn)
String str_DuongDanThuMucDich = (bangHienTai.getTenFile().equalsIgnoreCase(bangPhai.getTenFile())) ?
bangTrai.getTenFile() : bangPhai.getTenFile();
//tạo và cập nhật thông tin cho dialog
Dialog_CatNho dialog = new Dialog_CatNho(null, false);
dialog.getMyComp_OpenSaveFile_FileNguon().getJComboBox_DuongDanFile().setSelectedItem(str_DuongDanFileDangChon);
dialog.setTextOfJTextField_ThuMucDich(str_DuongDanThuMucDich);
dialog.setVisible(true);
}
}//GEN-LAST:event_jMenuItem_CatTapTinActionPerformed
private void jMenuItem_NoiTapTinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_NoiTapTinActionPerformed
// TODO add your handling code here:
//tạo dialog
Dialog_GhepNoi dialog = new Dialog_GhepNoi(null, true);
//Cập nhật thông tin mặc định
//Lấy file đầu tiên được chọn
ArrayList<String> astr_CacDuongDan = bangHienTai.layDuongDanDayDuFileDangDuocChon();
if (astr_CacDuongDan.size() > 0){
String str_DuongDanFileDangChon = astr_CacDuongDan.get(0);
File fileDauTien = new File(str_DuongDanFileDangChon);
if (fileDauTien.isFile()//Nếu file đầu tiên trong danh sách được chọn là file
&& str_DuongDanFileDangChon.endsWith(".001")){//Nếu là file và có phần mở rộng là 001
//tạo đường dẫn file đích (là đường dẫn hiện tại của bảng ko được chọn và tên của file nguồn)
String str_DuongDanFileDich = (bangHienTai.getTenFile().equalsIgnoreCase(bangPhai.getTenFile())) ?
bangTrai.getTenFile() : bangPhai.getTenFile();
str_DuongDanFileDich += fileDauTien.getName().substring(0,
fileDauTien.getName().lastIndexOf(".001"));
dialog.setTextOfJTextField_FileNguon(str_DuongDanFileDangChon);
dialog.setTextOfJTextField_ThuMucDich(str_DuongDanFileDich);
}
}
dialog.setVisible(true);
}//GEN-LAST:event_jMenuItem_NoiTapTinActionPerformed
private void jMenuItem_File_TimKiemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_File_TimKiemActionPerformed
// TODO add your handling code here:
Dialog_TimFile dialog = new Dialog_TimFile(null, true);
dialog.themEventListener_ClickChuotVaoBangDuyetFile(new EventListener_ClickChuotVaoBangDuyetFile() {
public void Event_ClickChuotVaoBangDuyetFile_Occurred(String strTenFileDuocChon, int iSoLanClick) {
bangTrai.capNhatBangDuyetThuMuc(strTenFileDuocChon, jScrollPane_PhanChinh_BangTrai);
//JOptionPane.showMessageDialog(null, js);
}
});
dialog.setVisible(true);
}//GEN-LAST:event_jMenuItem_File_TimKiemActionPerformed
private void MacLAFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MacLAFActionPerformed
// TODO add your handling code here:
try{
UIManager.setLookAndFeel(QuaquaManager.getLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(DoAn_TatalCommande_002App.getApplication().getMainFrame());
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_MacLAFActionPerformed
private void InfoNodeLAFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InfoNodeLAFActionPerformed
// TODO add your handling code here:
try{
UIManager.setLookAndFeel(new InfoNodeLookAndFeel());
SwingUtilities.updateComponentTreeUI(DoAn_TatalCommande_002App.getApplication().getMainFrame());
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_InfoNodeLAFActionPerformed
private void TinyLAFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TinyLAFActionPerformed
// TODO add your handling code here:
try{
UIManager.setLookAndFeel("de.muntjak.tinylookandfeel.TinyLookAndFeel");
SwingUtilities.updateComponentTreeUI(DoAn_TatalCommande_002App.getApplication().getMainFrame());
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_TinyLAFActionPerformed
private void SquarenessLAFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SquarenessLAFActionPerformed
// TODO add your handling code here:
try{
UIManager.setLookAndFeel("net.beeger.squareness.SquarenessLookAndFeel");
SwingUtilities.updateComponentTreeUI(DoAn_TatalCommande_002App.getApplication().getMainFrame());
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_SquarenessLAFActionPerformed
private void smoothLAFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_smoothLAFActionPerformed
// TODO add your handling code here:
try{
UIManager.setLookAndFeel("smooth.metal.SmoothLookAndFeel");
SwingUtilities.updateComponentTreeUI(DoAn_TatalCommande_002App.getApplication().getMainFrame());
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_smoothLAFActionPerformed
private void EaSynthLAFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EaSynthLAFActionPerformed
// TODO add your handling code here:
try{
UIManager.setLookAndFeel("com.easynth.lookandfeel.EaSynthLookAndFeel");
SwingUtilities.updateComponentTreeUI(DoAn_TatalCommande_002App.getApplication().getMainFrame());
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_EaSynthLAFActionPerformed
private void jComboBox_PhanChinh_BangTraiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_PhanChinh_BangTraiActionPerformed
// TODO add your handling code here:
if (!bKhoiTaoXong)//nếu chưa khởi tạo xong thì return
return;
if (jComboBox_PhanChinh_BangTrai.getSelectedItem() != null && bangTrai.getTenFile() != null
&& jComboBox_PhanChinh_BangTrai.getSelectedItem().toString().charAt(0) != bangTrai.getTenFile().charAt(0)){
//Nếu jCombox đã được khởi tạo và ổ đĩa được chọn khác ổ đỉa hiện tại
bangTrai.capNhatBangDuyetThuMuc(jComboBox_PhanChinh_BangTrai.getSelectedItem().toString(), jScrollPane_PhanChinh_BangTrai);
jTabbedPane_PhanChinh_BangTrai.setTitleAt(0, bangTrai.getTenFile());
}
}//GEN-LAST:event_jComboBox_PhanChinh_BangTraiActionPerformed
private void jMenuItem_File_DiChuyenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_File_DiChuyenActionPerformed
// TODO add your handling code here:
//Kiểm tra xem người dùng có chọn file nào không?
ArrayList<String> astr_CacDuongDan = bangHienTai.layDuongDanDayDuFileDangDuocChon();
if (astr_CacDuongDan.size() == 0){
JOptionPane.showMessageDialog(null, "Xin chọn file để move!");
return;
}
String str_DuongDanFileDangChon = astr_CacDuongDan.get(0);
//tạo file các file nguồn và đích
File f1 = new File(str_DuongDanFileDangChon);
File f2 = bangHienTai != bangPhai ? new File(bangPhai.getTenFile()) : new File(bangPhai.getTenFile());
Dialog_Move dialog = new Dialog_Move(null, false);
dialog.getJTextField_Dich().setText(f2.getAbsolutePath());
dialog.getJTextField_Nguon().setText(f1.getAbsolutePath());
dialog.setVisible(true);
}//GEN-LAST:event_jMenuItem_File_DiChuyenActionPerformed
private void jMenuItem_TaoFileMoiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_TaoFileMoiActionPerformed
// TODO add your handling code here:
String str_TenFileMoi =
JOptionPane.showInputDialog("Nhập tên file cần tạo:");
if (!str_TenFileMoi.contains("\\"))
str_TenFileMoi = bangHienTai.getTenFile() + str_TenFileMoi;
try {
BoQuanLyFile.taoFileMoi(str_TenFileMoi);
thucThiCommandLine("notepad " + str_TenFileMoi);
} catch (IOException ex) {
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jMenuItem_TaoFileMoiActionPerformed
// nen file va nen folder
private void jMenuItem_ZipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_ZipActionPerformed
// TODO add your handling code here:
ArrayList<String> astr_CacDuongDan = bangHienTai.layDuongDanDayDuFileDangDuocChon();
if (astr_CacDuongDan.size() == 0){
JOptionPane.showMessageDialog(null, "Xin chọn file để zip!");
return;
}
String str_DuongDanFileDangChon = astr_CacDuongDan.get(0);
String Str_TenMoi = JOptionPane.showInputDialog("Zip file " + str_DuongDanFileDangChon + " thành: ", str_DuongDanFileDangChon + ".zip");
if (!Str_TenMoi.contains("\\"))
Str_TenMoi = bangHienTai.getTenFile() + Str_TenMoi;
try {
BoQuanLyFileZip.zipFolder(str_DuongDanFileDangChon, Str_TenMoi);
} catch (Exception ex) {
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_jMenuItem_ZipActionPerformed
// unzip file va folder
private void jMenuItem_unZipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_unZipActionPerformed
// TODO add your handling code here:
ArrayList<String> astr_CacDuongDan = bangHienTai.layDuongDanDayDuFileDangDuocChon();
if (astr_CacDuongDan.size() == 0){
JOptionPane.showMessageDialog(null, "Xin chọn file *.zip để unzip!");
return;
}
String str_DuongDanFileDangChon = null;
for (String temp : astr_CacDuongDan)
if (temp.endsWith(".zip"))
str_DuongDanFileDangChon = temp;
if (str_DuongDanFileDangChon == null){
JOptionPane.showMessageDialog(null, "Xin chọn file *.zip để unzip!");
return;
}
String Str_TenMoi = JOptionPane.showInputDialog("Unzip file " + str_DuongDanFileDangChon + " vào thư mục: ", str_DuongDanFileDangChon.substring(0, str_DuongDanFileDangChon.indexOf(".")) + "\\");
if (!Str_TenMoi.contains("\\"))
Str_TenMoi = bangHienTai.getTenFile() + Str_TenMoi;
if (!Str_TenMoi.endsWith("\\"))
Str_TenMoi += "\\";
try {
BoQuanLyFileZip.UnZip(str_DuongDanFileDangChon, Str_TenMoi);
} catch (Exception ex) {
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_jMenuItem_unZipActionPerformed
private void jMenuItem_File_AppendZipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_File_AppendZipActionPerformed
ArrayList<String> astr_CacDuongDan = bangHienTai.layDuongDanDayDuFileDangDuocChon();
if (astr_CacDuongDan.size() == 0){
JOptionPane.showMessageDialog(null, "Xin chọn file để đổi append vào file zip!");
return;
}
String str_DuongDanFileDangChon = astr_CacDuongDan.get(0);
Dialog_AppendZip dialog = new Dialog_AppendZip(null, false);
dialog.getJTextField_Append().setText(str_DuongDanFileDangChon);
dialog.setVisible(true);
}//GEN-LAST:event_jMenuItem_File_AppendZipActionPerformed
private void jMenuItem_File_ViewZipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_File_ViewZipActionPerformed
// TODO add your handling code here:
ArrayList<String> astr_CacDuongDan = bangHienTai.layDuongDanDayDuFileDangDuocChon();
if (astr_CacDuongDan.size() == 0){
JOptionPane.showMessageDialog(null, "Xin chọn file *.zip để unzip!");
return;
}
String str_DuongDanFileDangChon = null;
for (String temp : astr_CacDuongDan)
if (temp.endsWith(".zip"))
str_DuongDanFileDangChon = temp;
if (str_DuongDanFileDangChon == null){
JOptionPane.showMessageDialog(null, "Xin chọn file *.zip để unzip!");
return;
}
String tempfolder = "";
try {
tempfolder = BoQuanLyFileZip.outPutTemp(str_DuongDanFileDangChon);
} catch (IOException ex) {
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "loi: " + ex.getMessage());
return;
}
if (bangHienTai != bangTrai)
bangTrai.capNhatBangDuyetThuMuc(tempfolder, jScrollPane_PhanChinh_BangTrai);
else
bangPhai.capNhatBangDuyetThuMuc(tempfolder, jScrollPane_PhanChinh_BangPhai);
}//GEN-LAST:event_jMenuItem_File_ViewZipActionPerformed
private void jMenuItem_File_DoiTenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_File_DoiTenActionPerformed
// TODO add your handling code here:
ArrayList<String> astr_CacDuongDan = bangHienTai.layDuongDanDayDuFileDangDuocChon();
if (astr_CacDuongDan.size() == 0){
JOptionPane.showMessageDialog(null, "Xin chọn file để đổi tên!");
return;
}
String str_DuongDanFileDangChon = astr_CacDuongDan.get(0);
String Str_TenMoi = JOptionPane.showInputDialog("Đổi tên " + str_DuongDanFileDangChon + " thành: ", str_DuongDanFileDangChon);
if (!Str_TenMoi.contains("\\"))
Str_TenMoi = bangHienTai.getTenFile() + Str_TenMoi;
try {
BoQuanLyFile.renamefile(str_DuongDanFileDangChon, Str_TenMoi);
} catch (FileNotFoundException ex) {
Logger.getLogger(DoAn_TatalCommande_002View.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, ex.getMessage());
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_jMenuItem_File_DoiTenActionPerformed
private void jButton_ViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ViewActionPerformed
// TODO add your handling code here:
jMenuItem_File_ViewZipActionPerformed(evt);
}//GEN-LAST:event_jButton_ViewActionPerformed
private void jButton_EditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EditActionPerformed
// TODO add your handling code here:
jMenuItem_Edit_BackActionPerformed(evt);
}//GEN-LAST:event_jButton_EditActionPerformed
private void jButton_CopyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CopyActionPerformed
// TODO add your handling code here:
jMenuItem1ActionPerformed(evt);
}//GEN-LAST:event_jButton_CopyActionPerformed
private void jButton_MoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_MoveActionPerformed
// TODO add your handling code here:
jMenuItem_File_DiChuyenActionPerformed(evt);
}//GEN-LAST:event_jButton_MoveActionPerformed
private void jButton_NewFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_NewFolderActionPerformed
// TODO add your handling code here:
jMenuItem_File_NewFolderActionPerformed(evt);
}//GEN-LAST:event_jButton_NewFolderActionPerformed
private void jButton_DeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DeleteActionPerformed
// TODO add your handling code here:
jMenuItem_File_XoaActionPerformed(evt);
}//GEN-LAST:event_jButton_DeleteActionPerformed
private void jButton_destopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_destopActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton_destopActionPerformed
private void jButton_myDocumentsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_myDocumentsActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton_myDocumentsActionPerformed
private void jButton_sosanhfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_sosanhfileActionPerformed
// TODO add your handling code here:
jMenuItem_File_SoSanhActionPerformed(evt);
}//GEN-LAST:event_jButton_sosanhfileActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem EaSynthLAF;
private javax.swing.JMenuItem InfoNodeLAF;
private javax.swing.JMenu LaF;
private javax.swing.JMenuItem MacLAF;
private javax.swing.JMenuItem SquarenessLAF;
private javax.swing.JMenuItem TinyLAF;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton_Copy;
private javax.swing.JButton jButton_Delete;
private javax.swing.JButton jButton_Edit;
private javax.swing.JButton jButton_Move;
private javax.swing.JButton jButton_NewFolder;
private javax.swing.JButton jButton_ThucThiCommandLine;
private javax.swing.JButton jButton_View;
private javax.swing.JButton jButton_destop;
private javax.swing.JButton jButton_find;
private javax.swing.JButton jButton_myDocuments;
private javax.swing.JButton jButton_newFile;
private javax.swing.JButton jButton_sosanhfile;
private javax.swing.JButton jButton_unzip;
private javax.swing.JButton jButton_zip;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem_Brief;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem_Thumbnail;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem_TreeView;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem_fullView;
private javax.swing.JComboBox jComboBox_PhanChinh_BangPhai;
private javax.swing.JComboBox jComboBox_PhanChinh_BangTrai;
private javax.swing.JComboBox jComboBox_ThucThiCommandLine;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem_CatTapTin;
private javax.swing.JMenuItem jMenuItem_Edit_Back;
private javax.swing.JMenuItem jMenuItem_File_AppendZip;
private javax.swing.JMenuItem jMenuItem_File_ChinhSuaTapTin;
private javax.swing.JMenuItem jMenuItem_File_DiChuyen;
private javax.swing.JMenuItem jMenuItem_File_DoiTen;
private javax.swing.JMenuItem jMenuItem_File_NewFolder;
private javax.swing.JMenuItem jMenuItem_File_SoSanh;
private javax.swing.JMenuItem jMenuItem_File_TimKiem;
private javax.swing.JMenuItem jMenuItem_File_ViewZip;
private javax.swing.JMenuItem jMenuItem_File_XemFile;
private javax.swing.JMenuItem jMenuItem_File_Xoa;
private javax.swing.JMenuItem jMenuItem_HienThiJavaDoc;
private javax.swing.JMenuItem jMenuItem_KetNoiFTP;
private javax.swing.JMenuItem jMenuItem_KetNoiLan;
private javax.swing.JMenuItem jMenuItem_NoiTapTin;
private javax.swing.JMenuItem jMenuItem_TaoFileMoi;
private javax.swing.JMenuItem jMenuItem_Zip;
private javax.swing.JMenuItem jMenuItem_unZip;
private javax.swing.JMenu jMenu_Edit;
private javax.swing.JMenu jMenu_Expect;
private javax.swing.JMenu jMenu_View_Tree;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel_PhanChan;
private javax.swing.JPanel jPanel_PhanDau;
private javax.swing.JScrollPane jScrollPane_PhanChinh_BangPhai;
private javax.swing.JScrollPane jScrollPane_PhanChinh_BangTrai;
private javax.swing.JScrollPane jScrollPane_PhanChinh_Tree;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator10;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JSeparator jSeparator6;
private javax.swing.JSeparator jSeparator7;
private javax.swing.JSeparator jSeparator8;
private javax.swing.JSeparator jSeparator9;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JSplitPane jSplitPane2;
private javax.swing.JTabbedPane jTabbedPane_PhanChinh_BangPhai;
private javax.swing.JTabbedPane jTabbedPane_PhanChinh_BangTrai;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JTree jTree1;
private javax.swing.JPanel mainPanel;
private javax.swing.JMenuBar menuBar;
private javax.swing.JProgressBar progressBar;
private javax.swing.JMenuItem smoothLAF;
private javax.swing.JLabel statusAnimationLabel;
private javax.swing.JLabel statusMessageLabel;
private javax.swing.JPanel statusPanel;
// End of variables declaration//GEN-END:variables
private final Timer messageTimer;
private final Timer busyIconTimer;
private final Icon idleIcon;
private final Icon[] busyIcons = new Icon[15];
private int busyIconIndex = 0;
private JDialog aboutBox;
}
| Java |
package doan_totalcommander_002;
import java.awt.Image;
import javax.swing.ImageIcon;
/**
* Dùng để co giản các ImageIcon tham khao tại: http://www.java2s.com/Code/Java/2D-Graphics-GUI/Imagescale.htm
* @author Administrator
*/
public class BoCoGianImage{
public BoCoGianImage() {
}
/**
* Co giản ảnh kiểu ImageIcon
* @param icon Ảnh cần co giản (do chủ yếu cần co giản Icon nên để kiểu dữ liệu đưa vào là ImageIcon
* @param i_Rong Chiều rộng sau khi co giản
* @param i_Cao Chiều cao sau khi co giản
* @param i_LoaiCoGian loại co giản (đẹp hay nhanh) ví dụ Image.SCALE_SMOOTH
* @return ImageIcon sau khi co giản
*/
public static ImageIcon coGianImageIcon(ImageIcon icon, int i_Rong, int i_Cao, int i_LoaiCoGian) {
//ImageIcon icon = new ImageIcon("D:\\08-09 HK2\\Java\\Bai Tap\\DoAn_TatalCommander_004\\src\\doan_tatalcommande_002\\resources\\Back.png");
Image image = icon.getImage();
Image original = image;
image = original.getScaledInstance(i_Rong, i_Cao, i_LoaiCoGian);
return new ImageIcon(image);
}
} | Java |
/*
* DoAn_TatalCommande_002App.java
*/
package doan_totalcommander_002;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
/**
* The main class of the application.
*/
public class DoAn_TatalCommande_002App extends SingleFrameApplication {
/**
* At startup create and show the main frame of the application.
*/
@Override protected void startup() {
show(new DoAn_TatalCommande_002View(this));
}
/**
* This method is to initialize the specified window by injecting resources.
* Windows shown in our application come fully initialized from the GUI
* builder, so this additional configuration is not needed.
*/
@Override protected void configureWindow(java.awt.Window root) {
}
/**
* A convenient static getter for the application instance.
* @return the instance of DoAn_TatalCommande_002App
*/
public static DoAn_TatalCommande_002App getApplication() {
return Application.getInstance(DoAn_TatalCommande_002App.class);
}
/**
* Main method launching the application.
*/
public static void main(String[] args) {
launch(DoAn_TatalCommande_002App.class, args);
}
}
| Java |
/*
* DoAn_TatalCommande_002AboutBox.java
*/
package doan_totalcommander_002;
import org.jdesktop.application.Action;
public class DoAn_TatalCommande_002AboutBox extends javax.swing.JDialog {
public DoAn_TatalCommande_002AboutBox(java.awt.Frame parent) {
super(parent);
initComponents();
getRootPane().setDefaultButton(closeButton);
}
@Action public void closeAboutBox() {
dispose();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
closeButton = new javax.swing.JButton();
javax.swing.JLabel appTitleLabel = new javax.swing.JLabel();
javax.swing.JLabel versionLabel = new javax.swing.JLabel();
javax.swing.JLabel appVersionLabel = new javax.swing.JLabel();
javax.swing.JLabel vendorLabel = new javax.swing.JLabel();
javax.swing.JLabel appVendorLabel = new javax.swing.JLabel();
javax.swing.JLabel homepageLabel = new javax.swing.JLabel();
javax.swing.JLabel appHomepageLabel = new javax.swing.JLabel();
javax.swing.JLabel appDescLabel = new javax.swing.JLabel();
javax.swing.JLabel imageLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getResourceMap(DoAn_TatalCommande_002AboutBox.class);
setTitle(resourceMap.getString("title")); // NOI18N
setModal(true);
setName("aboutBox"); // NOI18N
setResizable(false);
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getActionMap(DoAn_TatalCommande_002AboutBox.class, this);
closeButton.setAction(actionMap.get("closeAboutBox")); // NOI18N
closeButton.setName("closeButton"); // NOI18N
appTitleLabel.setFont(appTitleLabel.getFont().deriveFont(appTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, appTitleLabel.getFont().getSize()+4));
appTitleLabel.setText(resourceMap.getString("Application.title")); // NOI18N
appTitleLabel.setName("appTitleLabel"); // NOI18N
versionLabel.setFont(versionLabel.getFont().deriveFont(versionLabel.getFont().getStyle() | java.awt.Font.BOLD));
versionLabel.setText(resourceMap.getString("versionLabel.text")); // NOI18N
versionLabel.setName("versionLabel"); // NOI18N
appVersionLabel.setText(resourceMap.getString("Application.version")); // NOI18N
appVersionLabel.setName("appVersionLabel"); // NOI18N
vendorLabel.setFont(vendorLabel.getFont().deriveFont(vendorLabel.getFont().getStyle() | java.awt.Font.BOLD));
vendorLabel.setText(resourceMap.getString("vendorLabel.text")); // NOI18N
vendorLabel.setName("vendorLabel"); // NOI18N
appVendorLabel.setText(resourceMap.getString("Application.vendor")); // NOI18N
appVendorLabel.setName("appVendorLabel"); // NOI18N
homepageLabel.setFont(homepageLabel.getFont().deriveFont(homepageLabel.getFont().getStyle() | java.awt.Font.BOLD));
homepageLabel.setText(resourceMap.getString("homepageLabel.text")); // NOI18N
homepageLabel.setName("homepageLabel"); // NOI18N
appHomepageLabel.setText(resourceMap.getString("Application.homepage")); // NOI18N
appHomepageLabel.setName("appHomepageLabel"); // NOI18N
appDescLabel.setText(resourceMap.getString("appDescLabel.text")); // NOI18N
appDescLabel.setName("appDescLabel"); // NOI18N
imageLabel.setIcon(resourceMap.getIcon("imageLabel.icon")); // NOI18N
imageLabel.setName("imageLabel"); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(imageLabel)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(versionLabel)
.addComponent(vendorLabel)
.addComponent(homepageLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(appVersionLabel)
.addComponent(appVendorLabel)
.addComponent(appHomepageLabel)))
.addComponent(appTitleLabel, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(appDescLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
.addComponent(closeButton))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(appTitleLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(appDescLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(versionLabel)
.addComponent(appVersionLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(vendorLabel)
.addComponent(appVendorLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(homepageLabel)
.addComponent(appHomepageLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
.addComponent(closeButton)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton closeButton;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dialog_AppendZip.java
*
* Created on Apr 19, 2009, 5:48:34 AM
*/
package QuanLyFileNen;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Administrator
*/
public class Dialog_AppendZip extends javax.swing.JDialog {
/** Creates new form Dialog_AppendZip */
public Dialog_AppendZip(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
myComp_OpenSaveFile_To = new QuanLyFile.MyComp_OpenSaveFile();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField_Append = new javax.swing.JTextField();
jButton_Thoat = new javax.swing.JButton();
jButton_Append = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setName("Form"); // NOI18N
myComp_OpenSaveFile_To.setName("myComp_OpenSaveFile_To"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getResourceMap(Dialog_AppendZip.class);
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
jTextField_Append.setText(resourceMap.getString("jTextField_Append.text")); // NOI18N
jTextField_Append.setName("jTextField_Append"); // NOI18N
jButton_Thoat.setText(resourceMap.getString("jButton_Thoat.text")); // NOI18N
jButton_Thoat.setName("jButton_Thoat"); // NOI18N
jButton_Thoat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ThoatActionPerformed(evt);
}
});
jButton_Append.setText(resourceMap.getString("jButton_Append.text")); // NOI18N
jButton_Append.setName("jButton_Append"); // NOI18N
jButton_Append.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_AppendActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField_Append, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
.addComponent(myComp_OpenSaveFile_To, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton_Append)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Thoat)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField_Append, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(myComp_OpenSaveFile_To, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_Append)
.addComponent(jButton_Thoat))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_ThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ThoatActionPerformed
// TODO add your handling code here:
if (JOptionPane.showConfirmDialog(null, "Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
dispose();
}//GEN-LAST:event_jButton_ThoatActionPerformed
private void jButton_AppendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AppendActionPerformed
String filezip = myComp_OpenSaveFile_To.getJComboBox_DuongDanFile().getSelectedItem().toString();
try {
BoQuanLyFileZip.appendFileToFileZip(getJTextField_Append().getText(), filezip);
} catch (FileNotFoundException ex) {
Logger.getLogger(Dialog_AppendZip.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Lổi: " + ex.getMessage());
} catch (IOException ex) {
Logger.getLogger(Dialog_AppendZip.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Lổi: " + ex.getMessage());
} catch (Exception ex) {
Logger.getLogger(Dialog_AppendZip.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Lổi: " + ex.getMessage());
}
}//GEN-LAST:event_jButton_AppendActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Dialog_AppendZip dialog = new Dialog_AppendZip(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_Append;
private javax.swing.JButton jButton_Thoat;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField_Append;
private QuanLyFile.MyComp_OpenSaveFile myComp_OpenSaveFile_To;
// End of variables declaration//GEN-END:variables
/**
* @return the jTextField_Append
*/
public javax.swing.JTextField getJTextField_Append() {
return jTextField_Append;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package QuanLyFileNen;
import QuanLyFile.BoQuanLyFile;
import java.io.*;
import java.text.DateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.*;
import javax.swing.JOptionPane;
import java.util.*;
import java.util.ArrayList;
/**
* Chua cac ham de quan ly file zip: nen va giai nen file
* @author Dang Thi Phuong Thao
*/
public class BoQuanLyFileZip {
/**
* Ham nen file
* Tham khao tai http://www.exampledepot.com/egs/java.util.zip/pkg.html#ZIP
* @param filename la file can nen
* @param zipfilename la file sau khi nen
*/
public static void ZipFile(String[] filenames, String outFilename) {
byte[] buf = new byte[1024];
try {
// Create the ZIP file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
// Compress the files
for (int i = 0; i < filenames.length; i++) {
FileInputStream in = new FileInputStream(filenames[i]);
// Add ZIP entry to output stream.
File file = new File(filenames[i]);
out.putNextEntry(new ZipEntry(file.getName()));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
/**
* //http://www.java2s.com/Code/Java/File-Input-Output/unzip.htm
* giai nen file, folder
* @param filezip file zip can giai ne
* @param directory thu muc chua file giai nen
* @throws java.io.IOException
*/
public static void UnZip(String filezip, String directory) throws IOException {
ZipFile zf = new ZipFile(filezip);
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
// System.out.println("Unzipping " + ze.getName());
File file = new File (directory + ze.getName());
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
FileOutputStream fout = new FileOutputStream(directory + ze.getName());
InputStream in = zf.getInputStream(ze);
byte[] buf = new byte[1024];
int c = 0;
while((c = in.read(buf, 0, 1024)) != -1){
fout.write(buf, 0, c);
in.skip(c);
}
//for (int c = in.read(); c != -1; c = in.read())
// fout.write(c);
}
}
/**
* //http://www.java2s.com/Code/Java/File-Input-Output/UseJavacodetozipafolder.htm
* nen folder
* @param srcFolder: folder can nen
* @param destZipFile: duong dan va ten file zip
* @throws java.lang.Exception
*/
public static void zipFolder(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
if (new File(srcFolder).isFile())
addFileToZip("", srcFolder, zip);
else
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
/**
* dua file vao file zip,dc su dung boi ham zipFolder
* @param path: duong dan cua file can them
* @param srcFile: file dua vao
* @param zip: file zip
* @throws java.lang.Exception
*/
static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
zip.closeEntry();
}
}
/**
* dua folder vao file zip, dc su dung boi ham zipFolder
* @param path: duong dan cua folder can them
* @param srcFile: folder dua vao
* @param zip: file zip
* @throws java.lang.Exception
*/
static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
}
}
}
/**
* Them file vao file zip
* @param appendFile: file can them vao
* @param fileZip: file zip
* @throws java.io.FileNotFoundException
* @throws java.io.IOException
* @throws java.lang.Exception
*/
public static void appendFileToFileZip(String appendFile, String fileZip) throws FileNotFoundException, IOException, Exception{
String tempFolder = outPutTemp(fileZip);
BoQuanLyFile boQuanLyFile = new BoQuanLyFile();
File folder = new File(tempFolder).getCanonicalFile();
File zip = new File(fileZip);
boQuanLyFile.copyDirectory(new File(appendFile), new File(tempFolder + "/" + new File(appendFile).getName()), true);
zipFolder(folder.getPath(), fileZip);
}
/**
* Giải nén ra một thư mục tạm. nhớ xóa khi kết thúc chương trình
* @param zipfile file zip cần xem
* @return đường dẫn của thư mục tạm
* @throws java.io.IOException
*/
public static String outPutTemp (String zipfile) throws IOException
{
String tempfolder = System.getProperty("java.io.tmpdir");
String timenow = String.valueOf(new File (zipfile).getName());
tempfolder += timenow + "/";
new File(tempfolder).deleteOnExit();
UnZip(zipfile, tempfolder);
return tempfolder;
}
}
| Java |
package DuyetFile;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.Point;
import java.util.EventListener;
/**
*
* @author Dang Thi Phuong Thao
*/
public interface EventListener_ClickChuotVaoCayDuyetFile extends EventListener {
public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon);
}
| Java |
package DuyetFile;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.EventListener;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public interface EventListener_ClickChuotVaoBangDuyetFile extends EventListener {
public void Event_ClickChuotVaoBangDuyetFile_Occurred(String evt, int iSoLanClick);
}
| Java |
package DuyetFile;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
/**
*
*Tham khao http://www.java2s.com/Code/Java/Swing-JFC/FileTreewithPopupMenu.htm
* @author Dang Thi Phuong Thao
*/
public class CayDuyetFile {
/**
* ICON_CONPUTER la icon hinh compute
*/
public final ImageIcon ICON_COMPUTER =
new ImageIcon(this.getClass().getResource(".\\resources\\Tree_computer.png"));
/**
* ICON_DISK la hinh icon disk
*/
public final ImageIcon ICON_DISK =
new ImageIcon(this.getClass().getResource(".\\resources\\Tree_disk.png"));
/**
* m_tree la 1 tree, duoc su dung de duyet va dua file vao
*/
protected JTree m_tree;
/**
* m_model giu kieu cua node goc, la kieu ma m_tree su dung
*/
protected DefaultTreeModel m_model;
/**
* m_display
*/
// protected JTextField m_display;
/**
* m_popup luu lai nhung action de sao nay dua vao memu
*/
protected JPopupMenu m_popup;
/**
* m_action luu tru action dua vao m_popup
*/
protected Action m_action;
/**
* m_clickedPath luu nhung treepath da dc kick qua
*/
private TreePath m_clickedPath;
private DirSelectionListener dirSelectionListener;
/**
* ham khoi tao CayDuyetFile voi thong so vao la 1 jcsrollPane s
*/
public CayDuyetFile(JScrollPane s) {
DefaultMutableTreeNode top = new DefaultMutableTreeNode(
new IconData(ICON_COMPUTER, null, "Computer"));
DefaultMutableTreeNode node;
File[] roots = File.listRoots();
for (int k = 0; k < roots.length; k++) {
node = new DefaultMutableTreeNode(new IconData(ICON_DISK,
null, new FileNode(roots[k])));
top.add(node);
node.add(new DefaultMutableTreeNode(new Boolean(true)));
}
m_model = new DefaultTreeModel(top);
m_tree = new JTree(m_model);
m_tree.putClientProperty("JTree.lineStyle", "Angled");
TreeCellRenderer renderer = new IconCellRenderer();
m_tree.setCellRenderer(renderer);
m_tree.addTreeExpansionListener(new DirExpansionListener());
dirSelectionListener = new DirSelectionListener();
m_tree.addTreeSelectionListener(dirSelectionListener);
m_tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
m_tree.setShowsRootHandles(true);
m_tree.setEditable(false);
m_tree.setScrollsOnExpand(true);
s.getViewport().add(m_tree);
// m_display = new JTextField();
// m_display.setEditable(false);
m_popup = new JPopupMenu();
m_action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (getM_clickedPath() == null) {
return;
}
if (m_tree.isExpanded(getM_clickedPath())) {
m_tree.collapsePath(getM_clickedPath());
} else {
m_tree.expandPath(getM_clickedPath());
}
}
};
m_popup.add(m_action);
m_popup.addSeparator();
Action a3 = new AbstractAction("Open") {
public void actionPerformed(ActionEvent e) {
m_tree.repaint();
DefaultMutableTreeNode treenode = (DefaultMutableTreeNode) m_tree.getSelectionPath().getLastPathComponent();
IconData iconData = (IconData) treenode.getUserObject();
FileNode fileNode = (FileNode) iconData.getObject();
initEvent_ClickChuotVaoCayDuyetFile(fileNode.getFile().getPath());
}
};
m_popup.add(a3);
m_tree.add(m_popup);
m_tree.addMouseListener(new PopupTrigger());
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
//addWindowListener(wndCloser);
//setVisible(true);
}
public int capNhatCay(String path) {
String[] strCacDuongDan = path.split("\\\\");
String strDuongDanHienTai = "";
DefaultMutableTreeNode node = (DefaultMutableTreeNode) m_model.getRoot();
File file = null;
//Đầu tiên tìm node của phân vùng (hơi khác biệt vì dùng hàm listRoors)
for (int i = 0; i < File.listRoots().length; i++){
file = File.listRoots()[i];
if (file.getAbsolutePath().contains(strCacDuongDan[0])){//tìm đúng phân vùng
node = (DefaultMutableTreeNode) m_model.getChild(node, i);
strDuongDanHienTai += strCacDuongDan[0];
break;
}
}
int length = strCacDuongDan.length;
//Nếu là quay về thư mục cha thì loại bỏ 2 cấp (.. và thư mục con gần nhất)
if (strCacDuongDan[length - 1] == "..")
length -= 2;
//Lần lượt tiến sâu theo từng node (các đường dẫn tiếp theo)
for (int i = 1; i < length; i++){
//Lấy đường dẫn tiếp theo
String strDuongDanTiepTheo = strCacDuongDan[i];
//Duyệt xem stt của đường dẫn tiếp theo trong thư mục cha
file = new File(strDuongDanHienTai).getAbsoluteFile();
int j = 0;
for (File filecon : file.listFiles())
{
if (!filecon.isDirectory())
continue;
//Tìm thư mục con thì cập nhật node và đường dẫn hiện tại
if (filecon.getName().equalsIgnoreCase(strDuongDanTiepTheo)){
node = (DefaultMutableTreeNode) m_model.getChild(node, j);
strDuongDanHienTai += "\\" + strDuongDanTiepTheo;
break;
}
else //tăng số thứ tự lên
j++;
}
}
final FileNode filenode = new FileNode(file);
final DefaultMutableTreeNode finalNode = node;
//cập nhật cây
TreePath tf = new TreePath(m_model.getPathToRoot(finalNode));
if (m_clickedPath != tf)
m_tree.fireTreeExpanded(tf);
return m_tree.getSelectionRows()[0] * m_tree.getRowHeight();
}
/**
* lay ra 1 node tren tree
* @param path la duong dan treepath
* @return 1 node
*/
DefaultMutableTreeNode getTreeNode(TreePath path) {
return (DefaultMutableTreeNode) (path.getLastPathComponent());
}
/**
*
* @param node
* @return
*/
FileNode getFileNode(DefaultMutableTreeNode node) {
if (node == null) {
return null;
}
Object obj = node.getUserObject();
if (obj instanceof IconData) {
obj = ((IconData) obj).getObject();
}
if (obj instanceof FileNode) {
return (FileNode) obj;
} else {
return null;
}
}
//Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng)
//http://www.exampledepot.com/egs/java.util/CustEvent.html
// Tạo một listener list
protected javax.swing.event.EventListenerList listenerList =
new javax.swing.event.EventListenerList();
/**
* Phát sinh sử kiện click chuột vào tree
* @param evt tham số cho sự kiện click chuột vào tree (ở đây là tên của file đang được chọn)
*/
// This private class is used to fire MyEvents
void initEvent_ClickChuotVaoCayDuyetFile(String evt) {
Object[] listeners = listenerList.getListenerList();
// Each listener occupies two elements - the first is the listener class
// and the second is the listener instance
for (int i = 0; i < listeners.length; i += 2) {
if (listeners[i] == EventListener_ClickChuotVaoCayDuyetFile.class) {
((EventListener_ClickChuotVaoCayDuyetFile) listeners[i + 1]).Event_ClickChuotVaoCayDuyetFile_Occurred(evt);
}
}
}
/**
* Đăng ký sự kiện cho classes
* @param listener Sự kiện cần đăng ký
*/
public void addEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) {
listenerList.add(EventListener_ClickChuotVaoCayDuyetFile.class, listener);
}
/**
* Gỡ bỏ sự kiện khỏi classes
* @param listener Sự kiện cần gỡ bỏ
*/
public void delEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) {
listenerList.remove(EventListener_ClickChuotVaoCayDuyetFile.class, listener);
}
/**
* cap nhat lai cay duyet file sao khi click chuot vao bang
* @param tree la cay duyet file hien tai
* @param st_file file dang dc chon
*/
public void capNhatCay(CayDuyetFile tree, String st_file) {
tree.initEvent_ClickChuotVaoCayDuyetFile(st_file);
tree.addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() {
public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon) {
}
});
}
/**
* @return the dirSelectionListener
*/
public DirSelectionListener getDirSelectionListener() {
return dirSelectionListener;
}
/**
* @param dirSelectionListener the dirSelectionListener to set
*/
public void setDirSelectionListener(DirSelectionListener dirSelectionListener) {
this.dirSelectionListener = dirSelectionListener;
}
/**
* @return the m_clickedPath
*/
public TreePath getM_clickedPath() {
return m_clickedPath;
}
/**
* Lop PopupTrigger
*/
// NEW
class PopupTrigger extends MouseAdapter {
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
int x = e.getX();
int y = e.getY();
TreePath path = m_tree.getPathForLocation(x, y);
if (path != null) {
if (m_tree.isExpanded(path)) {
m_action.putValue(Action.NAME, "Collapse");
} else {
m_action.putValue(Action.NAME, "Expand");
}
m_popup.show(m_tree, x, y);
m_clickedPath = path;
}
}
}
}
// Make sure expansion is threaded and updating the tree model
// only occurs within the event dispatching thread.
/**
* Lop DirExpansionListener
*/
class DirExpansionListener implements TreeExpansionListener {
public void treeExpanded(TreeExpansionEvent event) {
final DefaultMutableTreeNode node = getTreeNode(
event.getPath());
final FileNode fnode = getFileNode(node);
Thread runner = new Thread() {
public void run() {
if (fnode != null && fnode.expand(node)) {
Runnable runnable = new Runnable() {
public void run() {
m_model.reload(node);
}
};
SwingUtilities.invokeLater(runnable);
}
}
};
runner.start();
m_tree.setSelectionPath(event.getPath());
}
public void treeCollapsed(TreeExpansionEvent event) {
}
}
/**
* Lop Dir SelectionListerner
*/
class DirSelectionListener
implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent event) {
DefaultMutableTreeNode node = getTreeNode(
event.getPath());
FileNode fnode = getFileNode(node);
if (fnode != null) {
// m_display.setText(fnode.getFile().
/// getAbsolutePath());
//initEvent_ClickChuotVaoCayDuyetFile(fnode.getFile().getAbsolutePath());
}
// else
// m_display.setText("");
}
}
}
/**
* Lop IconCellRenderer
* @author Dang Thi Phuong Thao
*/
class IconCellRenderer
extends JLabel
implements TreeCellRenderer {
protected Color m_textSelectionColor;
protected Color m_textNonSelectionColor;
protected Color m_bkSelectionColor;
protected Color m_bkNonSelectionColor;
protected Color m_borderSelectionColor;
protected boolean m_selected;
public IconCellRenderer() {
super();
m_textSelectionColor = UIManager.getColor(
"Tree.selectionForeground");
m_textNonSelectionColor = UIManager.getColor(
"Tree.textForeground");
m_bkSelectionColor = UIManager.getColor(
"Tree.selectionBackground");
m_bkNonSelectionColor = UIManager.getColor(
"Tree.textBackground");
m_borderSelectionColor = UIManager.getColor(
"Tree.selectionBorderColor");
setOpaque(false);
}
public Component getTreeCellRendererComponent(JTree tree,
Object value, boolean sel, boolean expanded, boolean leaf,
int row, boolean hasFocus) {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode) value;
Object obj = node.getUserObject();
setText(obj.toString());
if (obj instanceof Boolean) {
setText("Retrieving data...");
}
if (obj instanceof IconData) {
IconData idata = (IconData) obj;
if (expanded) {
setIcon(idata.getExpandedIcon());
} else {
setIcon(idata.getIcon());
}
} else {
setIcon(null);
}
setFont(tree.getFont());
setForeground(sel ? m_textSelectionColor : m_textNonSelectionColor);
setBackground(sel ? m_bkSelectionColor : m_bkNonSelectionColor);
m_selected = sel;
return this;
}
public void paintComponent(Graphics g) {
Color bColor = getBackground();
Icon icon = getIcon();
g.setColor(bColor);
int offset = 0;
if (icon != null && getText() != null) {
offset = (icon.getIconWidth() + getIconTextGap());
}
g.fillRect(offset, 0, getWidth() - 1 - offset,
getHeight() - 1);
if (m_selected) {
g.setColor(m_borderSelectionColor);
g.drawRect(offset, 0, getWidth() - 1 - offset, getHeight() - 1);
}
super.paintComponent(g);
}
}
/**
* Lop IconData mo ta mot doi tuong chung cho cac node
* @author Dang Thi Phuong Thao
*/
class IconData {
protected Icon m_icon;
protected Icon m_expandedIcon;
protected Object m_data;
public IconData(Icon icon, Object data) {
m_icon = icon;
m_expandedIcon = null;
m_data = data;
}
public IconData(Icon icon, Icon expandedIcon, Object data) {
m_icon = icon;
m_expandedIcon = expandedIcon;
m_data = data;
}
public Icon getIcon() {
return m_icon;
}
public Icon getExpandedIcon() {
return m_expandedIcon != null ? m_expandedIcon : m_icon;
}
public Object getObject() {
return m_data;
}
public String toString() {
return m_data.toString();
}
}
/**
* FileNode la 1 doi tuong file, la mot node tren tree
* @author Dang Thi Phuong Thao
*/
class FileNode {
public final ImageIcon ICON_FOLDER =
new ImageIcon(this.getClass().getResource(".\\resources\\Tree_folder.png"));
public final ImageIcon ICON_EXPANDEDFOLDER =
new ImageIcon(this.getClass().getResource(".\\resources\\Tree_expandedfolder.png"));
protected File m_file;
public FileNode(File file) {
m_file = file;
}
public File getFile() {
return m_file;
}
/**
* Lay ten file va chuyen sang dang chuoi.
* @return
*/
public String toString() {
return m_file.getName().length() > 0 ? m_file.getName() : m_file.getPath();
}
/**
* Kiem tra xem 1 node co the co expand ra node con ko
* @param parent : node cha
* @return: true neu expand dc, false neu expand ko dc
*/
public boolean expand(DefaultMutableTreeNode parent) {
DefaultMutableTreeNode flag =
(DefaultMutableTreeNode) parent.getFirstChild();
if (flag == null) // No flag
{
return false;
}
Object obj = flag.getUserObject();
if (!(obj instanceof Boolean)) {
return false; // Already expanded
}
parent.removeAllChildren(); // Remove Flag
File[] files = listFiles();
if (files == null) {
return true;
}
Vector v = new Vector();
for (int k = 0; k < files.length; k++) {
File f = files[k];
if (!(f.isDirectory())) {
continue;
}
FileNode newNode = new FileNode(f);
boolean isAdded = false;
for (int i = 0; i < v.size(); i++) {
FileNode nd = (FileNode) v.elementAt(i);
if (newNode.compareTo(nd) < 0) {
v.insertElementAt(newNode, i);
isAdded = true;
break;
}
}
if (!isAdded) {
v.addElement(newNode);
}
}
for (int i = 0; i < v.size(); i++) {
FileNode nd = (FileNode) v.elementAt(i);
IconData idata = new IconData(ICON_FOLDER,
ICON_EXPANDEDFOLDER, nd);
DefaultMutableTreeNode node = new DefaultMutableTreeNode(idata);
parent.add(node);
if (nd.hasSubDirs()) {
node.add(new DefaultMutableTreeNode(
new Boolean(true)));
}
}
return true;
}
/**
* Kiem tra xem trong cac file co thu muc con ko
* @return true neu co thu muc con, false neu ko co
*/
public boolean hasSubDirs() {
File[] files = listFiles();
if (files == null) {
return false;
}
for (int k = 0; k < files.length; k++) {
if (files[k].isDirectory()) {
return true;
}
}
return false;
}
public int compareTo(FileNode toCompare) {
return m_file.getName().compareToIgnoreCase(
toCompare.m_file.getName());
}
/**
* lay ra danh sach cac file neu co
* neu ko co thi thong bao loi
* @return danh sach cac file co trong m_file
*/
protected File[] listFiles() {
if (!m_file.isDirectory()) {
return null;
}
try {
return m_file.listFiles();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error reading directory " + m_file.getAbsolutePath(),
"Warning", JOptionPane.WARNING_MESSAGE);
return null;
}
}
} | Java |
package DuyetFile;
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski
ISBN: 1-893115-78-X
Publisher: APress
*/
import QuanLyFile.BoQuanLyFile;
import doan_totalcommander_002.*;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import sun.awt.shell.ShellFolder;
/**
* Lớp đối tượng dùng để hiện thị các file trong một thư mục
* @author Administrator
*/
public class BangDuyetFile {
private String tenThuMucHienHanh;
private Object[][] cacDongDuLieu;
private JScrollPane scrollPane_HienThiBang;
private DroppableTable bangHienThiThuMucHienHanh;
private TableModel modelBangHienThi;
private int kichThuocIcon = 24;
public BangDuyetFile(String myTenFile, JScrollPane myScrollPane) {
tenThuMucHienHanh = myTenFile;
scrollPane_HienThiBang = myScrollPane;
//Phần này tham khảo source từ nhiều nguồn trên mạng!!!
//http://www.java2s.com/Code/Java/Swing-JFC/ColumnSampleTableModel.htm 08
modelBangHienThi = new AbstractTableModel() {
Object Data[][] = cacDongDuLieu;
String columnNames[] = {"Icon", "Tên", "Cỡ", "Đường dẫn tuyệt đối"};
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return cacDongDuLieu.length;
}
public Object getValueAt(int row, int column) {
return cacDongDuLieu[row][column];
}
@Override
public Class getColumnClass(int column) {
return (getValueAt(0, column).getClass());
}
};
bangHienThiThuMucHienHanh = new DroppableTable(getModelBangHienThi(),this) {
@Override
/**
* Them tooltip cho tung cell
*/
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
JComponent jcomp = (JComponent) comp;
if (comp == jcomp) {
File file = new File(getTenFile());
jcomp.setToolTipText(file.getPath() + "\\" + (String) getValueAt(row, 1));
}
return comp;
}
};
capNhatBangDuyetThuMuc(myTenFile, myScrollPane);
bangHienThiThuMucHienHanh.addMouseListener(new MouseAdapter() {
//Xu ly su kien click vao _bangHienThiThuMucHienHanh
@Override
// Xử lý xử kiện người dùng click chuột vào bảng
public void mousePressed(MouseEvent evt) {
xuLyClickChuot(evt);
}
});
//<Chỉnh các thuộc tính cho giao diên của table>
int Heigth = kichThuocIcon;//Chieu cao cua icon
bangHienThiThuMucHienHanh.setRowHeight(Heigth);
bangHienThiThuMucHienHanh.setShowHorizontalLines(false);
bangHienThiThuMucHienHanh.setShowVerticalLines(false);
bangHienThiThuMucHienHanh.getColumnModel().getColumn(0).setMinWidth(kichThuocIcon + 3);
bangHienThiThuMucHienHanh.getColumnModel().getColumn(0).setMaxWidth(kichThuocIcon + 3);
bangHienThiThuMucHienHanh.getColumnModel().getColumn(2).setMinWidth(70);
bangHienThiThuMucHienHanh.getColumnModel().getColumn(2).setMaxWidth(70);
bangHienThiThuMucHienHanh.getColumnModel().getColumn(3).setMinWidth(0);
bangHienThiThuMucHienHanh.getColumnModel().getColumn(3).setMaxWidth(0);
bangHienThiThuMucHienHanh.getColumnModel().getColumn(3).setPreferredWidth(0);
//</Chỉnh các thuộc tính cho giao diên của table>
bangHienThiThuMucHienHanh.addRowSelectionInterval(0, 0);
//bangHienThiThuMucHienHanh.setAutoCreateRowSorter(true);
scrollPane_HienThiBang.setViewportView(bangHienThiThuMucHienHanh);
}
public void xuLyClickChuot(MouseEvent evt) {
bangHienThiThuMucHienHanh = (DroppableTable) evt.getComponent();
int selectedRow = bangHienThiThuMucHienHanh.getSelectedRow();
String str_TenFileDuocChon = getTenFile();
phatSinhSuKien_ClickChuotVaoBangDuyetFile(str_TenFileDuocChon, evt.getClickCount());
if (!getTenFile().endsWith("\\")) {
str_TenFileDuocChon += "\\";
}
if (evt.getButton() != 1 || evt.getClickCount() != 2) {
return;
}
str_TenFileDuocChon += bangHienThiThuMucHienHanh.getValueAt(selectedRow, 1).toString();
if (bangHienThiThuMucHienHanh.getValueAt(selectedRow, 1).toString().equals("..")) {
//Nếu là click đơn thì bỏ qua
quayVeThuMucCha();
return;
}
//Xác định file đang được chọn
File file = new File(str_TenFileDuocChon);
//Xử lý mở file hoặc duyệt vào thư mục con.
getScrollPane_HienThiBang().setToolTipText(tenThuMucHienHanh);
if (file.isFile()) {
String str_PhanMoRong = str_TenFileDuocChon.substring(str_TenFileDuocChon.lastIndexOf("."), str_TenFileDuocChon.length());
if (str_PhanMoRong.compareToIgnoreCase(".lnk") == 0) {
//nếu là file shortcut
try {
ShellFolder sh = ShellFolder.getShellFolder(file.getAbsoluteFile());
//Lấy link và duyệt thư mục trong link
file = new File(sh.getLinkLocation().getPath());
if (file.isFile()) {
try {
Desktop.getDesktop().open(file);
} catch (IOException ex) {
Logger.getLogger(BangDuyetFile.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
//nếu dẫn tới thư mục
setTenFile(file.getPath());
capNhatBangDuyetThuMuc(tenThuMucHienHanh, getScrollPane_HienThiBang());
}
} catch (FileNotFoundException ex) {
Logger.getLogger(BangDuyetFile.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
Desktop.getDesktop().open(file);
} catch (IOException ex) {
Logger.getLogger(BangDuyetFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
setTenFile(str_TenFileDuocChon);
capNhatBangDuyetThuMuc(tenThuMucHienHanh, getScrollPane_HienThiBang()); //new BangDuyetFile(getTenFile(),_scrollPane_HienThiBang);
}
return;
}
// <editor-fold defaultstate="collapsed" desc="Đã hoàn thành">
/**
* Rút gọn phần thập phân của một số
* @param i_SoCanLamTron số cần làm rút gọn
* @param i_SoLuongChuSoSauDauCham số lượng số sau dấu "." cần lầy
* @return s ố đã được làm rút gọn
* Ví dụ: lamTronPhanThapPhan(3.146,2) return 3.14
* Cần cải tiến thêm thành hàm làm tròn
*/
public static double rutGonPhanThapPhan(double i_SoCanLamTron, int i_SoLuongChuSoSauDauCham) {
double Kq = 0;
String Temp = String.valueOf(i_SoCanLamTron);
int viTriCuoiCanLay = Math.min(Temp.lastIndexOf(".") + i_SoLuongChuSoSauDauCham - 1, String.valueOf(i_SoCanLamTron).length());
Temp = Temp.substring(0, viTriCuoiCanLay);
Kq = Double.parseDouble(Temp);
return Kq;
}
/**
* Đếm xem trong thư mục có bao nhiêu file (không tính thư mục)
* @param file_ThuMucCanDem Thư mục cần đếm
* @return
*/
public static int demSoLuongFileTrongThuMuc(File file_ThuMucCanDem) {
int Kq = 0;
if (file_ThuMucCanDem.isDirectory()) {
for (File file : file_ThuMucCanDem.listFiles()) {
if (file.isFile()) {
Kq++;
}
}
}
return Kq;
}
/**
* Quay trở về thư mục cha của thư mục hiện hành (nếu có)
*/
public void quayVeThuMucCha() {
File file = new File(getScrollPane_HienThiBang().getToolTipText());
if (file.getParentFile() != null) {
setTenFile(file.getParent());
getScrollPane_HienThiBang().setToolTipText(tenThuMucHienHanh);
capNhatBangDuyetThuMuc(tenThuMucHienHanh,getScrollPane_HienThiBang());
}
}
/**
* @return the _tenThuMucHienHanh
*/
public String getTenFile() {
return tenThuMucHienHanh;
}
/**
* @param _tenThuMucHienHanh the _tenThuMucHienHanh to set
*/
public void setTenFile(String tenFile) {
this.tenThuMucHienHanh = tenFile;
}
//Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng)
//http://www.exampledepot.com/egs/java.util/CustEvent.html
// Tạo một listener list
protected javax.swing.event.EventListenerList listenerList =
new javax.swing.event.EventListenerList();
/**
* Phát sinh sử kiện click chuột vào bảng
* @param evt tham số cho sự kiện click chuột vào bảng (ở đây là tên của file đang được chọn)
*/
// This private class is used to fire MyEvents
void phatSinhSuKien_ClickChuotVaoBangDuyetFile(String evt, int iSoLanClick) {
Object[] listeners = listenerList.getListenerList();
// Each listener occupies two elements - the first is the listener class
// and the second is the listener instance
for (int i = 0; i < listeners.length; i += 2) {
if (listeners[i] == EventListener_ClickChuotVaoBangDuyetFile.class) {
((EventListener_ClickChuotVaoBangDuyetFile) listeners[i + 1]).Event_ClickChuotVaoBangDuyetFile_Occurred(evt, iSoLanClick);
}
}
}
/**
* Đăng ký sự kiện cho classes
* @param listener Sự kiện cần đăng ký
*/
public void themEventListener_ClickChuotVaoBangDuyetFile(EventListener_ClickChuotVaoBangDuyetFile listener) {
listenerList.add(EventListener_ClickChuotVaoBangDuyetFile.class, listener);
}
/**
* Gỡ bỏ sự kiện khỏi classes
* @param listener Sự kiện cần gỡ bỏ
*/
public void boEventListener_ClickChuotVaoBangDuyetFile(EventListener_ClickChuotVaoBangDuyetFile listener) {
listenerList.remove(EventListener_ClickChuotVaoBangDuyetFile.class, listener);
}
/**
* @return the _bangHienThiThuMucHienHanh
*/
public DroppableTable getTable() {
return bangHienThiThuMucHienHanh;
}
/**
* @param _bangHienThiThuMucHienHanh the _bangHienThiThuMucHienHanh to set
*/
public void setTable(DroppableTable table) {
this.bangHienThiThuMucHienHanh = table;
}
/**
* duyệt các thư mục và file con bên trong một thư mục và hiện thị vào _bangHienThiThuMucHienHanh
* @param str_FileName đường dẫn thư mục cần duyệt
* @param myScrollPane JScrollPane hiện thị bảng
*/
public void capNhatBangDuyetThuMuc(String str_FileName, JScrollPane myScrollPane) {
if (!new File(str_FileName).exists())
return;
String fileTrucoc = tenThuMucHienHanh;
tenThuMucHienHanh = str_FileName;
scrollPane_HienThiBang = myScrollPane;
//Phần này tham khảo source từ nhiều nguồn trên mạng!!!
//http://www.java2s.com/Code/Java/Swing-JFC/ColumnSampleTableModel.htm
int SoThuocTinh = 4;
File file = new File(getTenFile()).getAbsoluteFile();
setTenFile(file.getPath());
myScrollPane.setToolTipText(file.getPath());
File files[] = (new File(getTenFile())).listFiles();
if (files == null) {
//JOptionPane.showMessageDialog(null, "Không duyệt được thư mục " + _tenThuMucHienHanh);
cacDongDuLieu = new Object[1][SoThuocTinh];
cacDongDuLieu[0][0] = new ImageIcon();
cacDongDuLieu[0][1] = "";
cacDongDuLieu[0][2] = "";
cacDongDuLieu[0][3] = "";
} else {
cacDongDuLieu = new Object[files.length + 1][SoThuocTinh];//thêm một dòng thư mục cha
int SoLuongFileCon = demSoLuongFileTrongThuMuc(new File(getTenFile()));
//Các thư mục tạm để phân loại file hay thư mục
Object rowFiles[][] = new Object[SoLuongFileCon][SoThuocTinh];
int indexFiles = 0;
Object rowFolders[][] = new Object[files.length - SoLuongFileCon][SoThuocTinh];
int indexFolders = 0;
//Các giá trị của KB, MB, GB để xác định size phù hợp của file
double KB = jEnum_CacEnumTrongBai.KB.value();
double MB = jEnum_CacEnumTrongBai.MB.value();
double GB = jEnum_CacEnumTrongBai.GB.value();
Icon icon = null;
//Duyệt danh sách các file trong thư mục
for (int i = 0; i < files.length; i++) {
file = files[i];
ShellFolder sf1;
try {
//Lấy icon tên của file và đường dẫn của thư mục hiện hành
cacDongDuLieu[i][1] = file.getName();
cacDongDuLieu[i][3] = file.getAbsolutePath();
sf1 = ShellFolder.getShellFolder(file);
icon = new ImageIcon(sf1.getIcon(true));
icon = BoCoGianImage.coGianImageIcon(new ImageIcon(sf1.getIcon(true)),
kichThuocIcon, kichThuocIcon, Image.SCALE_SMOOTH);
cacDongDuLieu[i][0] = icon;
} catch (FileNotFoundException ex) {
Logger.getLogger(BangDuyetFile.class.getName()).log(Level.SEVERE, null, ex);
}
//Tạo chuổi kích thước file thích hợp và đưa vào mảng tạm file nếu là file
if (file.isFile()) {
//_cacDongDuLieu[i][2] = file.getName().substring(file.getName().lastIndexOf("."));
double filesize = file.length();
if (filesize / GB > 0.9) {//GB
cacDongDuLieu[i][2] = String.valueOf(rutGonPhanThapPhan(filesize / GB, 3)) + " GB";
} else if (filesize / MB > 0.9) {//MB
cacDongDuLieu[i][2] = String.valueOf(rutGonPhanThapPhan(filesize / MB, 3)) + " MB";
} else if (filesize / KB > 0.9) {//KB
cacDongDuLieu[i][2] = String.valueOf(rutGonPhanThapPhan(filesize / KB, 3)) + " KB";
} else {
cacDongDuLieu[i][2] = String.valueOf(filesize) + " bytes";
}
rowFiles[indexFiles++] = cacDongDuLieu[i];
} else {//Nếu là thư mục thì đưa vào mảng tạm thông tin các thư mục
cacDongDuLieu[i][2] = "Folder";
rowFolders[indexFolders++] = cacDongDuLieu[i];
}
}
int index = 0;
file = new File(tenThuMucHienHanh);
if (file.getParentFile() != null && !file.getPath().startsWith("\\")) {
//Nếu có thư mục cha và không phải đang truy cập mạng
index++;
cacDongDuLieu = new Object[files.length + 1][SoThuocTinh];//thêm một dòng thư mục cha
//Tạo dòng thư mục cha
icon = BoCoGianImage.coGianImageIcon(new ImageIcon(this.getClass().getResource("../doan_totalcommander_002/resources/Up.png")),
kichThuocIcon, kichThuocIcon, Image.SCALE_SMOOTH);
cacDongDuLieu[0][0] = icon;
cacDongDuLieu[0][1] = "..";
cacDongDuLieu[0][2] = "Folder";
cacDongDuLieu[0][3] = tenThuMucHienHanh;
}
//Thêm các thư mục trước các file
for (int i = 0; i < rowFolders.length; i++) {
cacDongDuLieu[index++] = rowFolders[i];
}
for (int i = 0; i < rowFiles.length; i++) {
cacDongDuLieu[index++] = rowFiles[i];
}
}
bangHienThiThuMucHienHanh.setModel(getModelBangHienThi());
//JOptionPane.showMessageDialog(null, bangHienThiThuMucHienHanh.getRowCount());
bangHienThiThuMucHienHanh.paintImmediately(bangHienThiThuMucHienHanh.getBounds());
myScrollPane.setViewportView(bangHienThiThuMucHienHanh);
//System.setProperty("user.dir", getTenFile());
if (!fileTrucoc.equalsIgnoreCase(tenThuMucHienHanh))
phatSinhSuKien_ClickChuotVaoBangDuyetFile(getTenFile(), 2);
}
/**
* Trả về đường dẫn đầy đủ của file đang được chọn trong bảng hiện thị.
* @return đường dẫn
*/
public ArrayList<String> layDuongDanDayDuFileDangDuocChon() {
String str_ThuMucHienHanh = getTenFile();
if (!getTenFile().endsWith("\\")) {
str_ThuMucHienHanh += "\\";
}
int[] i_DongDuocChon = bangHienThiThuMucHienHanh.getSelectedRows();
ArrayList<String> als_CacFileDuocChon = new ArrayList<String>();
for (int i : i_DongDuocChon) {
if (cacDongDuLieu[i][1] != "..") {
als_CacFileDuocChon.add(str_ThuMucHienHanh +
bangHienThiThuMucHienHanh.getValueAt(i, 1).toString());
}
}
return als_CacFileDuocChon;
}
/**
* tham khảo tại: http://lwjgl.org/forum/index.php?topic=1956.0
* duyệt một số thư mục đặc biệt như My Documents, Desktop của user hiện tại (đối với win XP)
* @param str_TenThuMucDatBiet tên thư mục muốn duyệt
* @param jTabbedPane TabbedPane chứa ScrollPane chứa bảng duyệt thư mục
*/
public void duyetCacThuMucDatBiet(String str_TenThuMucDatBiet, JTabbedPane jTabbedPane) {
// TODO add your handling code here:
String str_DuongDan = System.getProperty("user.home") + "\\" + str_TenThuMucDatBiet;
capNhatBangDuyetThuMuc(str_DuongDan,getScrollPane_HienThiBang());
jTabbedPane.setTitleAt(0, str_DuongDan);
}
/**
* @return the scrollPane_HienThiBang
*/
public JScrollPane getScrollPane_HienThiBang() {
return scrollPane_HienThiBang;
}
/**
* @return the modelBangHienThi
*/
public TableModel getModelBangHienThi() {
return modelBangHienThi;
}
/**
* @param modelBangHienThi the modelBangHienThi to set
*/
public void setModelBangHienThi(TableModel modelBangHienThi) {
this.modelBangHienThi = modelBangHienThi;
}
}//</editor-fold> | Java |
package DuyetFile;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.EventObject;
/**
*
* @author Dang Thi Phuong Thao
*/
public class Event_ClickVaoCayDuyetFile extends EventObject {
public Event_ClickVaoCayDuyetFile(Object source) {
super(source);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DuyetFile;
import QuanLyFile.BoQuanLyFile;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.TableModel;
/**
*
* @author Administrator
*/
// <editor-fold defaultstate="collapsed" desc="class DroppableTable">
/**
* Lớp DroppableTable là một JTable có khả năng DnD
* tham khảo http://www.codeproject.com/KB/list/dnd.aspx?display=Print
* @author Administrator
*/
public class DroppableTable extends JTable
implements DropTargetListener, DragSourceListener, DragGestureListener {
BoQuanLyFile boQuanLyFile = new BoQuanLyFile();
DropTarget dropTarget = new DropTarget(this, this);
DragSource dragSource = DragSource.getDefaultDragSource();
BangDuyetFile bangDuyetFile;
public DroppableTable(TableModel model, BangDuyetFile bangDuyet) {
bangDuyetFile = bangDuyet;
dragSource.createDefaultDragGestureRecognizer(
this, DnDConstants.ACTION_COPY, this);
setModel(model);
}
//Các hàm bắt buộc phải override
public void dragDropEnd(DragSourceDropEvent DragSourceDropEvent) {
}
public void dragEnter(DragSourceDragEvent DragSourceDragEvent) {
}
public void dragExit(DragSourceEvent DragSourceEvent) {
}
public void dragOver(DragSourceDragEvent DragSourceDragEvent) {
}
public void dropActionChanged(DragSourceDragEvent DragSourceDragEvent) {
}
public void dragEnter(DropTargetDragEvent dropTargetDragEvent) {
dropTargetDragEvent.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
public void dragExit(DropTargetEvent dropTargetEvent) {
}
public void dragOver(DropTargetDragEvent dropTargetDragEvent) {
}
public void dropActionChanged(DropTargetDragEvent dropTargetDragEvent) {
}
/**
* Xử lý xử kiện khi kéo thả file vào DTable
* @param dropTargetDropEvent tham số của xử kiện
*/
public synchronized void drop(DropTargetDropEvent dropTargetDropEvent) {
try {
Transferable tr = dropTargetDropEvent.getTransferable();
//Nếu đối tượng phù hợp được drop
if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
//Đặt xử kiện là copy
dropTargetDropEvent.acceptDrop(DnDConstants.ACTION_COPY);
java.util.List fileList = null;
try {
fileList = (java.util.List) tr.getTransferData(DataFlavor.javaFileListFlavor);
} catch (IOException ex) {
Logger.getLogger(DroppableTable.class.getName()).log(Level.SEVERE, null, ex);
}
//Tương đương foreach
Iterator iterator = fileList.iterator();
while (iterator.hasNext()) {
File file = (File) iterator.next();
boQuanLyFile.copyDirectory(file,
new File(bangDuyetFile.getTenFile() + "\\" + file.getName()), false);
// JOptionPane.showMessageDialog(null, file.getAbsolutePath());
//((DefaultListModel)getModel()).addElement(file.getPath());
bangDuyetFile.capNhatBangDuyetThuMuc(bangDuyetFile.getTenFile(), bangDuyetFile.getScrollPane_HienThiBang());
}
dropTargetDropEvent.getDropTargetContext().dropComplete(true);
} else {
System.err.println("Rejected");
dropTargetDropEvent.rejectDrop();
}
} catch (UnsupportedFlavorException ex) {
ex.printStackTrace();
dropTargetDropEvent.rejectDrop();
Logger.getLogger(DroppableTable.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException io) {
io.printStackTrace();
dropTargetDropEvent.rejectDrop();
}
}
public void dragGestureRecognized(DragGestureEvent dragGestureEvent) {
if (getSelectedRow() == -1) {
return;
}
int obj = getSelectedRow();
if (obj < 0) {
// Nothing selected, nothing to drag
System.out.println("Nothing selected - beep");
getToolkit().beep();
} else {
FileSelection transferable =
new FileSelection(new File(getValueAt(obj, 3).toString()));
dragGestureEvent.startDrag(
DragSource.DefaultCopyDrop,
transferable,
this);
}
}
//</editor-fold>
// <editor-fold defaultstate="collapsed" desc="Class FileSelection">
/**
* Tạo lớp lấy thông tin file được chọn để đưa ra cho WindowsExplorer
* tham khảo http://www.codeproject.com/KB/list/dnd.aspx?display=Print
*/
public class FileSelection extends Vector implements Transferable {
final static int FILE = 0;
final static int STRING = 1;
final static int PLAIN = 2;
DataFlavor flavors[] = {DataFlavor.javaFileListFlavor,
DataFlavor.stringFlavor,
DataFlavor.plainTextFlavor};
public FileSelection(File file) {
addElement(file);
}
/* Returns the array of flavors in which it can provide the data. */
public synchronized DataFlavor[] getTransferDataFlavors() {
return flavors;
}
/* Returns whether the requested flavor is supported by this object. */
/* Kiểm tra xem đối tượng được chọn có hợp lệ không */
public boolean isDataFlavorSupported(DataFlavor flavor) {
boolean b = false;
b |= flavor.equals(flavors[FILE]);
b |= flavor.equals(flavors[STRING]);
b |= flavor.equals(flavors[PLAIN]);
return (b);
}
/**
* If the data was requested in the "java.lang.String" flavor,
* return the String representing the selection.
* trả về đối tượng thích hợp nếu File, hay đường dẫn tuyệt đối của file
*/
public synchronized Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (flavor.equals(flavors[FILE])) {
return this;
} else if (flavor.equals(flavors[PLAIN])) {
return new StringReader(((File) elementAt(0)).getAbsolutePath());
} else if (flavor.equals(flavors[STRING])) {
return ((File) elementAt(0)).getAbsolutePath();
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
}
//</editor-fold>
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DuyetFile;
import java.util.EventObject;
/**
*
* @author Administrator
*/
public class Event_ClickVaoBangDuyetFile extends EventObject {
public Event_ClickVaoBangDuyetFile(Object source) {
super(source);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dialog_SoSanhFile.java
*
* Created on Apr 10, 2009, 2:59:38 AM
*/
package QuanLyFile;
import doan_totalcommander_002.*;
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JScrollBar;
import javax.swing.border.Border;
import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
/**
* hiện thị dialog so sánh 2 file
* @author Administrator
*/
public class Dialog_SoSanhFile extends javax.swing.JFrame {
/** Creates new form Dialog_SoSanhFile */
public Dialog_SoSanhFile() {
initComponents();
}
public Dialog_SoSanhFile(String str_DuongDanFileBenTrai, String str_DuongDanFileBenPhai) throws IOException {
initComponents();
BoQuanLyFile.hienThiFile(str_DuongDanFileBenTrai, jTextPane_BenTrai, jEnum_CacEnumTrongBai.XemFile);
BoQuanLyFile.hienThiFile(str_DuongDanFileBenPhai, jTextPane_BenPhai, jEnum_CacEnumTrongBai.XemFile);
themSuKienScrollBarDiChuyen(jScrollPane_BenTrai.getVerticalScrollBar()
, jScrollPane_BenPhai.getVerticalScrollBar());
themSuKienScrollBarDiChuyen(jScrollPane_BenPhai.getVerticalScrollBar()
, jScrollPane_BenTrai.getVerticalScrollBar());
themSuKienScrollBarDiChuyen(jScrollPane_BenTrai.getHorizontalScrollBar()
, jScrollPane_BenPhai.getHorizontalScrollBar());
themSuKienScrollBarDiChuyen(jScrollPane_BenPhai.getHorizontalScrollBar()
, jScrollPane_BenTrai.getHorizontalScrollBar());
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
jTextPane2 = new javax.swing.JTextPane();
jPanel1 = new javax.swing.JPanel();
jTextField_BenTrai = new javax.swing.JTextField();
jButton_DuyetFileBenPhai = new javax.swing.JButton();
jButton_DuyetFileBenTrai = new javax.swing.JButton();
jButton_SoSanh = new javax.swing.JButton();
jTextField_BenPhai = new javax.swing.JTextField();
jPanel3 = new javax.swing.JPanel();
jSplitPane1 = new javax.swing.JSplitPane();
jScrollPane_BenTrai = new javax.swing.JScrollPane();
jPanel_BenTrai = new javax.swing.JPanel();
jTextPane_BenTrai = new javax.swing.JTextPane();
jScrollPane_BenPhai = new javax.swing.JScrollPane();
jPanel_BenPhai = new javax.swing.JPanel();
jTextPane_BenPhai = new javax.swing.JTextPane();
jScrollPane2.setName("jScrollPane2"); // NOI18N
jTextPane2.setName("jTextPane2"); // NOI18N
jScrollPane2.setViewportView(jTextPane2);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getResourceMap(Dialog_SoSanhFile.class);
setTitle(resourceMap.getString("Form.title")); // NOI18N
setName("Form"); // NOI18N
jPanel1.setName("jPanel1"); // NOI18N
jPanel1.setPreferredSize(new java.awt.Dimension(680, 50));
jTextField_BenTrai.setText(resourceMap.getString("jTextField_BenTrai.text")); // NOI18N
jTextField_BenTrai.setName("jTextField_BenTrai"); // NOI18N
jTextField_BenTrai.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField_BenTraiActionPerformed(evt);
}
});
jButton_DuyetFileBenPhai.setText(resourceMap.getString("jButton_DuyetFileBenPhai.text")); // NOI18N
jButton_DuyetFileBenPhai.setName("jButton_DuyetFileBenPhai"); // NOI18N
jButton_DuyetFileBenPhai.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_DuyetFileBenPhaiActionPerformed(evt);
}
});
jButton_DuyetFileBenTrai.setText(resourceMap.getString("jButton_DuyetFileBenTrai.text")); // NOI18N
jButton_DuyetFileBenTrai.setName("jButton_DuyetFileBenTrai"); // NOI18N
jButton_DuyetFileBenTrai.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_DuyetFileBenTraiActionPerformed(evt);
}
});
jButton_SoSanh.setText(resourceMap.getString("jButton_SoSanh.text")); // NOI18N
jButton_SoSanh.setName("jButton_SoSanh"); // NOI18N
jButton_SoSanh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_SoSanhActionPerformed(evt);
}
});
jTextField_BenPhai.setName("jTextField_BenPhai"); // NOI18N
jTextField_BenPhai.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField_BenPhaiActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField_BenTrai)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_DuyetFileBenTrai)
.addGap(64, 64, 64)
.addComponent(jButton_SoSanh)
.addGap(52, 52, 52)
.addComponent(jButton_DuyetFileBenPhai, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField_BenPhai)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_BenTrai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_DuyetFileBenTrai)
.addComponent(jTextField_BenPhai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_DuyetFileBenPhai)
.addComponent(jButton_SoSanh))
.addContainerGap(16, Short.MAX_VALUE))
);
getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);
jPanel3.setName("jPanel3"); // NOI18N
jPanel3.setPreferredSize(new java.awt.Dimension(544, 524));
jSplitPane1.setDividerLocation(500);
jSplitPane1.setName("jSplitPane1"); // NOI18N
jSplitPane1.setPreferredSize(getPreferredSize());
jScrollPane_BenTrai.setBorder(null);
jScrollPane_BenTrai.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane_BenTrai.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane_BenTrai.setViewportBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jScrollPane_BenTrai.viewportBorder.title"))); // NOI18N
jScrollPane_BenTrai.setName("jScrollPane_BenTrai"); // NOI18N
jPanel_BenTrai.setName("jPanel_BenTrai"); // NOI18N
jPanel_BenTrai.setPreferredSize(new java.awt.Dimension(32767, 32767));
jTextPane_BenTrai.setBorder(null);
jTextPane_BenTrai.setName("jTextPane_BenTrai"); // NOI18N
javax.swing.GroupLayout jPanel_BenTraiLayout = new javax.swing.GroupLayout(jPanel_BenTrai);
jPanel_BenTrai.setLayout(jPanel_BenTraiLayout);
jPanel_BenTraiLayout.setHorizontalGroup(
jPanel_BenTraiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1466, Short.MAX_VALUE)
.addGroup(jPanel_BenTraiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_BenTraiLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextPane_BenTrai, javax.swing.GroupLayout.DEFAULT_SIZE, 1446, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel_BenTraiLayout.setVerticalGroup(
jPanel_BenTraiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1017, Short.MAX_VALUE)
.addGroup(jPanel_BenTraiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_BenTraiLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextPane_BenTrai, javax.swing.GroupLayout.DEFAULT_SIZE, 995, Short.MAX_VALUE)
.addContainerGap()))
);
jScrollPane_BenTrai.setViewportView(jPanel_BenTrai);
jSplitPane1.setLeftComponent(jScrollPane_BenTrai);
jScrollPane_BenPhai.setBorder(null);
jScrollPane_BenPhai.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane_BenPhai.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane_BenPhai.setViewportBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jScrollPane_BenPhai.viewportBorder.title"))); // NOI18N
jScrollPane_BenPhai.setName("jScrollPane_BenPhai"); // NOI18N
jPanel_BenPhai.setName("jPanel_BenPhai"); // NOI18N
jPanel_BenPhai.setPreferredSize(new java.awt.Dimension(32767, 32767));
jTextPane_BenPhai.setBorder(null);
jTextPane_BenPhai.setName("jTextPane_BenPhai"); // NOI18N
javax.swing.GroupLayout jPanel_BenPhaiLayout = new javax.swing.GroupLayout(jPanel_BenPhai);
jPanel_BenPhai.setLayout(jPanel_BenPhaiLayout);
jPanel_BenPhaiLayout.setHorizontalGroup(
jPanel_BenPhaiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_BenPhaiLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextPane_BenPhai, javax.swing.GroupLayout.DEFAULT_SIZE, 1446, Short.MAX_VALUE)
.addContainerGap())
);
jPanel_BenPhaiLayout.setVerticalGroup(
jPanel_BenPhaiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_BenPhaiLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextPane_BenPhai, javax.swing.GroupLayout.DEFAULT_SIZE, 995, Short.MAX_VALUE)
.addContainerGap())
);
jScrollPane_BenPhai.setViewportView(jPanel_BenPhai);
jSplitPane1.setRightComponent(jScrollPane_BenPhai);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE)
);
getContentPane().add(jPanel3, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
// <editor-fold defaultstate="collapsed" desc="Đã hoàn thành(themSuKienScroollBarDiChuyen, doiTitle)">
/**
* Đổi title cho border của JComponent
* @param jcomponent component cần đổi title
* @param str_Title title mới
*/
/**
* Them sự kiện khi người dùng di chuyển scrollbar thì scrollbar ảnh hưởng cũng di chuyển theo
* Giúp cho việc so sánh các file bằng mắt dể dàng hơn
* @param scrollBarDiChuyen scroll di chuyển
* @param scrollBarAnhHuong scroll di chuyển theo
*/
private void themSuKienScrollBarDiChuyen(JScrollBar scrollBarDiChuyen, final JScrollBar scrollBarAnhHuong) {
scrollBarDiChuyen.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
if (!scrollBarAnhHuong.getValueIsAdjusting()) {
scrollBarAnhHuong.setValue(e.getValue());
}
}
});
}
/**
* đổi title của border của một component
* @param jcomponent component cần đổi title
* @param str_Title title mới
*/
private void doiTitleCuaBorder(JComponent jcomponent, String str_Title) {
// TODO add your handling code here:
Border borderHienTai = jcomponent.getBorder();
borderHienTai = BorderFactory.createTitledBorder(borderHienTai, str_Title);
jcomponent.setBorder(borderHienTai);
}
//</editor-fold>
private void toMauKhacBiet(boolean b_phanBietHoaThuong){
//Tạo AttributeSet chữ màu đỏ.
MutableAttributeSet mA_KhacBiet = new SimpleAttributeSet();
StyleConstants.setForeground(mA_KhacBiet, Color.RED);
//Tạo AttributeSet chữ thường.
MutableAttributeSet mA_Giong = new SimpleAttributeSet();
StyleConstants.setForeground(mA_Giong, Color.BLACK);
//Lấy doc của 2 jtextpane
StyledDocument document_BenTrai = jTextPane_BenTrai.getStyledDocument();
StyledDocument document_BenPhai = jTextPane_BenPhai.getStyledDocument();
//Trả doc về kiểu thường
document_BenPhai.setCharacterAttributes(0, document_BenPhai.getLength(), mA_Giong, false);
document_BenTrai.setCharacterAttributes(0, document_BenTrai.getLength(), mA_Giong, false);
int i = 0;
int i_nganhon = Math.min(document_BenPhai.getLength(), document_BenTrai.getLength());
while (i < i_nganhon){//duyệt từng phần của của doc ngắn hơn
try {
//duyệt từng phần của của doc ngắn hơn
if (b_phanBietHoaThuong){//Nếu phân biệt hoa thường dùng hàm equals
if (!document_BenTrai.getText(i, 1).equals(document_BenPhai.getText(i, 1))) {
document_BenPhai.setCharacterAttributes(i, 1, mA_KhacBiet, false);
document_BenTrai.setCharacterAttributes(i, 1, mA_KhacBiet, false);
}
}
else//equalsIgnoreCase
if (!document_BenTrai.getText(i, 1).equalsIgnoreCase(document_BenPhai.getText(i, 1))) {
document_BenPhai.setCharacterAttributes(i, 1, mA_KhacBiet, false);
document_BenTrai.setCharacterAttributes(i, 1, mA_KhacBiet, false);
}
i++;
} catch (BadLocationException ex) {
Logger.getLogger(Dialog_SoSanhFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Sau khi so sánh xong phần ngắn hơn, tất cả những phần còn lại của bên dài hơn đều tô màu
if(i_nganhon == document_BenTrai.getLength())
document_BenPhai.setCharacterAttributes(i, document_BenPhai.getLength() - i, mA_KhacBiet, false);
else
document_BenTrai.setCharacterAttributes(i, document_BenTrai.getLength() - i, mA_KhacBiet, false);
//Dat lại styled document cho jtextpane
jTextPane_BenTrai.setStyledDocument(document_BenTrai);
jTextPane_BenPhai.setStyledDocument(document_BenPhai);
}
private void jButton_DuyetFileBenPhaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DuyetFileBenPhaiActionPerformed
// TODO add your handling code here:
try {
String str_duongDanDuocChon = moDialogChonFile();
if (str_duongDanDuocChon.equals("")) {
return; //Nếu không chọn file nào cả
}
jTextField_BenPhai.setText(str_duongDanDuocChon);
BoQuanLyFile.hienThiFile(str_duongDanDuocChon, jTextPane_BenPhai, jEnum_CacEnumTrongBai.XemFile);
} catch (IOException ex) {
Logger.getLogger(Dialog_SoSanhFile.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton_DuyetFileBenPhaiActionPerformed
private void jButton_DuyetFileBenTraiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DuyetFileBenTraiActionPerformed
try {
String str_duongDanDuocChon = moDialogChonFile();
if (str_duongDanDuocChon.equals("")) {
return; //Nếu không chọn file nào cả
}
jTextField_BenTrai.setText(str_duongDanDuocChon);
BoQuanLyFile.hienThiFile(str_duongDanDuocChon, jTextPane_BenTrai, jEnum_CacEnumTrongBai.XemFile);
} catch (IOException ex) {
Logger.getLogger(Dialog_SoSanhFile.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton_DuyetFileBenTraiActionPerformed
private void jTextField_BenTraiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_BenTraiActionPerformed
if (!new File (jTextField_BenTrai.getText()).isFile())
return;
try {
// TODO add your handling code here:
BoQuanLyFile.hienThiFile(jTextField_BenTrai.getText(),
jTextPane_BenTrai, jEnum_CacEnumTrongBai.XemFile);
} catch (IOException ex) {
Logger.getLogger(Dialog_SoSanhFile.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jTextField_BenTraiActionPerformed
private void jTextField_BenPhaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_BenPhaiActionPerformed
// TODO add your handling code here:
if (!new File (jTextField_BenPhai.getText()).isFile())
return;
try {
// TODO add your handling code here:
BoQuanLyFile.hienThiFile(jTextField_BenPhai.getText(),
jTextPane_BenPhai, jEnum_CacEnumTrongBai.XemFile);
} catch (IOException ex) {
Logger.getLogger(Dialog_SoSanhFile.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jTextField_BenPhaiActionPerformed
private void jButton_SoSanhActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SoSanhActionPerformed
// TODO add your handling code here:
toMauKhacBiet(true);
}//GEN-LAST:event_jButton_SoSanhActionPerformed
/**
* Mở dialog cho phép chọn file
* @return đường dẫn file được chọn
* @throws java.awt.HeadlessException
*/
private String moDialogChonFile() throws HeadlessException {
// TODO add your handling code here:
JFileChooser fc = new JFileChooser();
//Mở dialog
fc.showOpenDialog(this);
File fileDuocChon = fc.getSelectedFile();
if (fileDuocChon != null)
//if (fc.get)
return fileDuocChon.getPath();
return "";
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Dialog_SoSanhFile().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_DuyetFileBenPhai;
private javax.swing.JButton jButton_DuyetFileBenTrai;
private javax.swing.JButton jButton_SoSanh;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel_BenPhai;
private javax.swing.JPanel jPanel_BenTrai;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane_BenPhai;
private javax.swing.JScrollPane jScrollPane_BenTrai;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JTextField jTextField_BenPhai;
private javax.swing.JTextField jTextField_BenTrai;
private javax.swing.JTextPane jTextPane2;
private javax.swing.JTextPane jTextPane_BenPhai;
private javax.swing.JTextPane jTextPane_BenTrai;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dialog_CatNho.java
*
* Created on Apr 10, 2009, 6:38:44 PM
*/
package QuanLyFile;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
* hiện thị dialog cắt nhỏ file
* @author Administrator
*/
public class Dialog_GhepNoi extends javax.swing.JDialog {
/** Creates new form Dialog_CatNho */
public Dialog_GhepNoi(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jTextField_FileDich = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jTextField_FileDauTien = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jButton_Ghep = new javax.swing.JButton();
jButton_Thoát = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getResourceMap(Dialog_GhepNoi.class);
setTitle(resourceMap.getString("Form.title")); // NOI18N
setName("Form"); // NOI18N
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
jPanel1.setName("jPanel1"); // NOI18N
jTextField_FileDich.setText(resourceMap.getString("jTextField_FileDich.text")); // NOI18N
jTextField_FileDich.setName("jTextField_FileDich"); // NOI18N
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jTextField_FileDauTien.setText(resourceMap.getString("jTextField_FileDauTien.text")); // NOI18N
jTextField_FileDauTien.setName("jTextField_FileDauTien"); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel1))
.addGap(9, 9, 9)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField_FileDich, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
.addComponent(jTextField_FileDauTien, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_FileDauTien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_FileDich, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2.setName("jPanel2"); // NOI18N
jButton_Ghep.setText(resourceMap.getString("jButton_Ghep.text")); // NOI18N
jButton_Ghep.setName("jButton_Ghep"); // NOI18N
jButton_Ghep.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_GhepActionPerformed(evt);
}
});
jButton_Thoát.setText(resourceMap.getString("jButton_Thoát.text")); // NOI18N
jButton_Thoát.setName("jButton_Thoát"); // NOI18N
jButton_Thoát.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ThoátActionPerformed(evt);
}
});
jLabel2.setForeground(resourceMap.getColor("jLabel2.foreground")); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_Ghep, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Thoát)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_Thoát)
.addComponent(jButton_Ghep)
.addComponent(jLabel2))
.addContainerGap(16, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_GhepActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_GhepActionPerformed
File fileDich = new File(jTextField_FileDich.getText());
File fileNguon = new File(jTextField_FileDich.getText());
if (fileDich.getUsableSpace() < fileNguon.length()){
JOptionPane.showMessageDialog(null, "Không đủ dung lượng ổ cứng!");
return;
}
if (JOptionPane.showConfirmDialog(null, "Bạn muốn nối file? File đích (nếu có) sẽ bị xóa!!!"
, "Xác nhận ghép", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION)
return;
try {
// TODO add your handling code here:
// Lấy kích thước file sau khi cắt
int i_SoFile = BoQuanLyFile.ghepFile(jTextField_FileDauTien.getText(), jTextField_FileDich.getText());
//Thông báo thành công và xác nhận thoát
if (JOptionPane.showConfirmDialog(null, "Nối thành công! " + i_SoFile + " Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
dispose();
} catch (IOException ex) {
Logger.getLogger(Dialog_GhepNoi.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Nối file thất bại! Lỗi: " + ex.getMessage());
}
}//GEN-LAST:event_jButton_GhepActionPerformed
private void jButton_ThoátActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ThoátActionPerformed
// TODO add your handling code here:
if (JOptionPane.showConfirmDialog(null, "Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
dispose();
}//GEN-LAST:event_jButton_ThoátActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Dialog_GhepNoi dialog = new Dialog_GhepNoi(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_Ghep;
private javax.swing.JButton jButton_Thoát;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JTextField jTextField_FileDauTien;
private javax.swing.JTextField jTextField_FileDich;
// End of variables declaration//GEN-END:variables
/**
* @param jTextField_FileNguon the jTextField_FileNguon to set
*/
public void setTextOfJTextField_FileNguon(String str_DuongDanFileNguon) {
this.jTextField_FileDauTien.setText(str_DuongDanFileNguon);
}
/**
* @param jTextField_ThuMucDich the jTextField_ThuMucDich to set
*/
public void setTextOfJTextField_ThuMucDich(String str_DuongDanThuMucDich) {
this.jTextField_FileDich.setText(str_DuongDanThuMucDich);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package QuanLyFile;
import doan_totalcommander_002.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
/**
* gồm các hàm hộ trở xử lý file như hiện thị file, doc file...
* @author Administrator
*/
public class BoQuanLyFile extends JComponent{
// <editor-fold defaultstate="collapsed" desc="Đã hoàn thành">
/**
*
* Hiện thị binary code của file vào jScrollPane
* @param str_DuongDanFile đường dẫn file cần hiện thị
* @param jScrollPane ScrollPane chứa textpane hiện thị
* @param enumLoaiTruyXuat Loại hiện thị ví dụ: jEnum_CacEnumTrongBai.SuaFile
*/
public static void hienThiFile (String str_DuongDanFile, JTextPane jTextPane, jEnum_CacEnumTrongBai enumLoaiTruyXuat)
throws IOException {
File file = new File(str_DuongDanFile);
if (!file.exists()){
JOptionPane.showMessageDialog(null, "Không tìm thấy file " + str_DuongDanFile);
return;
}
jTextPane.setText(docFile(str_DuongDanFile));
//Set edit cho textpane phù hợp
jTextPane.setEditable(enumLoaiTruyXuat == jEnum_CacEnumTrongBai.SuaFile);
}
/**
* Đọc 1 file và trả về một String dữ liệu trong file
* @param str_DuongDan đường dẫn đến file cần đọc
* @return dữ liệu trả về kiển string
* @throws java.io.IOException
*/
private static String docFile(String str_DuongDan)throws java.io.IOException{
StringBuffer strbuff_DuLieu = new StringBuffer(1000);
BufferedReader buffReader = new BufferedReader(new FileReader(str_DuongDan));
char[] buf = new char[1024];
int numRead=0;
while((numRead=buffReader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
strbuff_DuLieu.append(readData);
buf = new char[1024];
}
buffReader.close();
return strbuff_DuLieu.toString();
}
/**
* Ghi một string vào file
* @param str_DuongDan đường dẫn file cần ghi
* @param str_DuLieu dữ liệu cần ghi
* @throws java.io.IOException
*/
public static void ghiFile(String str_DuongDan, String str_DuLieu)throws java.io.IOException{
BufferedWriter buffWriter = new BufferedWriter(new FileWriter(str_DuongDan));
buffWriter.write(str_DuLieu);
buffWriter.close();
}
/**
*
* copy nội dung của file nguồn sng9 file đích
* @param srFile đường dẫn file nguồn
* @param dtFile đường dẫn file đích
*
*/
public static void copyfile(String srFile, String dtFile) throws FileNotFoundException, IOException{
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
//For Append the file.
// OutputStream out = new FileOutputStream(f2,true);
//For Overwrite the file.
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
/**
* Tạo tên mặc định cho thư mục mới có dạng NewFolderx với x từ 0 đến 2^20
* @param str_DuongDanThuMucCha Đường dẫn đến thư mục cha của thư mục cần tạo để xác định số
* folder có tên dạng NewFolderx đang có trong thư mục cha
* @return tên được tạo
*/
public static String taoTenThuMucMoiMacDinh (String str_DuongDanThuMucCha){
String str_TenThuMucMoi = "NewFolder";
String str_DuongDanDayDuThuMucCanTao = str_DuongDanThuMucCha + "\\" + str_TenThuMucMoi;
File file = new File(str_DuongDanDayDuThuMucCanTao);
if (!file.exists() && !file.isDirectory()){
return str_DuongDanDayDuThuMucCanTao;
}
int i = 1;
for (; i < Math.pow(2, 20); i++){
file = new File(str_DuongDanDayDuThuMucCanTao + String.valueOf(i));
if (!file.exists() && !file.isDirectory()){
str_DuongDanDayDuThuMucCanTao += String.valueOf(i);
break;
}
}
return str_DuongDanDayDuThuMucCanTao;
}
/**
* Tạo một thư mục mới
* @param str_DuongDan Đường dẫn đầy đủ (bao gồm tên) của thư mục cần tạo
*/
public static void taoThuMucMoi (String str_DuongDan){
File file = new File(str_DuongDan);
if(!file.mkdirs())
JOptionPane.showMessageDialog(null, "Không thể tạo thư mục!");
}
/**
* Tạo một file mới
* @param str_DuongDan Đường dẫn đầy đủ (bao gồm tên) của thư mục cần tạo
*/
public static void taoFileMoi (String str_DuongDan) throws IOException{
File file = new File(str_DuongDan);
if(!file.createNewFile())
JOptionPane.showMessageDialog(null, "Không thể tạo file!");
}
/**
*
* copy folder,file sang đường dẫn khác
* @param srcPath đường dẫn file,folder nguồn
* @param dstpath đường dẫn file,folder đích
*
*/
public void copyDirectory(File srcPath, File dstPath,boolean xoatatca)
throws IOException{
JOptionPane overwritePrompt = new JOptionPane();
Object[] options = {"Yes","Yes to all","No"};
if (srcPath.isDirectory()){
if (!dstPath.exists()){
dstPath.mkdir();
}
//tao thu muc nguon trong thu muc dich
String namedir = srcPath.getName();
dstPath = new File (dstPath + "/" + namedir);
if (dstPath.exists() && xoatatca == false){
int n = JOptionPane.showOptionDialog(overwritePrompt,
"Already exists. Overwrite?",
"Overwrite All File?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE,
null,
options,
options[2]);
if(n ==0 )
dstPath.delete();
if(n ==1){
dstPath.delete();
xoatatca = true;
}
if(n==2){
return;
}
}
dstPath.mkdirs();
String files[] = srcPath.list();
//de quy
for(int i = 0; i < files.length; i++){
copyDirectory(new File(srcPath, files[i]),
new File(dstPath, files[i]),xoatatca);
}
}
//neu la file
else{
if(!srcPath.exists()){//ko tồn tại
return;
}
//da co file o thu muc dich
else{ //chua co
if (dstPath.exists() && xoatatca == false){
int n = JOptionPane.showOptionDialog(overwritePrompt,
"Already exists. Overwrite?",
"Overwrite All File?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE,
null,
options,
options[2]);
if(n ==0 )
dstPath.delete();
if(n ==1){
dstPath.delete();
xoatatca = true;
}
if(n==2){
return;
}
}
this.firePropertyChange("DangCopy", "", srcPath.getCanonicalPath());
InputStream in = new FileInputStream(srcPath.getAbsoluteFile());
OutputStream out = new FileOutputStream(dstPath.getAbsoluteFile());
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
public void removeDirectory(File srcPath,boolean xoatatca)
throws IOException{
JOptionPane overwritePrompt = new JOptionPane();
Object[] options = {"Yes","Yes to all","No"};
if(xoatatca==false)
{
int n = JOptionPane.showOptionDialog(overwritePrompt,
"Do you realy want to delete?",
"Delete all Files?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE,
null,
options,
options[2]);
if(n ==1){
xoatatca = true;
}
if(n==2){
xoatatca = true;
return;
}
}
if (srcPath.isDirectory()){
String files[] = srcPath.list();
//de quy
for(int i = 0; i < files.length; i++){
removeDirectory(new File(srcPath, files[i]),xoatatca);
}
this.firePropertyChange("DangRemove", "", srcPath.getCanonicalPath());
srcPath.delete();
}
//neu la file
else{
if(!srcPath.exists()){//ko tồn tại
return;
}
else{
this.firePropertyChange("DangRemove", "", srcPath.getCanonicalPath());
srcPath.delete();
}
}
}
/**
* di chuyển file đến thư vị trí khác
* @param oldFile đường dẫn file nguồn
* @param newFile đường dẫn file địch
* @return
* @throws java.io.FileNotFoundException
* @throws java.io.IOException
*/
public boolean movefile(String oldFile, String newFile) throws FileNotFoundException, IOException{
File f1 = new File(oldFile);
File f2 = new File(newFile);
boolean result = f1.renameTo(f2);
if(result == false)// && JOptionPane.showConfirmDialog(null, "File bị trùng bạn có muốn chép đè lên ko") == 0)
{
copyDirectory(f1,f2,false);
removeDirectory(f1, true);
}
return result;
}
/**
* đổi tên file
* @param oldFile tên file nguồn
* @param newFile tên file đích
* @return
* @throws java.io.FileNotFoundException
* @throws java.io.IOException
*/
public static boolean renamefile(String oldFile, String newFile) throws FileNotFoundException, IOException{
File f1 = new File(oldFile);
File f2 = new File(newFile);
boolean result = f1.renameTo(f2);
if(result == false)
{
JOptionPane.showMessageDialog(null, "File bị trùng tên");
}
return result;
}
/**
* Cắt nhỏ 1 file thành nhiều file
* @param str_DuongDanFileNguon file cần cắt
* @param str_DuongDanThuMucDich thư mục chứa các file sau khi cắt
* @param l_KichThuoc kích thước mỗi file sau khi cắt
* @return
*/
public boolean catFile (String str_DuongDanFileNguon, String str_DuongDanThuMucDich, long l_KichThuoc) throws IOException{
File fileNguon = new File(str_DuongDanFileNguon);
String str_DuongDanChungCuaFileDich = str_DuongDanThuMucDich + "\\" + fileNguon.getName() + ".";
int i_SttFileHienTai = 1001;
long l_KichThuocDaCopy = 0;
int oldValue = (int)(fileNguon.length() / jEnum_CacEnumTrongBai.MB.value());
while (l_KichThuocDaCopy < fileNguon.length()){
int newValue = (int)(l_KichThuocDaCopy / jEnum_CacEnumTrongBai.MB.value());
if (newValue % 5 == 0)
this.firePropertyChange("KichThuocDaCat", oldValue, newValue);
//Tạo file có dạng filenguon.xxx
//do stt hiện tại có 1001 để khi chuyển thành chuổi có thể giữ được những số 0 đầu
//nên cần cắt chuổi từ vị trí 1 - 4
File fileDichHienTai = new File(str_DuongDanChungCuaFileDich +
String.valueOf(i_SttFileHienTai).substring(1, 4));
fileDichHienTai.deleteOnExit();//xóa trước khi tạo file mới
copy1phanfile(str_DuongDanFileNguon, fileDichHienTai.getPath()
, l_KichThuocDaCopy, false, l_KichThuoc);
//Copy phần file vào file đích hiện tại
//Tăng số stt file hiện tại và cập nhật kích thước đã copy
i_SttFileHienTai++;
l_KichThuocDaCopy += l_KichThuoc;
}
return true;
}
/**
* Copy 1 phần của file
* @param srFile file nguồn
* @param dtFile file đích
* @param l_ViTriBatDauCopy bắt đầu từ vị trí này của file
* @param l_KichThuocCanCopy kích thước phần cần copy
* @throws java.io.FileNotFoundException
* @throws java.io.IOException
*/
public static void copy1phanfile(String srFile, String dtFile, long l_ViTriBatDauCopy
, boolean b_NoiThemVao, long l_KichThuocCanCopy) throws FileNotFoundException, IOException{
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
in.skip(l_ViTriBatDauCopy);
//For Append the file.
// OutputStream out = new FileOutputStream(f2,true);
//For Overwrite the file.
OutputStream out = new FileOutputStream(f2, b_NoiThemVao);
byte[] buf = new byte[1024];
int len;
long l_KichThuocDaCopy = 0;
while ((len = in.read(buf)) > 0 && l_KichThuocDaCopy < l_KichThuocCanCopy){
out.write(buf, 0, len);
l_KichThuocDaCopy += len;
}
in.close();
out.close();
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
//// </editor-fold>
public static int ghepFile (String str_FileDauTien, String str_FileDich) throws FileNotFoundException, IOException{
File fileHienTai = new File (str_FileDauTien);
String str_FileHienTai = str_FileDauTien.substring(0, str_FileDauTien.lastIndexOf(".") + 1);
int i_SttFileHienTai = 1001;
//Xóa nếu file hiện tại đã có
new File(str_FileDich).deleteOnExit();
while (fileHienTai.isFile()){
//copy thêm file hiện tại vào file đích
copy1phanfile(fileHienTai.getPath(), str_FileDich, 0, true, fileHienTai.length());
//Tăng số thứ tự file hiện tại
i_SttFileHienTai++;
//Cập nhât file hiện tại
fileHienTai = new File(str_FileHienTai + String.valueOf(i_SttFileHienTai).substring(1, 4));
}
return i_SttFileHienTai - 1000;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dialog_Copy.java
*
* Created on Apr 16, 2009, 7:41:29 PM
*/
package QuanLyFile;
import java.awt.Cursor;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
/**
*
* @author Administrator
*/
public class Dialog_Copy extends javax.swing.JDialog {
BoQuanLyFile boQuanLyFile;
Task task;
/** Creates new form Dialog_Copy */
public Dialog_Copy(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
boQuanLyFile = new BoQuanLyFile();
boQuanLyFile.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("DangCopy")){
jLabel_DangCopy.setText(evt.getNewValue().toString());
}
}
});
}
/**
* @param jTextField_Dich the jTextField_Dich to set
*/
public void setJTextField_Dich(javax.swing.JTextField jTextField_Dich) {
this.jTextField_Dich = jTextField_Dich;
}
/**
* @param jTextField_Nguon the jTextField_Nguon to set
*/
public void setJTextField_Nguon(javax.swing.JTextField jTextField_Nguon) {
this.jTextField_Nguon = jTextField_Nguon;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTextField_Dich = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jTextField_Nguon = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel_DangCopy = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton_Copy = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setName("Form"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getResourceMap(Dialog_Copy.class);
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jTextField_Dich.setText(resourceMap.getString("jTextField_Dich.text")); // NOI18N
jTextField_Dich.setName("jTextField_Dich"); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
jTextField_Nguon.setText(resourceMap.getString("jTextField_Nguon.text")); // NOI18N
jTextField_Nguon.setName("jTextField_Nguon"); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
jLabel_DangCopy.setText(resourceMap.getString("jLabel_DangCopy.text")); // NOI18N
jLabel_DangCopy.setName("jLabel_DangCopy"); // NOI18N
jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
jButton1.setName("jButton1"); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton_Copy.setText(resourceMap.getString("jButton_Copy.text")); // NOI18N
jButton_Copy.setName("jButton_Copy"); // NOI18N
jButton_Copy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_CopyActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton_Copy)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 56, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel_DangCopy, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE))
.addGap(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField_Nguon)
.addComponent(jTextField_Dich, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField_Nguon, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField_Dich, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel_DangCopy))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton_Copy))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
if (JOptionPane.showConfirmDialog(null, "Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
dispose();
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton_CopyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CopyActionPerformed
// TODO add your handling code here:
jButton_Copy.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
task = new Task();
task.addPropertyChangeListener(boQuanLyFile.getPropertyChangeListeners()[0]);
task.execute();
}//GEN-LAST:event_jButton_CopyActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Dialog_Copy dialog = new Dialog_Copy(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton_Copy;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel_DangCopy;
private javax.swing.JTextField jTextField_Dich;
private javax.swing.JTextField jTextField_Nguon;
// End of variables declaration//GEN-END:variables
/**
* @return the jTextField_Dich
*/
public javax.swing.JTextField getJTextField_Dich() {
return jTextField_Dich;
}
/**
* @return the jTextField_Nguon
*/
public javax.swing.JTextField getJTextField_Nguon() {
return jTextField_Nguon;
} // End of variables declaration
class Task extends SwingWorker<Void, Void> {
public void copyFile(){
try {
// TODO add your handling code here:
String str_FileNguon = getJTextField_Nguon().getText();
String str_FileDich = getJTextField_Dich().getText();
boQuanLyFile.copyDirectory(new File(str_FileNguon), new File(str_FileDich), false);
} catch (IOException ex) {
Logger.getLogger(Dialog_CatNho.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Copy file thất bại! Lỗi: " + ex.getMessage());
}
}
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
copyFile();
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
jButton_Copy.setEnabled(true);
setCursor(null); //turn off the wait cursor
//jLabel_DuongDanDangTim.setText("Số file tìm được: " + jTable_TimDuoc.getRowCount());
//Thông báo thành công và xác nhận thoát
jLabel_DangCopy.setText("Đã hoàn thành!");
/*if (JOptionPane.showConfirmDialog(null, "Copy file thành công! Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)*/
dispose();
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* MyComp_OpenSaveFile.java
*
* Created on Apr 15, 2009, 12:05:37 AM
*/
package QuanLyFile;
import com.sun.org.apache.bcel.internal.generic.Select;
import javax.swing.JFileChooser;
import javax.swing.plaf.FileChooserUI;
/**
*
* @author Administrator
*/
public class MyComp_OpenSaveFile extends javax.swing.JPanel {
private Boolean bTimFileLuu = false;
private JFileChooser fileChooser = new JFileChooser();
/** Creates new form MyComp_OpenSaveFile */
public MyComp_OpenSaveFile() {
initComponents();
}
public MyComp_OpenSaveFile(boolean bMoTimFileLuu) {
initComponents();
bTimFileLuu = bMoTimFileLuu;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jComboBox_DuongDanFile = new javax.swing.JComboBox();
jButton_MoDialog = new javax.swing.JButton();
setName("Form"); // NOI18N
jComboBox_DuongDanFile.setEditable(true);
jComboBox_DuongDanFile.setName("jComboBox_DuongDanFile"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getResourceMap(MyComp_OpenSaveFile.class);
jButton_MoDialog.setText(resourceMap.getString("jButton_MoDialog.text")); // NOI18N
jButton_MoDialog.setName("jButton_MoDialog"); // NOI18N
jButton_MoDialog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_MoDialogActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jComboBox_DuongDanFile, 0, 196, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_MoDialog))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox_DuongDanFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_MoDialog))
);
}// </editor-fold>//GEN-END:initComponents
private void jButton_MoDialogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_MoDialogActionPerformed
// TODO add your handling code here:
int iLuaChonCuaNguoiDung;
iLuaChonCuaNguoiDung = getBTimFileLuu() ? getFileChooser().showSaveDialog(null) : getFileChooser().showOpenDialog(null);
if (iLuaChonCuaNguoiDung == JFileChooser.APPROVE_OPTION){
String strDuongDanFile = getFileChooser().getSelectedFile().getAbsolutePath();
getJComboBox_DuongDanFile().setSelectedItem(strDuongDanFile);
if(getJComboBox_DuongDanFile().getSelectedIndex() == -1)
getJComboBox_DuongDanFile().addItem(strDuongDanFile);
}
phatSinhSuKien_DongFileChooser(getFileChooser());
}//GEN-LAST:event_jButton_MoDialogActionPerformed
//Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng)
//http://www.exampledepot.com/egs/java.util/CustEvent.html
// Tạo một listener list
protected javax.swing.event.EventListenerList listenerList =
new javax.swing.event.EventListenerList();
/**
* Phát sinh sử kiện đóng file chooser
* @param evt tham số cho sự kiện
*/
// This private class is used to fire MyEvents
void phatSinhSuKien_DongFileChooser(JFileChooser evt) {
Object[] listeners = listenerList.getListenerList();
// Each listener occupies two elements - the first is the listener class
// and the second is the listener instance
for (int i = 0; i < listeners.length; i += 2) {
if (listeners[i] == EventListener_HoanThanhCongViec.class) {
((EventListener_HoanThanhCongViec) listeners[i + 1]).Event_DongFileChooser_Occurred(evt);
}
}
}
/**
* Đăng ký sự kiện cho classes
* @param listener Sự kiện cần đăng ký
*/
public void themEventListener_HoanThanhCongViec(EventListener_HoanThanhCongViec listener) {
listenerList.add(EventListener_HoanThanhCongViec.class, listener);
}
/**
* Gỡ bỏ sự kiện khỏi classes
* @param listener Sự kiện cần gỡ bỏ
*/
public void boEventListener_HoanThanhCongViec(EventListener_HoanThanhCongViec listener) {
listenerList.remove(EventListener_HoanThanhCongViec.class, listener);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_MoDialog;
private javax.swing.JComboBox jComboBox_DuongDanFile;
// End of variables declaration//GEN-END:variables
/**
* @return the bTimFileLuu
*/
public Boolean getBTimFileLuu() {
return bTimFileLuu;
}
/**
* @param bTimFileLuu the bTimFileLuu to set
*/
public void setBTimFileLuu(Boolean bTimFileLuu) {
this.bTimFileLuu = bTimFileLuu;
}
/**
* @return the jComboBox_DuongDanFile
*/
public javax.swing.JComboBox getJComboBox_DuongDanFile() {
return jComboBox_DuongDanFile;
}
/**
* @param jComboBox_DuongDanFile the jComboBox_DuongDanFile to set
*/
public void setJComboBox_DuongDanFile(javax.swing.JComboBox jComboBox_DuongDanFile) {
this.jComboBox_DuongDanFile = jComboBox_DuongDanFile;
}
/**
* @return the fileChooser
*/
public JFileChooser getFileChooser() {
return fileChooser;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package QuanLyFile;
import java.util.EventObject;
/**
* Sự kiện khi tạo mới hoặc xóa một file
* phát đi để bạn hiện thị file có thể cập nhật kiệp thời
* @author Administrator
*/
public class Event_Tao_XoaMotFile extends EventObject {
public Event_Tao_XoaMotFile(Object source) {
super(source);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dialog_CatNho.java
*
* Created on Apr 10, 2009, 6:38:44 PM
*/
package QuanLyFile;
import doan_totalcommander_002.jEnum_CacEnumTrongBai;
import java.awt.Cursor;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
/**
* hiện thị dialog cắt nhỏ file
* @author Administrator
*/
public class Dialog_CatNho extends javax.swing.JDialog implements ActionListener,
PropertyChangeListener{
BoQuanLyFile boQuanLyFile = new BoQuanLyFile();
Task task = new Task();
/** Creates new form Dialog_CatNho */
public Dialog_CatNho(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
myComp_OpenSaveFile_FileNguon.setBTimFileLuu(false);
boQuanLyFile.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if ("KichThuocDaCat" == evt.getPropertyName()) {
int oldValue = Integer.parseInt(evt.getOldValue().toString());
int newValue = Integer.parseInt(evt.getNewValue().toString());
int i_PhanTramHoanThanh = newValue * 100 / oldValue;
jProgressBar_Progress.setValue(i_PhanTramHoanThanh);
jLabel_PhanTramHoanThanh.setText(String.valueOf(i_PhanTramHoanThanh) + "%");
}
}
});
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jTextField_ThuMucDich = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
myComp_OpenSaveFile_FileNguon = new QuanLyFile.MyComp_OpenSaveFile();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jComboBox_KichThuocFile = new javax.swing.JComboBox();
jButton_Cat = new javax.swing.JButton();
jButton_Thoát = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jProgressBar_Progress = new javax.swing.JProgressBar();
jLabel_PhanTramHoanThanh = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getResourceMap(Dialog_CatNho.class);
setTitle(resourceMap.getString("Form.title")); // NOI18N
setName("Form"); // NOI18N
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
jPanel1.setName("jPanel1"); // NOI18N
jTextField_ThuMucDich.setText(resourceMap.getString("jTextField_ThuMucDich.text")); // NOI18N
jTextField_ThuMucDich.setName("jTextField_ThuMucDich"); // NOI18N
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
myComp_OpenSaveFile_FileNguon.setName("myComp_OpenSaveFile_FileNguon"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(myComp_OpenSaveFile_FileNguon, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
.addComponent(jTextField_ThuMucDich, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(myComp_OpenSaveFile_FileNguon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_ThuMucDich, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2.setName("jPanel2"); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
jComboBox_KichThuocFile.setEditable(true);
jComboBox_KichThuocFile.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "100", "650", "700", " " }));
jComboBox_KichThuocFile.setName("jComboBox_KichThuocFile"); // NOI18N
jButton_Cat.setText(resourceMap.getString("jButton_Cat.text")); // NOI18N
jButton_Cat.setName("jButton_Cat"); // NOI18N
jButton_Cat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_CatActionPerformed(evt);
}
});
jButton_Thoát.setText(resourceMap.getString("jButton_Thoát.text")); // NOI18N
jButton_Thoát.setName("jButton_Thoát"); // NOI18N
jButton_Thoát.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ThoátActionPerformed(evt);
}
});
jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
jLabel4.setName("jLabel4"); // NOI18N
jProgressBar_Progress.setName("jProgressBar_Progress"); // NOI18N
jLabel_PhanTramHoanThanh.setText(resourceMap.getString("jLabel_PhanTramHoanThanh.text")); // NOI18N
jLabel_PhanTramHoanThanh.setName("jLabel_PhanTramHoanThanh"); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox_KichThuocFile, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Cat, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Thoát))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jProgressBar_Progress, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jLabel_PhanTramHoanThanh)))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jComboBox_KichThuocFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_Thoát)
.addComponent(jButton_Cat)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel_PhanTramHoanThanh)
.addComponent(jProgressBar_Progress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_CatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CatActionPerformed
if (JOptionPane.showConfirmDialog(null, "Bạn muốn cắc file? Các file đích (nếu có) sẽ bị xóa!!!"
, "Xác nhận ghép", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION)
return;
actionPerformed(evt);
}//GEN-LAST:event_jButton_CatActionPerformed
private void jButton_ThoátActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ThoátActionPerformed
// TODO add your handling code here:
if (JOptionPane.showConfirmDialog(null, "Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
dispose();
}//GEN-LAST:event_jButton_ThoátActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Dialog_CatNho dialog = new Dialog_CatNho(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_Cat;
private javax.swing.JButton jButton_Thoát;
private javax.swing.JComboBox jComboBox_KichThuocFile;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel_PhanTramHoanThanh;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JProgressBar jProgressBar_Progress;
private javax.swing.JTextField jTextField_ThuMucDich;
private QuanLyFile.MyComp_OpenSaveFile myComp_OpenSaveFile_FileNguon;
// End of variables declaration//GEN-END:variables
/**
* @param jTextField_ThuMucDich the jTextField_ThuMucDich to set
*/
public void setTextOfJTextField_ThuMucDich(String str_DuongDanThuMucDich) {
this.jTextField_ThuMucDich.setText(str_DuongDanThuMucDich);
}
/**
* @return the myComp_OpenSaveFile_FileNguon
*/
public QuanLyFile.MyComp_OpenSaveFile getMyComp_OpenSaveFile_FileNguon() {
return myComp_OpenSaveFile_FileNguon;
}
public void actionPerformed(ActionEvent e) {
jButton_Cat.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
public void propertyChange(PropertyChangeEvent evt) {
}
class Task extends SwingWorker<Void, Void> {
public void catFile(){
try {
// TODO add your handling code here:
long i_KichThuoc = Integer.valueOf(jComboBox_KichThuocFile.getSelectedItem().toString()) *
jEnum_CacEnumTrongBai.MB.value();
String str_FileNguon = getMyComp_OpenSaveFile_FileNguon().getJComboBox_DuongDanFile().getSelectedItem().toString();
boQuanLyFile.catFile(str_FileNguon,jTextField_ThuMucDich.getText(), i_KichThuoc);
} catch (IOException ex) {
Logger.getLogger(Dialog_CatNho.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Cắt file thất bại! Lỗi: " + ex.getMessage());
}
}
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
catFile();
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
jButton_Cat.setEnabled(true);
setCursor(null); //turn off the wait cursor
//jLabel_DuongDanDangTim.setText("Số file tìm được: " + jTable_TimDuoc.getRowCount());
jProgressBar_Progress.setValue(100);
jLabel_PhanTramHoanThanh.setText(100 + "%");
//Thông báo thành công và xác nhận thoát
if (JOptionPane.showConfirmDialog(null, "Cắt file thành công! Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
dispose();
}
}
//Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng)
//http://www.exampledepot.com/egs/java.util/CustEvent.html
// Tạo một listener list
protected javax.swing.event.EventListenerList listenerList =
new javax.swing.event.EventListenerList();
/**
* Phát sinh sử kiện đóng file chooser
* @param evt tham số cho sự kiện
*/
// This private class is used to fire MyEvents
void phatSinhSuKien_DongFileChooser(JFileChooser evt) {
Object[] listeners = listenerList.getListenerList();
// Each listener occupies two elements - the first is the listener class
// and the second is the listener instance
for (int i = 0; i < listeners.length; i += 2) {
if (listeners[i] == EventListener_HoanThanhCongViec.class) {
((EventListener_HoanThanhCongViec) listeners[i + 1]).Event_DongFileChooser_Occurred(evt);
}
}
}
/**
* Đăng ký sự kiện cho classes
* @param listener Sự kiện cần đăng ký
*/
public void themEventListener_HoanThanhCongViec(EventListener_HoanThanhCongViec listener) {
listenerList.add(EventListener_HoanThanhCongViec.class, listener);
}
/**
* Gỡ bỏ sự kiện khỏi classes
* @param listener Sự kiện cần gỡ bỏ
*/
public void boEventListener_HoanThanhCongViec(EventListener_HoanThanhCongViec listener) {
listenerList.remove(EventListener_HoanThanhCongViec.class, listener);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package QuanLyFile;
import java.util.EventObject;
/**
*
* @author Administrator
*/
public class Event_DongFileChooser extends EventObject {
public Event_DongFileChooser(Object source) {
super(source);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dialog_TimFile.java
*
* Created on Apr 13, 2009, 3:48:12 PM
*/
package QuanLyFile;
import DuyetFile.BangDuyetFile;
import DuyetFile.EventListener_ClickChuotVaoBangDuyetFile;
import doan_totalcommander_002.jEnum_CacEnumTrongBai;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;
/**
* tham khảo http://java.sun.com/docs/books/tutorial/uiswing/examples/components/ProgressBarDemoProject/src/components/ProgressBarDemo.java
* @author Administrator
*/
public class Dialog_TimFile extends javax.swing.JFrame implements ActionListener,
PropertyChangeListener{
Task task = new Task();
private BangDuyetFile bangDuyetFile;
/** Creates new form Dialog_TimFile */
public Dialog_TimFile(java.awt.Frame parent, boolean modal) {
super();
initComponents();
jTable_TimDuoc.setAutoCreateRowSorter(true);
//this.setAlwaysOnTop(true);
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
jTextField_NgayCuoi.setText(dateFormat.format(new Date()).toString());
for (File phanVung : File.listRoots()){
jComboBox_ViTriDuyet.addItem(phanVung.getPath());
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel3 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
jTextField_TenFile = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jTextField_NgayDau = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jTextField_KichThuocDau = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jButton_Tim = new javax.swing.JButton();
jComboBox_LoaiKichThuocKetThuc = new javax.swing.JComboBox();
jComboBox_LoaiKichThuocBatDau = new javax.swing.JComboBox();
jTextField_KichThuocCuoi = new javax.swing.JTextField();
jCheckBox_TrungKhopTatCa = new javax.swing.JCheckBox();
jSeparator1 = new javax.swing.JSeparator();
jTextField_NgayCuoi = new javax.swing.JTextField();
jCheckBox_NgayThayDoiCuoi = new javax.swing.JCheckBox();
jCheckBox_KichThuoc = new javax.swing.JCheckBox();
jLabel7 = new javax.swing.JLabel();
jComboBox_ViTriDuyet = new javax.swing.JComboBox();
jButton_Ngung = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabel_DuongDanDangTim = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable_TimDuoc = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel3.setLayout(new java.awt.BorderLayout());
jPanel1.setPreferredSize(new java.awt.Dimension(806, 120));
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Các tiêu chí tìm kiếm"));
jLabel6.setText("Tên file:");
jLabel2.setText("Ngày thay đổi cuối từ:");
jTextField_NgayDau.setText("1/1/1970");
jLabel4.setText("đến:");
jLabel1.setText("Kích thước từ:");
jTextField_KichThuocDau.setText("0");
jLabel5.setText("đến:");
jButton_Tim.setText("Tìm");
jButton_Tim.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_TimActionPerformed(evt);
}
});
jComboBox_LoaiKichThuocKetThuc.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Byte", "KB", "MB", "GB" }));
jComboBox_LoaiKichThuocBatDau.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Byte", "KB", "MB", "GB" }));
jTextField_KichThuocCuoi.setText("0");
jCheckBox_TrungKhopTatCa.setSelected(true);
jCheckBox_TrungKhopTatCa.setText("Trùng khớp tất cả");
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jCheckBox_NgayThayDoiCuoi.setSelected(true);
jCheckBox_NgayThayDoiCuoi.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox_NgayThayDoiCuoiActionPerformed(evt);
}
});
jCheckBox_KichThuoc.setSelected(true);
jCheckBox_KichThuoc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox_KichThuocActionPerformed(evt);
}
});
jLabel7.setText("Trong:");
jComboBox_ViTriDuyet.setEditable(true);
jButton_Ngung.setText("Ngưng");
jButton_Ngung.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_NgungActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jCheckBox_TrungKhopTatCa)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Tim, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_Ngung))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBox_ViTriDuyet, 0, 199, Short.MAX_VALUE)
.addComponent(jTextField_TenFile, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jCheckBox_NgayThayDoiCuoi)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2))
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jCheckBox_KichThuoc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addComponent(jTextField_NgayDau, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4))
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jTextField_KichThuocDau, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox_LoaiKichThuocBatDau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jTextField_KichThuocCuoi, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox_LoaiKichThuocKetThuc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jTextField_NgayCuoi, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField_TenFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox_ViTriDuyet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jTextField_NgayCuoi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jCheckBox_NgayThayDoiCuoi)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField_NgayDau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jCheckBox_TrungKhopTatCa)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField_KichThuocCuoi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox_LoaiKichThuocKetThuc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(jTextField_KichThuocDau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox_LoaiKichThuocBatDau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jCheckBox_KichThuoc))
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_Tim)
.addComponent(jButton_Ngung))))
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3.add(jPanel1, java.awt.BorderLayout.PAGE_START);
jPanel2.setPreferredSize(new java.awt.Dimension(400, 30));
jLabel_DuongDanDangTim.setText("Đang tìm trong:");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel_DuongDanDangTim)
.addContainerGap(623, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel_DuongDanDangTim)
.addContainerGap())
);
jPanel3.add(jPanel2, java.awt.BorderLayout.PAGE_END);
jTable_TimDuoc.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Tên", "Loại", "Đường dẫn", "Size (bytes)"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Long.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable_TimDuoc.setColumnSelectionAllowed(true);
jTable_TimDuoc.getTableHeader().setReorderingAllowed(false);
jTable_TimDuoc.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable_TimDuocMouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable_TimDuoc);
jTable_TimDuoc.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
jTable_TimDuoc.getColumnModel().getColumn(1).setMinWidth(64);
jTable_TimDuoc.getColumnModel().getColumn(1).setPreferredWidth(64);
jTable_TimDuoc.getColumnModel().getColumn(1).setMaxWidth(64);
jTable_TimDuoc.getColumnModel().getColumn(3).setMinWidth(96);
jTable_TimDuoc.getColumnModel().getColumn(3).setPreferredWidth(96);
jTable_TimDuoc.getColumnModel().getColumn(3).setMaxWidth(96);
jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel3, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_TimActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_TimActionPerformed
jButton_Tim.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}//GEN-LAST:event_jButton_TimActionPerformed
private void jCheckBox_NgayThayDoiCuoiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_NgayThayDoiCuoiActionPerformed
// TODO add your handling code here:
jTextField_NgayDau.setEnabled(jCheckBox_NgayThayDoiCuoi.isSelected());
jTextField_NgayCuoi.setEnabled(jCheckBox_NgayThayDoiCuoi.isSelected());
}//GEN-LAST:event_jCheckBox_NgayThayDoiCuoiActionPerformed
private void jCheckBox_KichThuocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_KichThuocActionPerformed
// TODO add your handling code here:
jTextField_KichThuocDau.setEnabled(jCheckBox_KichThuoc.isSelected());
jTextField_KichThuocCuoi.setEnabled(jCheckBox_KichThuoc.isSelected());
}//GEN-LAST:event_jCheckBox_KichThuocActionPerformed
private void jButton_NgungActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_NgungActionPerformed
// TODO add your handling code here:
task.cancel(true);
}//GEN-LAST:event_jButton_NgungActionPerformed
private void jTable_TimDuocMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable_TimDuocMouseClicked
try {
// TODO add your handling code here:
if (evt.getButton() != 1 || evt.getClickCount() == 1) {
//Nếu không click chuột trái hoặc mới click 1 lần
return;
}
int iDongDuocChon = jTable_TimDuoc.getSelectedRow();
//Nếu loại file là folder thì phát sinh sự kiện để bảng duyệt file bắt với tham số là đường dẫn
if (jTable_TimDuoc.getValueAt(iDongDuocChon, 1).equals("Folder")) {
phatSinhSuKien_ClickChuotVaoBangDuyetFile(jTable_TimDuoc.getValueAt(iDongDuocChon, 0).toString(), 2);
} else {//Nếu là file thì thử mở với chương trình mặc định
Desktop.getDesktop().open(new File(jTable_TimDuoc.getValueAt(iDongDuocChon, 2) + "\\" +
jTable_TimDuoc.getValueAt(iDongDuocChon, 0) + jTable_TimDuoc.getValueAt(iDongDuocChon, 1)));
//Tổng hợp cột 2 (đường dẫn), 0 (tên) và 1 (loại) lại sẽ được đường dẫn file hoàn chỉnh
}
} catch (IOException ex) {
Logger.getLogger(Dialog_TimFile.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jTable_TimDuocMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Dialog_TimFile dialog = new Dialog_TimFile(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_Ngung;
private javax.swing.JButton jButton_Tim;
private javax.swing.JCheckBox jCheckBox_KichThuoc;
private javax.swing.JCheckBox jCheckBox_NgayThayDoiCuoi;
private javax.swing.JCheckBox jCheckBox_TrungKhopTatCa;
private javax.swing.JComboBox jComboBox_LoaiKichThuocBatDau;
private javax.swing.JComboBox jComboBox_LoaiKichThuocKetThuc;
private javax.swing.JComboBox jComboBox_ViTriDuyet;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel_DuongDanDangTim;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTable jTable_TimDuoc;
private javax.swing.JTextField jTextField_KichThuocCuoi;
private javax.swing.JTextField jTextField_KichThuocDau;
private javax.swing.JTextField jTextField_NgayCuoi;
private javax.swing.JTextField jTextField_NgayDau;
private javax.swing.JTextField jTextField_TenFile;
// End of variables declaration//GEN-END:variables
public void actionPerformed(ActionEvent e) {
// TODO add your handling code here:
jButton_Tim.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
public void propertyChange(PropertyChangeEvent evt) {
//int i = 0;
if ("STARTED" == evt.getNewValue().toString()) {
//int progress = (Integer) evt.getNewValue();
//Object[] dongDuLieu = {evt., strLoai, strDuongDan, lSize};
DefaultTableModel model = (DefaultTableModel) jTable_TimDuoc.getModel();
model.setRowCount(0);
jTable_TimDuoc.setModel(model);
//taskOutput.append(task.f);
}
if ("File" == evt.getPropertyName()) {
File file = (File) evt.getNewValue();
String strTen = file.getName();
String strLoai = "";
String strDuongDan = file.getAbsolutePath();
long lSize = file.length();
if (strTen.contains(".")){
strLoai = strTen.substring(strTen.lastIndexOf("."), strTen.length());
strTen = strTen.substring(0, strTen.lastIndexOf("."));
}
Object[] dongDuLieu = {strTen, strLoai, strDuongDan, lSize};
DefaultTableModel model = (DefaultTableModel) jTable_TimDuoc.getModel();
model.addRow(dongDuLieu);
jTable_TimDuoc.setModel(model);
//jTable_TimDuoc.getModel()
}
if ("Folder" == evt.getPropertyName()) {
jLabel_DuongDanDangTim.setText("Đang tìm trong: " + evt.getNewValue().toString() + "\n");
String regex = evt.getOldValue().toString().replace(".", "\\.");
regex = regex.replace("*", ".*");
regex = regex.replace("?", ".?");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(new File(evt.getNewValue().toString()).getName());
if (!matcher.find())
//if(!pathname.getName().contains(tenFile))
return;
Object[] dongDuLieu = {evt.getNewValue(), "Folder", "", (long)0};
DefaultTableModel model = (DefaultTableModel) jTable_TimDuoc.getModel();
model.addRow(dongDuLieu);
jTable_TimDuoc.setModel(model);
}
}
/**
* @param bangDuyetFile the bangDuyetFile to set
*/
public void setBangDuyetFile(BangDuyetFile bangDuyetFile) {
this.bangDuyetFile = bangDuyetFile;
}
//Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng)
//http://www.exampledepot.com/egs/java.util/CustEvent.html
// Tạo một listener list
protected javax.swing.event.EventListenerList listenerList =
new javax.swing.event.EventListenerList();
/**
* Phát sinh sử kiện click chuột vào bảng
* @param evt tham số cho sự kiện click chuột vào bảng (ở đây là tên của file đang được chọn)
* @param iSoLanClick số lần click chuột
*/
// This private class is used to fire MyEvents
void phatSinhSuKien_ClickChuotVaoBangDuyetFile(String evt, int iSoLanClick) {
Object[] listeners = listenerList.getListenerList();
// Each listener occupies two elements - the first is the listener class
// and the second is the listener instance
for (int i = 0; i < listeners.length; i += 2) {
if (listeners[i] == EventListener_ClickChuotVaoBangDuyetFile.class) {
((EventListener_ClickChuotVaoBangDuyetFile) listeners[i + 1]).Event_ClickChuotVaoBangDuyetFile_Occurred(evt, iSoLanClick);
}
}
}
/**
* Đăng ký sự kiện cho classes
* @param listener Sự kiện cần đăng ký
*/
public void themEventListener_ClickChuotVaoBangDuyetFile(EventListener_ClickChuotVaoBangDuyetFile listener) {
listenerList.add(EventListener_ClickChuotVaoBangDuyetFile.class, listener);
}
/**
* Gỡ bỏ sự kiện khỏi classes
* @param listener Sự kiện cần gỡ bỏ
*/
public void boEventListener_ClickChuotVaoBangDuyetFile(EventListener_ClickChuotVaoBangDuyetFile listener) {
listenerList.remove(EventListener_ClickChuotVaoBangDuyetFile.class, listener);
}
class Task extends SwingWorker<Void, Void> {
public void DuyetFile(String duongDan, BoLocFile filter){
File files = new File(duongDan);
firePropertyChange("Folder", filter.getTenFile(), files.getAbsolutePath());
for (File file : files.listFiles(filter)){
try {
Thread.sleep(1L);
} catch (InterruptedException ignore) {
Thread.currentThread().stop();
}
if (file.isDirectory()){
DuyetFile(file.getAbsolutePath(), filter);
}
else{
firePropertyChange("File", "", file);
}
}
}
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
long l_NgayBatDau, l_NgayKetThuc, l_KichThuocBatDau, l_KichThuocKetThuc;
//<editor-fold defaultstate="collapsed" desc="Bắt lỗi input và 4 thuộc tính đầu">
if (jCheckBox_NgayThayDoiCuoi.isSelected()){
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
try{l_NgayBatDau = dateFormat.parse(jTextField_NgayDau.getText()).getTime();}
catch(Exception ex){
l_NgayBatDau = 0;
JOptionPane.showMessageDialog(null, "Thông tin ngày bắt đầu không hợp lệ sẽ bỏ qua!");
}
try{l_NgayKetThuc = dateFormat.parse(jTextField_NgayCuoi.getText()).getTime();}
catch(Exception ex){
l_NgayKetThuc = 0;
JOptionPane.showMessageDialog(null, "Thông tin ngày kết thúc không hợp lệ sẽ bỏ qua!");
}
}
else{
l_NgayBatDau = l_NgayKetThuc = 0;
}
if (jCheckBox_KichThuoc.isSelected()){
try{l_KichThuocBatDau = Integer.parseInt(jTextField_KichThuocDau.getText());}
catch(Exception ex){
l_KichThuocBatDau = 0;
JOptionPane.showMessageDialog(null, "Thông tin kích thước bắt đầu không hợp lệ bỏ qua");
}
try{l_KichThuocKetThuc = Integer.parseInt(jTextField_KichThuocCuoi.getText());}
catch(Exception ex){
l_KichThuocKetThuc = 0;
JOptionPane.showMessageDialog(null, "Thông tin kích thước không hợp lệ sẽ bỏ qua!");
}
}
else{
l_KichThuocBatDau = l_KichThuocKetThuc = 0;
}
//</editor-fold>
String loaiKichThuoc = jComboBox_LoaiKichThuocBatDau.getSelectedItem().toString();
if (loaiKichThuoc.equalsIgnoreCase("KB"))
l_KichThuocBatDau *= jEnum_CacEnumTrongBai.KB.value();
else if(loaiKichThuoc.equalsIgnoreCase("MB"))
l_KichThuocBatDau *= jEnum_CacEnumTrongBai.MB.value();
else if(loaiKichThuoc.equalsIgnoreCase("GB"))
l_KichThuocBatDau *= jEnum_CacEnumTrongBai.GB.value();
loaiKichThuoc = jComboBox_LoaiKichThuocKetThuc.getSelectedItem().toString();
if (loaiKichThuoc.equalsIgnoreCase("KB"))
l_KichThuocKetThuc *= jEnum_CacEnumTrongBai.KB.value();
else if(loaiKichThuoc.equalsIgnoreCase("MB"))
l_KichThuocKetThuc *= jEnum_CacEnumTrongBai.MB.value();
else if(loaiKichThuoc.equalsIgnoreCase("GB"))
l_KichThuocKetThuc *= jEnum_CacEnumTrongBai.GB.value();
BoLocFile boLocFile = new BoLocFile(l_NgayBatDau, l_NgayKetThuc,
l_KichThuocBatDau, l_KichThuocKetThuc,
jTextField_TenFile.getText(), jCheckBox_TrungKhopTatCa.isSelected());
DuyetFile(jComboBox_ViTriDuyet.getSelectedItem().toString(), boLocFile);
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
jButton_Tim.setEnabled(true);
setCursor(null); //turn off the wait cursor
jLabel_DuongDanDangTim.setText("Số file tìm được: " + jTable_TimDuoc.getRowCount());
setProgress(100);
}
}
}
class BoLocFile implements FileFilter{
long ngayBatDau;
long ngayKetThuc;
long kichThuocBatDau;
long kichThuocKetThuc;
private String tenFile;
boolean khopTatCa;
public boolean accept(File pathname) {
//Nếu ngày thay đổi cuối không thuộc khoảng phù hợp và phải trùng khớp tất cả
//Nếu các giá trị kết thúc bằng 0 thì bỏ qua
//Trả về false
if (pathname.isDirectory())
return true;
if (pathname.lastModified() < ngayBatDau
|| (pathname.lastModified() > ngayKetThuc && 0 != ngayKetThuc)&& khopTatCa)
return false;
//Tương tự cho kích thước
if (pathname.length() < kichThuocBatDau
|| (pathname.length() > kichThuocKetThuc && 0 != kichThuocKetThuc) && khopTatCa)
return false;
//Nếu đã đạt được cả hai
String regex = getTenFile().replace(".", "\\.");
regex = regex.replace("*", ".*");
regex = regex.replace("?", ".?");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(pathname.getName());
if (!matcher.find())
//if(!pathname.getName().contains(tenFile))
return false;
return true;
}
public BoLocFile (long l_NgayBatDau, long l_NgayKetThuc,
long l_KichThuocBatDau, long l_KichThuocKetThuc, String str_TenFile, boolean b_KhopTatCa){
ngayBatDau = l_NgayBatDau;
ngayKetThuc = l_NgayKetThuc;
kichThuocBatDau = l_KichThuocBatDau;
kichThuocKetThuc = l_KichThuocKetThuc;
tenFile = str_TenFile;
khopTatCa = b_KhopTatCa;
}
/**
* @return the tenFile
*/
public String getTenFile() {
return tenFile;
}
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dialog_Xem_ChinhSuaFile.java
*
* Created on Apr 9, 2009, 10:14:10 PM
*/
package QuanLyFile;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
/**
* hiện thị dialog cho phép xem dữ liệu bên trong file
* @author Administrator
*/
public class Dialog_Xem_ChinhSuaFile extends javax.swing.JFrame {
/** Creates new form Dialog_Xem_ChinhSuaFile */
public Dialog_Xem_ChinhSuaFile() {
initComponents();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane_HienThiFile = new javax.swing.JScrollPane();
jTextPane_HienThiFile = new javax.swing.JTextPane();
jButton_Luu = new javax.swing.JButton();
jButton_Thoat = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem_Luu = new javax.swing.JMenuItem();
jMenuItem_Thoat = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setName("Form"); // NOI18N
jScrollPane_HienThiFile.setName("jScrollPane_HienThiFile"); // NOI18N
jTextPane_HienThiFile.setName("jTextPane_HienThiFile"); // NOI18N
jTextPane_HienThiFile.setNextFocusableComponent(jButton_Luu);
jScrollPane_HienThiFile.setViewportView(jTextPane_HienThiFile);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getResourceMap(Dialog_Xem_ChinhSuaFile.class);
jButton_Luu.setText(resourceMap.getString("jButton_Luu.text")); // NOI18N
jButton_Luu.setName("jButton_Luu"); // NOI18N
jButton_Luu.setNextFocusableComponent(jButton_Thoat);
jButton_Luu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_LuuActionPerformed(evt);
}
});
jButton_Thoat.setText(resourceMap.getString("jButton_Thoat.text")); // NOI18N
jButton_Thoat.setName("jButton_Thoat"); // NOI18N
jButton_Thoat.setNextFocusableComponent(jTextPane_HienThiFile);
jButton_Thoat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ThoatActionPerformed(evt);
}
});
jMenuBar1.setName("jMenuBar1"); // NOI18N
jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
jMenu1.setName("jMenu1"); // NOI18N
jMenuItem_Luu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_Luu.setText(resourceMap.getString("jMenuItem_Luu.text")); // NOI18N
jMenuItem_Luu.setName("jMenuItem_Luu"); // NOI18N
jMenuItem_Luu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_LuuActionPerformed(evt);
}
});
jMenu1.add(jMenuItem_Luu);
jMenuItem_Thoat.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
jMenuItem_Thoat.setText(resourceMap.getString("jMenuItem_Thoat.text")); // NOI18N
jMenuItem_Thoat.setName("jMenuItem_Thoat"); // NOI18N
jMenuItem_Thoat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem_ThoatActionPerformed(evt);
}
});
jMenu1.add(jMenuItem_Thoat);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(475, Short.MAX_VALUE)
.addComponent(jButton_Luu, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton_Thoat)
.addContainerGap())
.addComponent(jScrollPane_HienThiFile, javax.swing.GroupLayout.DEFAULT_SIZE, 624, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane_HienThiFile, javax.swing.GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_Luu)
.addComponent(jButton_Thoat))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_LuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_LuuActionPerformed
// TODO add your handling code here
//Xác nhận lưu
if (JOptionPane.showConfirmDialog(null, "Bạn muốn lưu thay đổi?"
, "Xác nhận lưu", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
try {
BoQuanLyFile.ghiFile(getTitle(), jTextPane_HienThiFile.getText());
JOptionPane.showMessageDialog(null, "Lưu file thành công");
} catch (IOException ex) {
Logger.getLogger(Dialog_Xem_ChinhSuaFile.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Không thể ghi file " + getTitle());
}
}//GEN-LAST:event_jButton_LuuActionPerformed
private void jButton_ThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ThoatActionPerformed
// TODO add your handling code here:
//Xác nhận thoát
if (JOptionPane.showConfirmDialog(null, "Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
dispose();
}//GEN-LAST:event_jButton_ThoatActionPerformed
private void jMenuItem_ThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_ThoatActionPerformed
// TODO add your handling code here:
jButton_ThoatActionPerformed(evt);
}//GEN-LAST:event_jMenuItem_ThoatActionPerformed
private void jMenuItem_LuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_LuuActionPerformed
// TODO add your handling code here:
jButton_LuuActionPerformed(evt);
}//GEN-LAST:event_jMenuItem_LuuActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Dialog_Xem_ChinhSuaFile().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_Luu;
private javax.swing.JButton jButton_Thoat;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem_Luu;
private javax.swing.JMenuItem jMenuItem_Thoat;
private javax.swing.JScrollPane jScrollPane_HienThiFile;
private javax.swing.JTextPane jTextPane_HienThiFile;
// End of variables declaration//GEN-END:variables
public JScrollPane getjScrollPane_HienThiFile(){
return getJScrollPane_HienThiFile();
}
public void setjScrollPane_HienThiFile(JScrollPane jScrollPane){
setJScrollPane_HienThiFile(jScrollPane);
}
/**
* @return the jButton_Huy
*/
public javax.swing.JButton getJButton_Huy() {
return getJButton_Thoat();
}
/**
* @param jButton_Huy the jButton_Huy to set
*/
public void setJButton_Huy(javax.swing.JButton jButton_Huy) {
this.setJButton_Thoat(jButton_Huy);
}
/**
* @return the jButton_Luu
*/
public javax.swing.JButton getJButton_Luu() {
return jButton_Luu;
}
/**
* @param jButton_Luu the jButton_Luu to set
*/
public void setJButton_Luu(javax.swing.JButton jButton_Luu) {
this.jButton_Luu = jButton_Luu;
}
/**
* @return the jScrollPane_HienThiFile
*/
public javax.swing.JScrollPane getJScrollPane_HienThiFile() {
return jScrollPane_HienThiFile;
}
/**
* @param jScrollPane_HienThiFile the jScrollPane_HienThiFile to set
*/
public void setJScrollPane_HienThiFile(javax.swing.JScrollPane jScrollPane_HienThiFile) {
this.jScrollPane_HienThiFile = jScrollPane_HienThiFile;
}
/**
* @return the jButton_Thoat
*/
public javax.swing.JButton getJButton_Thoat() {
return jButton_Thoat;
}
/**
* @param jButton_Thoat the jButton_Thoat to set
*/
public void setJButton_Thoat(javax.swing.JButton jButton_Thoat) {
this.jButton_Thoat = jButton_Thoat;
}
/**
* @return the jTextPane_HienThiFile
*/
public javax.swing.JTextPane getJTextPane_HienThiFile() {
return jTextPane_HienThiFile;
}
/**
* @param jTextPane_HienThiFile the jTextPane_HienThiFile to set
*/
public void setJTextPane_HienThiFile(javax.swing.JTextPane jTextPane_HienThiFile) {
this.jTextPane_HienThiFile = jTextPane_HienThiFile;
}
}
| Java |
package QuanLyFile;
import java.awt.Point;
import java.util.EventListener;
import javax.swing.JFileChooser;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public interface EventListener_HoanThanhCongViec extends EventListener {
public void Event_DongFileChooser_Occurred(JFileChooser jFileChooser);
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dialog_Copy.java
*
* Created on Apr 16, 2009, 7:41:29 PM
*/
package QuanLyFile;
import java.awt.Cursor;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
/**
*
* @author Administrator
*/
public class Dialog_Move extends javax.swing.JDialog {
BoQuanLyFile boQuanLyFile;
Task task;
/** Creates new form Dialog_Copy */
public Dialog_Move(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
jButton_Thoat.setText("Thoát");
boQuanLyFile = new BoQuanLyFile();
boQuanLyFile.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("DangCopy")){
jLabel_DangMove.setText(evt.getNewValue().toString());
}
}
});
}
/**
* @param jTextField_Dich the jTextField_Dich to set
*/
public void setJTextField_Dich(javax.swing.JTextField jTextField_Dich) {
this.jTextField_Dich = jTextField_Dich;
}
/**
* @param jTextField_Nguon the jTextField_Nguon to set
*/
public void setJTextField_Nguon(javax.swing.JTextField jTextField_Nguon) {
this.jTextField_Nguon = jTextField_Nguon;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton_Move = new javax.swing.JButton();
jButton_Thoat = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jTextField_Nguon = new javax.swing.JTextField();
jTextField_Dich = new javax.swing.JTextField();
jLabel_DangMove = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setName("Form"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getResourceMap(Dialog_Move.class);
jButton_Move.setText(resourceMap.getString("jButton_Move.text")); // NOI18N
jButton_Move.setName("jButton_Move"); // NOI18N
jButton_Move.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_MoveActionPerformed(evt);
}
});
jButton_Thoat.setText(resourceMap.getString("jButton_Thoat.text")); // NOI18N
jButton_Thoat.setName("jButton_Thoat"); // NOI18N
jButton_Thoat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ThoatActionPerformed(evt);
}
});
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jTextField_Nguon.setName("jTextField_Nguon"); // NOI18N
jTextField_Dich.setName("jTextField_Dich"); // NOI18N
jLabel_DangMove.setText(resourceMap.getString("jLabel_DangMove.text")); // NOI18N
jLabel_DangMove.setName("jLabel_DangMove"); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel_DangMove))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton_Move)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_Thoat))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE))
.addGap(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField_Nguon)
.addComponent(jTextField_Dich, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField_Nguon, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField_Dich, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_DangMove))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_Thoat)
.addComponent(jButton_Move))
.addContainerGap(11, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_MoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_MoveActionPerformed
// TODO add your handling code here:
jButton_Move.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
task = new Task();
task.addPropertyChangeListener(boQuanLyFile.getPropertyChangeListeners()[0]);
task.execute();
}//GEN-LAST:event_jButton_MoveActionPerformed
private void jButton_ThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ThoatActionPerformed
// TODO add your handling code here:
if (JOptionPane.showConfirmDialog(null, "Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
dispose();
}//GEN-LAST:event_jButton_ThoatActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Dialog_Move dialog = new Dialog_Move(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_Move;
private javax.swing.JButton jButton_Thoat;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel_DangMove;
private javax.swing.JTextField jTextField_Dich;
private javax.swing.JTextField jTextField_Nguon;
// End of variables declaration//GEN-END:variables
/**
* @return the jTextField_Dich
*/
public javax.swing.JTextField getJTextField_Dich() {
return jTextField_Dich;
}
/**
* @return the jTextField_Nguon
*/
public javax.swing.JTextField getJTextField_Nguon() {
return jTextField_Nguon;
} // End of variables declaration
class Task extends SwingWorker<Void, Void> {
public void copyFile(){
// TODO add your handling code here:
String str_FileNguon = getJTextField_Nguon().getText();
String str_FileDich = getJTextField_Dich().getText();
try {
boQuanLyFile.movefile(str_FileNguon, str_FileDich);
} catch (FileNotFoundException ex) {
Logger.getLogger(Dialog_Move.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Move file thất bại! Lỗi: " + ex.getMessage());
} catch (IOException ex) {
Logger.getLogger(Dialog_Move.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Move file thất bại! Lỗi: " + ex.getMessage());
}
}
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
copyFile();
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
jButton_Move.setEnabled(true);
setCursor(null); //turn off the wait cursor
//jLabel_DuongDanDangTim.setText("Số file tìm được: " + jTable_TimDuoc.getRowCount());
//Thông báo thành công và xác nhận thoát
jLabel_DangMove.setText("Đã hoàn thành!");
/*if (JOptionPane.showConfirmDialog(null, "Move file thành công! Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)*/
dispose();
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dialog_Copy.java
*
* Created on Apr 16, 2009, 7:41:29 PM
*/
package QuanLyFile;
import java.awt.Cursor;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
/**
*
* @author Administrator
*/
public class Dialog_ReMove extends javax.swing.JDialog {
BoQuanLyFile boQuanLyFile;
Task task;
/** Creates new form Dialog_Copy */
public Dialog_ReMove(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
jButton_Thoat.setText("Thoát");
jButton_Delete.setText("Delete");
jLabel_Delete.setText("Delete:");
jLabel3.setText("Đang Delete:");
boQuanLyFile = new BoQuanLyFile();
boQuanLyFile.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("DangReMove")){
jLabel_DangMove.setText(evt.getNewValue().toString());
}
}
});
}
/**
* @param jTextField_Nguon the jTextField_Nguon to set
*/
public void setJTextField_Nguon(javax.swing.JTextField jTextField_Nguon) {
this.jTextField_Nguon = jTextField_Nguon;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton_Delete = new javax.swing.JButton();
jButton_Thoat = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jLabel_Delete = new javax.swing.JLabel();
jTextField_Nguon = new javax.swing.JTextField();
jLabel_DangMove = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setName("Form"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doan_totalcommander_002.DoAn_TatalCommande_002App.class).getContext().getResourceMap(Dialog_ReMove.class);
jButton_Delete.setText(resourceMap.getString("jButton_Move.text")); // NOI18N
jButton_Delete.setName("jButton_Move"); // NOI18N
jButton_Delete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_MoveActionPerformed(evt);
}
});
jButton_Thoat.setText(resourceMap.getString("jButton_Thoat.text")); // NOI18N
jButton_Thoat.setName("jButton_Thoat"); // NOI18N
jButton_Thoat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ThoatActionPerformed(evt);
}
});
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
jLabel_Delete.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel_Delete.setName("jLabel1"); // NOI18N
jTextField_Nguon.setName("jTextField_Nguon"); // NOI18N
jLabel_DangMove.setText(resourceMap.getString("jLabel_DangMove.text")); // NOI18N
jLabel_DangMove.setName("jLabel_DangMove"); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel_Delete)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
.addComponent(jTextField_Nguon, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel_DangMove, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton_Delete)
.addGap(4, 4, 4)
.addComponent(jButton_Thoat)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_Nguon, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_Delete, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel_DangMove, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 21, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_Delete)
.addComponent(jButton_Thoat))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_MoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_MoveActionPerformed
// TODO add your handling code here:
jButton_Delete.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
task = new Task();
task.addPropertyChangeListener(boQuanLyFile.getPropertyChangeListeners()[0]);
task.execute();
}//GEN-LAST:event_jButton_MoveActionPerformed
private void jButton_ThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ThoatActionPerformed
// TODO add your handling code here:
if (JOptionPane.showConfirmDialog(null, "Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
dispose();
}//GEN-LAST:event_jButton_ThoatActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Dialog_Move dialog = new Dialog_Move(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_Delete;
private javax.swing.JButton jButton_Thoat;
private javax.swing.JLabel jLabel_Delete;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel_DangMove;
private javax.swing.JTextField jTextField_Nguon;
// End of variables declaration//GEN-END:variables
/**
* @return the jTextField_Nguon
*/
public javax.swing.JTextField getJTextField_Nguon() {
return jTextField_Nguon;
} // End of variables declaration
class Task extends SwingWorker<Void, Void> {
public void deleteFile(){
try {
// TODO add your handling code here:
String str_FileNguon = getJTextField_Nguon().getText();
boQuanLyFile.removeDirectory(new File(str_FileNguon), false);
} catch (IOException ex) {
Logger.getLogger(Dialog_ReMove.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Delete file thất bại! Lỗi: " + ex.getMessage());
}
}
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
deleteFile();
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
jButton_Delete.setEnabled(true);
setCursor(null); //turn off the wait cursor
//jLabel_DuongDanDangTim.setText("Số file tìm được: " + jTable_TimDuoc.getRowCount());
//Thông báo thành công và xác nhận thoát
jLabel_DangMove.setText("Đã hoàn thành!");
/*if (JOptionPane.showConfirmDialog(null, "Delete file thành công! Bạn muốn thoát?"
, "Xác nhận thoát", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)*/
dispose();
}
}
}
| Java |
package edu.gatech.gro.model;
import edu.gatech.gro.utils.Utils;
public class ItemType extends AbstractObject {
/* Attributes matching exactly the database model. */
private String name;
private String nameClean;
public ItemType() {
super();
}
public String getNameClean() {
return nameClean;
}
public void setNameClean(String nameClean) {
this.nameClean = nameClean;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
this.setNameClean(Utils.cleanName(name));
}
}
| Java |
package edu.gatech.gro.model;
import java.util.ArrayList;
public class ListGroup extends ItemType {
private ArrayList<Item> items;
public void setItems(ArrayList<Item> items) {
this.items = items;
}
public ArrayList<Item> getItems() {
return items;
}
}
| Java |
package edu.gatech.gro.model;
public class Currency {
public static final Currency[] ALL = new Currency[] { new Currency(1, "$", "dollar"), new Currency(2, "€", "euro"), new Currency(3, "£", "pound") };
private final int id;
private final String symbol;
private final String name;
private Currency(int id, String symbol, String name) {
this.id = id;
this.symbol = symbol;
this.name = name;
}
public int getId() {
return id;
}
public String getSymbol() {
return symbol;
}
public String getName() {
return name;
}
public static String[] allSymbols() {
String[] r = new String[ALL.length];
for (int i = 0; i < ALL.length; i++) {
r[i] = ALL[i].getSymbol();
}
return r;
}
}
| Java |
package edu.gatech.gro.model;
import edu.gatech.gro.utils.Utils;
public class Item extends AbstractObject {
/* Attributes matching exactly the database model. */
private int itemTypeId;
private int groceryStoreId;
private String name;
private String nameClean;
private String barCode;
private String barCodeHash;
private double price;
private int currency;
/* Attributes to ease the use of the class */
private Item item;
private GroceryStore groceryStore;
public Item() {
super();
}
public Item getItem() {
// TODO: need to be improved! Not working!
return item;
}
public void setItem(Item item) {
// TODO: need to be improved! Not working!
this.item = item;
}
public GroceryStore getGroceryStore() {
// TODO: need to be improved! Not working!
return groceryStore;
}
public void setGroceryStore(GroceryStore groceryStore) {
// TODO: need to be improved! Not working!
this.groceryStore = groceryStore;
}
public int getItemTypeId() {
return itemTypeId;
}
public void setItemTypeId(int itemTypeId) {
this.itemTypeId = itemTypeId;
}
public int getGroceryStoreId() {
return groceryStoreId;
}
public void setGroceryStoreId(int groceryStoreId) {
this.groceryStoreId = groceryStoreId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
this.setNameClean(Utils.cleanName(name));
}
public String getNameClean() {
return nameClean;
}
public void setNameClean(String nameClean) {
this.nameClean = nameClean;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
this.setBarCodeHash(Utils.hash(barCode));
}
public String getBarCodeHash() {
return barCodeHash;
}
public void setBarCodeHash(String barCodeHash) {
this.barCodeHash = barCodeHash;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getCurrency() {
return currency;
}
public void setCurrency(int currency) {
this.currency = currency;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append(id).append(" ");
b.append(name).append(" ");
return b.toString();
}
}
| Java |
package edu.gatech.gro.model;
import java.util.List;
public class ObjectResponse {
private boolean success;
private Object data;
private int totalCount;
private List<String> errors;
public boolean isSuccessful() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getErrorsAsString() {
StringBuilder b = new StringBuilder();
for (int i = 0; i < errors.size(); i++) {
if (i > 0) {
b.append("\n");
}
b.append(errors.get(i));
}
return b.toString();
}
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
}
| Java |
package edu.gatech.gro.model;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import edu.gatech.gro.utils.Utils;
public class NamedList extends AbstractObject {
/* Attributes matching exactly the database model. */
private int userId;
private String name;
private String nameClean;
/* Attributes to ease the use of the class */
private User user;
private ArrayList<ListGroup> itemGroups = new ArrayList<ListGroup>();
private List<ListItem> unsortedItems;
public NamedList() {
super();
}
public void setItemGroups(ArrayList<ListGroup> itemGroups) {
this.itemGroups = itemGroups;
}
public ArrayList<ListGroup> getItemGroups() {
return itemGroups;
}
public ArrayList<ListGroup> getItemGroups(Context ctx) {
if (itemGroups == null && ctx != null) {
}
return this.itemGroups;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getNameClean() {
return nameClean;
}
public void setNameClean(String nameClean) {
this.nameClean = nameClean;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
this.setNameClean(Utils.cleanName(name));
}
}
| Java |
package edu.gatech.gro.model;
import edu.gatech.gro.utils.Utils;
public class GroceryStore extends AbstractObject {
/* Attributes matching exactly the database model. */
private String name;
private String nameClean;
public GroceryStore() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
this.setNameClean(Utils.cleanName(name));
}
public String getNameClean() {
return nameClean;
}
public void setNameClean(String nameClean) {
this.nameClean = nameClean;
}
}
| Java |
package edu.gatech.gro.model;
import java.util.List;
import android.content.Context;
import edu.gatech.gro.model.dao.NamedListDao;
import edu.gatech.gro.utils.Utils;
public class User extends AbstractObject {
/* Attributes matching exactly the database model. */
private String username;
private String usernameClean;
private String email;
private String password;
private List<NamedList> lists;
public User() {
super();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
this.setUsernameClean(Utils.cleanName(username));
}
public String getUsernameClean() {
return usernameClean;
}
public void setUsernameClean(String usernameClean) {
this.usernameClean = usernameClean;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<NamedList> getLists(Context ctx) {
if (lists == null && ctx != null) {
NamedListDao dao = new NamedListDao(ctx);
lists = dao.getAllNamedLists(id);
}
return lists;
}
public List<NamedList> getLists() {
return lists;
}
public void setLists(List<NamedList> lists) {
this.lists = lists;
}
}
| Java |
package edu.gatech.gro.model.parser;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import edu.gatech.gro.model.NamedList;
public class NamedListJsonHandler extends JsonHandler {
private static final String TAG = "NAMED_LIST_JSON_HANDLER";
@Override
protected void parseDataArray() {
try {
getResponse().setData(getNamedLists(json.getJSONArray("data")));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
@Override
protected void parseData() {
NamedList dataParsed = null;
try {
dataParsed = getNamedList(json.getJSONObject("data"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
public static ArrayList<NamedList> getNamedLists(JSONArray array) {
ArrayList<NamedList> dataParsed = new ArrayList<NamedList>();
if (array != null) {
try {
for (int i = 0; i < array.length(); i++) {
dataParsed.add(getNamedList(array.getJSONObject(i)));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return dataParsed;
}
public static NamedList getNamedList(JSONObject obj) {
NamedList nl = new NamedList();
try {
parseAbstractObject(nl, obj);
nl.setUserId(obj.getInt("userId"));
nl.setName(obj.getString("name"));
nl.setNameClean(obj.getString("nameClean"));
if (obj.has("groups")) {
nl.setItemGroups(ListGroupListItemJsonHandler.getListGroups(obj.getJSONArray("groups")));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
return nl;
}
}
| Java |
package edu.gatech.gro.model.parser;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import edu.gatech.gro.model.User;
public class UserJsonHandler extends JsonHandler {
private static final String TAG = "USER_JSON_HANDLER";
@Override
protected void parseDataArray() {
List<User> dataParsed = new ArrayList<User>();
try {
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
dataParsed.add(getUser(array.getJSONObject(i)));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
@Override
protected void parseData() {
User dataParsed = null;
try {
dataParsed = getUser(json.getJSONObject("data"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
public User getUser(JSONObject obj) {
User u = new User();
try {
parseAbstractObject(u, obj);
u.setUsername(obj.getString("username"));
u.setUsernameClean(obj.getString("usernameClean"));
if (obj.has("email")) {
u.setEmail(obj.getString("email"));
}
if (obj.has("password")) {
u.setPassword(obj.getString("password"));
}
if (obj.has("lists")) {
u.setLists(NamedListJsonHandler.getNamedLists(obj.getJSONArray("lists")));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
return u;
}
}
| Java |
package edu.gatech.gro.model.parser;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import edu.gatech.gro.model.Item;
import edu.gatech.gro.model.ListItem;
public class ListItemJsonHandler extends JsonHandler {
private static final String TAG = "LIST_ITEM_JSON_HANDLER";
@Override
protected void parseDataArray() {
try {
getResponse().setData(getListItems(json.getJSONArray("data")));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
@Override
protected void parseData() {
ListItem dataParsed = null;
try {
dataParsed = getListItem(json.getJSONObject("data"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
public static ArrayList<Item> getListItems(JSONArray array) {
ArrayList<Item> dataParsed = new ArrayList<Item>();
if (array != null) {
try {
for (int i = 0; i < array.length(); i++) {
dataParsed.add(getListItem(array.getJSONObject(i)));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
return dataParsed;
}
public static ListItem getListItem(JSONObject obj) {
ListItem li = new ListItem();
try {
parseAbstractObject(li, obj);
li.setName(obj.getString("name"));
li.setItemTypeId(obj.getInt("itemTypeId"));
li.setGroceryStoreId(obj.getInt("groceryStoreId"));
li.setBarCode(obj.getString("barCode"));
li.setPrice(obj.getDouble("price"));
li.setCurrency(obj.getInt("currency"));
li.setChecked(obj.getBoolean("checked"));
li.setQuantity(obj.getInt("quantity"));
li.setCurrentQuantity(obj.getInt("currentQuantity"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
return li;
}
}
| Java |
package edu.gatech.gro.model.parser;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import edu.gatech.gro.model.ItemType;
public class ItemTypeJsonHandler extends JsonHandler {
private static final String TAG = "ITEM_TYPE_JSON_HANDLER";
@Override
protected void parseDataArray() {
List<ItemType> dataParsed = new ArrayList<ItemType>();
try {
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
dataParsed.add(getItemType(array.getJSONObject(i)));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
@Override
protected void parseData() {
ItemType dataParsed = null;
try {
dataParsed = getItemType(json.getJSONObject("data"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
public ItemType getItemType(JSONObject obj) {
ItemType it = new ItemType();
try {
parseAbstractObject(it, obj);
it.setName(obj.getString("name"));
it.setNameClean(obj.getString("nameClean"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
return it;
}
}
| Java |
package edu.gatech.gro.model.parser;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import edu.gatech.gro.model.Item;
import edu.gatech.gro.model.ListGroup;
public class ListGroupItemJsonHandler extends JsonHandler {
private static final String TAG = "LIST_GROUP_ITEM_JSON_HANDLER";
@Override
protected void parseDataArray() {
List<ListGroup> dataParsed = new ArrayList<ListGroup>();
try {
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
dataParsed.add(getListGroup(array.getJSONObject(i)));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
@Override
protected void parseData() {
ListGroup dataParsed = null;
try {
dataParsed = getListGroup(json.getJSONObject("data"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
public ListGroup getListGroup(JSONObject obj) {
ListGroup group = new ListGroup();
try {
group.setId(obj.getInt("id"));
group.setName(obj.getString("name"));
group.setNameClean(obj.getString("nameClean"));
if (obj.has("items") && obj.optJSONArray("items") != null) {
JSONArray jsonItems = obj.getJSONArray("items");
ArrayList<Item> list = new ArrayList<Item>();
ItemJsonHandler h = new ItemJsonHandler();
for (int i = 0; i < jsonItems.length(); i++) {
list.add(h.getItem(jsonItems.getJSONObject(i)));
}
group.setItems(list);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
return group;
}
}
| Java |
package edu.gatech.gro.model.parser;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import edu.gatech.gro.model.GroceryStore;
public class GroceryStoreJsonHandler extends JsonHandler {
private static final String TAG = "GROCERY_STORE_JSON_HANDLER";
@Override
protected void parseDataArray() {
List<GroceryStore> dataParsed = new ArrayList<GroceryStore>();
try {
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
dataParsed.add(getGroceryStore(array.getJSONObject(i)));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
@Override
protected void parseData() {
GroceryStore dataParsed = null;
try {
dataParsed = getGroceryStore(json.getJSONObject("data"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
public GroceryStore getGroceryStore(JSONObject obj) {
GroceryStore gs = new GroceryStore();
try {
parseAbstractObject(gs, obj);
gs.setName(obj.getString("name"));
gs.setNameClean(obj.getString("nameClean"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
return gs;
}
}
| Java |
package edu.gatech.gro.model.parser;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import edu.gatech.gro.model.Item;
public class ItemJsonHandler extends JsonHandler {
private static final String TAG = "ITEM_TYPE_JSON_HANDLER";
@Override
protected void parseDataArray() {
List<Item> dataParsed = new ArrayList<Item>();
try {
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
dataParsed.add(getItem(array.getJSONObject(i)));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
@Override
protected void parseData() {
Item dataParsed = null;
try {
dataParsed = getItem(json.getJSONObject("data"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
public Item getItem(JSONObject obj) {
Item i = new Item();
try {
parseAbstractObject(i, obj);
i.setName(obj.getString("name"));
i.setItemTypeId(obj.getInt("itemTypeId"));
i.setGroceryStoreId(obj.getInt("groceryStoreId"));
i.setBarCode(obj.getString("barCode"));
i.setPrice(obj.getDouble("price"));
i.setCurrency(obj.getInt("currency"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
return i;
}
}
| Java |
package edu.gatech.gro.model.parser;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import edu.gatech.gro.model.ListGroup;
public class ListGroupListItemJsonHandler extends JsonHandler {
private static final String TAG = "LIST_GROUP_LIST_ITEM_JSON_HANDLER";
@Override
protected void parseDataArray() {
try {
getResponse().setData(json.getJSONArray("data"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
@Override
protected void parseData() {
ListGroup dataParsed = null;
try {
dataParsed = getListGroup(json.getJSONObject("data"));
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
getResponse().setData(dataParsed);
}
public static ArrayList<ListGroup> getListGroups(JSONArray array) {
ArrayList<ListGroup> dataParsed = new ArrayList<ListGroup>();
if (array != null) {
try {
for (int i = 0; i < array.length(); i++) {
dataParsed.add(getListGroup(array.getJSONObject(i)));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
return dataParsed;
}
public static ListGroup getListGroup(JSONObject obj) {
ListGroup group = new ListGroup();
try {
group.setId(obj.getInt("id"));
group.setName(obj.getString("name"));
group.setNameClean(obj.getString("nameClean"));
if (obj.has("items") && obj.optJSONArray("items") != null) {
group.setItems(ListItemJsonHandler.getListItems(obj.getJSONArray("items")));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
return group;
}
}
| Java |
package edu.gatech.gro.model.parser;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import edu.gatech.gro.model.AbstractObject;
import edu.gatech.gro.model.ObjectResponse;
public class JsonHandler {
private static final String TAG = "JSON_HANDLER";
protected JSONObject json;
private ObjectResponse response;
public final void parse(String jsonString) {
response = new ObjectResponse();
try {
Log.d(TAG, jsonString);
json = new JSONObject(jsonString);
response.setSuccess(json.getBoolean("success"));
if (response.isSuccessful()) {
if (json.has("totalCount")) {
response.setTotalCount(json.getInt("totalCount"));
}
if (json.optJSONArray("data") != null) {
parseDataArray();
} else {
parseData();
}
} else {
parseError();
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
public ObjectResponse getResponse() {
return response;
}
private final void parseError() {
if (json.has("errors")) {
List<String> errors = new ArrayList<String>();
try {
JSONArray array = json.getJSONArray("errors");
for (int i = 0; i < array.length(); i++) {
errors.add(array.getString(i));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
response.setErrors(errors);
}
}
protected void parseDataArray() {
}
protected void parseData() {
}
protected static void parseAbstractObject(AbstractObject ao, JSONObject obj) throws JSONException {
if (ao != null) {
if (obj.has("id")) {
ao.setId(obj.getInt("id"));
}
if (obj.has("creationTime")) {
ao.setCreationTime(obj.getInt("creationTime"));
}
if (obj.has("lastUpdateTime")) {
ao.setLastUpdateTime(obj.getInt("lastUpdateTime"));
}
if (obj.has("deleteFlag")) {
ao.setDeleteFlag(obj.getBoolean("deleteFlag"));
}
}
}
}
| Java |
package edu.gatech.gro.model.dao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public abstract class DatabaseHandler extends SQLiteOpenHelper {
protected static final String DATABASE_NAME = "grocery311db";
protected static final int DATABASE_VERSION = 4;
protected static final String USER_TABLE = "User";
private static final String USER_TABLE_CREATE = "CREATE TABLE " + USER_TABLE + " (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, usernameClean TEXT NOT NULL, email TEXT NOT NULL, password TEXT NOT NULL, creationTime INTEGER, lastUpdateTime INTEGER, deleteFlag INTEGER);";
protected static final String NAMED_LIST_TABLE = "NamedList";
private static final String NAMED_LIST_TABLE_CREATE = "CREATE TABLE " + NAMED_LIST_TABLE + " (id INTEGER PRIMARY KEY AUTOINCREMENT, userId INTEGER REFERENCES User(id) ON UPDATE CASCADE ON DELETE CASCADE, name TEXT NOT NULL, nameClean TEXT NOT NULL, creationTime INTEGER, lastUpdateTime INTEGER, deleteFlag INTEGER);";
protected static final String NAMED_LIST_ITEM_TABLE = "NamedListItem";
private static final String NAMED_LIST_ITEM_TABLE_CREATE = "CREATE TABLE " + NAMED_LIST_ITEM_TABLE + " (namedListId INTEGER REFERENCES NamedList(id) ON UPDATE CASCADE ON DELETE CASCADE, itemId INTEGER REFERENCES Item(id), checked INTEGER, quantity INTEGER, currentQuantity INTEGER, creationTime INTEGER, lastUpdateTime INTEGER, deleteFlag INTEGER);";
protected static final String GROCERY_STORE_TABLE = "GroceryStore";
private static final String GROCERY_STORE_TABLE_CREATE = "CREATE TABLE " + GROCERY_STORE_TABLE + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, nameClean TEXT NOT NULL, creationTime INTEGER, lastUpdateTime INTEGER, deleteFlag INTEGER);";
protected static final String ITEM_TYPE_TABLE = "ItemType";
private static final String ITEM_TYPE_TABLE_CREATE = "CREATE TABLE " + ITEM_TYPE_TABLE + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, nameClean TEXT NOT NULL, creationTime INTEGER, lastUpdateTime INTEGER, deleteFlag INTEGER);";
protected static final String ITEM_TABLE = "Item";
private static final String ITEM_TABLE_CREATE = "CREATE TABLE " + ITEM_TABLE + " (id INTEGER PRIMARY KEY AUTOINCREMENT, itemTypeId INTEGER REFERENCES ItemType(id), groceryStoreId INTEGER REFERENCES GroceryStore(id), name TEXT NOT NULL, nameClean TEXT NOT NULL, barCode TEXT NOT NULL, barCodeHash TEXT NOT NULL, price REAL, currency INTEGER, creationTime INTEGER, lastUpdateTime INTEGER, deleteFlag INTEGER);";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USER_TABLE_CREATE);
db.execSQL(NAMED_LIST_TABLE_CREATE);
db.execSQL(GROCERY_STORE_TABLE_CREATE);
db.execSQL(ITEM_TYPE_TABLE_CREATE);
db.execSQL(ITEM_TABLE_CREATE);
db.execSQL(NAMED_LIST_ITEM_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + NAMED_LIST_ITEM_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + ITEM_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + ITEM_TYPE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + GROCERY_STORE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + NAMED_LIST_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
onCreate(db);
}
public abstract void clear();
}
| Java |
package edu.gatech.gro.model.dao;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import edu.gatech.gro.model.ListItem;
public class ListItemDao extends DatabaseHandler {
private static final String TAG = "NAMED_LIST_ITEM_DAO";
public ListItemDao(Context context) {
super(context);
}
@Override
public void clear() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(NAMED_LIST_ITEM_TABLE, "namedListId > 0", null);
db.close();
}
public ArrayList<ListItem> getAllListItems(final int listId) {
ArrayList<ListItem> list = new ArrayList<ListItem>();
String selectQuery = "SELECT * FROM " + NAMED_LIST_ITEM_TABLE + " WHERE namedListId = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(listId) });
if (cursor.moveToFirst()) {
do {
ListItem listItem = new ListItem();
listItem.setNamedListId(cursor.getInt(0));
listItem.setId(cursor.getInt(1));
listItem.setChecked(cursor.getInt(2) == 1);
listItem.setQuantity(cursor.getInt(3));
listItem.setCurrentQuantity(cursor.getInt(4));
listItem.setCreationTime(cursor.getInt(5));
listItem.setLastUpdateTime(cursor.getInt(6));
listItem.setDeleteFlag(cursor.getInt(7) == 1);
list.add(listItem);
} while (cursor.moveToNext());
}
db.close();
return list;
}
public int count() {
String countQuery = "SELECT * FROM " + NAMED_LIST_ITEM_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
public boolean saveListItem(ListItem listItem) {
if (listItem == null) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("namedListId", listItem.getNamedListId());
values.put("itemId", listItem.getId());
values.put("checked", listItem.isChecked() ? 1 : 0);
values.put("quantity", listItem.getQuantity());
values.put("currentQuantity", listItem.getCurrentQuantity());
values.put("creationTime", listItem.getCreationTime());
values.put("lastUpdateTime", listItem.getLastUpdateTime());
values.put("deleteFlag", listItem.isDeleteFlag() ? 1 : 0);
long id = db.insert(NAMED_LIST_ITEM_TABLE, null, values);
if (id == -1) {
// TODO: error
return false;
} else {
listItem.setId((int) id);
}
db.close();
return true;
}
public boolean updateListItem(ListItem listItem) {
if (listItem == null || listItem.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("checked", listItem.isChecked() ? 1 : 0);
values.put("quantity", listItem.getQuantity());
values.put("currentQuantity", listItem.getCurrentQuantity());
values.put("lastUpdateTime", listItem.getLastUpdateTime());
values.put("deleteFlag", listItem.isDeleteFlag() ? 1 : 0);
int r = db.update(NAMED_LIST_ITEM_TABLE, values, "namedListId = ? AND itemId = ?", new String[] { String.valueOf(listItem.getNamedListId()), String.valueOf(listItem.getId()) });
db.close();
return r == 1;
}
public boolean deleteListItem(ListItem listItem) {
if (listItem == null || listItem.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
int r = db.delete(NAMED_LIST_ITEM_TABLE, "namedListId = ? AND itemId = ?", new String[] { String.valueOf(listItem.getNamedListId()), String.valueOf(listItem.getId()) });
db.close();
return r == 1;
}
}
| Java |
package edu.gatech.gro.model.dao;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import edu.gatech.gro.model.ItemType;
public class ItemTypeDao extends DatabaseHandler {
private static final String TAG = "ITEM_TYPE_DAO";
public ItemTypeDao(Context context) {
super(context);
}
@Override
public void clear() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(ITEM_TYPE_TABLE, "id > 0", null);
db.close();
}
public ArrayList<ItemType> getAllItemTypes() {
ArrayList<ItemType> list = new ArrayList<ItemType>();
String selectQuery = "SELECT * FROM " + ITEM_TYPE_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
ItemType itemType = new ItemType();
itemType.setId(cursor.getInt(0));
itemType.setName(cursor.getString(1));
itemType.setNameClean(cursor.getString(2));
itemType.setCreationTime(cursor.getInt(3));
itemType.setLastUpdateTime(cursor.getInt(4));
itemType.setDeleteFlag(cursor.getInt(5) == 1);
list.add(itemType);
} while (cursor.moveToNext());
}
db.close();
return list;
}
public int count() {
String countQuery = "SELECT * FROM " + ITEM_TYPE_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
db.close();
return cursor.getCount();
}
public boolean saveItemType(final ItemType itemType) {
if (itemType == null) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", itemType.getName());
values.put("nameClean", itemType.getNameClean());
values.put("creationTime", itemType.getCreationTime());
values.put("lastUpdateTime", itemType.getLastUpdateTime());
values.put("deleteFlag", itemType.isDeleteFlag() ? 1 : 0);
long id = db.insert(ITEM_TYPE_TABLE, null, values);
if (id == -1) {
// TODO: error*
return false;
} else {
itemType.setId((int) id);
}
db.close();
return true;
}
public boolean upgrade(ArrayList<ItemType> itemTypes) {
if (itemTypes == null) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for (ItemType itemType : itemTypes) {
if (itemType.isDeleteFlag()) {
db.delete(ITEM_TYPE_TABLE, "id = ?", new String[] { String.valueOf(itemType.getId()) });
} else {
values.clear();
values.put("id", itemType.getId());
values.put("name", itemType.getName());
values.put("nameClean", itemType.getNameClean());
values.put("creationTime", itemType.getCreationTime());
values.put("lastUpdateTime", itemType.getLastUpdateTime());
values.put("deleteFlag", 0);
db.replace(ITEM_TYPE_TABLE, null, values);
}
}
db.close();
return true;
}
public boolean updateItemType(final ItemType itemType) {
if (itemType == null || itemType.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", itemType.getName());
values.put("nameClean", itemType.getNameClean());
values.put("lastUpdateTime", itemType.getLastUpdateTime());
values.put("deleteFlag", itemType.isDeleteFlag() ? 1 : 0);
// updating row
int r = db.update(ITEM_TYPE_TABLE, values, "id = ?", new String[] { String.valueOf(itemType.getId()) });
db.close();
return r == 1;
}
public boolean deleteItemType(final ItemType itemType) {
if (itemType == null || itemType.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
int r = db.delete(ITEM_TYPE_TABLE, "id = ?", new String[] { String.valueOf(itemType.getId()) });
db.close();
return r == 1;
}
}
| Java |
package edu.gatech.gro.model.dao;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import edu.gatech.gro.model.GroceryStore;
public class GroceryStoreDao extends DatabaseHandler {
private static final String TAG = "GROCERY_STORE_DAO";
public GroceryStoreDao(Context context) {
super(context);
}
@Override
public void clear() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(GROCERY_STORE_TABLE, "id > 0", null);
db.close();
}
public ArrayList<GroceryStore> getAllGroceryStores() {
ArrayList<GroceryStore> list = new ArrayList<GroceryStore>();
String selectQuery = "SELECT * FROM " + GROCERY_STORE_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
GroceryStore store = new GroceryStore();
store.setId(cursor.getInt(0));
store.setName(cursor.getString(1));
store.setNameClean(cursor.getString(2));
store.setCreationTime(cursor.getInt(3));
store.setLastUpdateTime(cursor.getInt(4));
store.setDeleteFlag(cursor.getInt(5) == 1);
list.add(store);
} while (cursor.moveToNext());
}
db.close();
return list;
}
public int count() {
String countQuery = "SELECT * FROM " + GROCERY_STORE_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
db.close();
return cursor.getCount();
}
public boolean saveGroceryStore(final GroceryStore store) {
if (store == null) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", store.getName());
values.put("nameClean", store.getNameClean());
values.put("creationTime", store.getCreationTime());
values.put("lastUpdateTime", store.getLastUpdateTime());
values.put("deleteFlag", store.isDeleteFlag() ? 1 : 0);
long id = db.insert(GROCERY_STORE_TABLE, null, values);
if (id == -1) {
// TODO: error
return false;
} else {
store.setId((int) id);
}
db.close();
return true;
}
public boolean upgrade(ArrayList<GroceryStore> stores) {
if (stores == null) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for (GroceryStore store : stores) {
if (store.isDeleteFlag()) {
db.delete(GROCERY_STORE_TABLE, "id = ?", new String[] { String.valueOf(store.getId()) });
} else {
values.clear();
values.put("id", store.getId());
values.put("name", store.getName());
values.put("nameClean", store.getNameClean());
values.put("creationTime", store.getCreationTime());
values.put("lastUpdateTime", store.getLastUpdateTime());
values.put("deleteFlag", 0);
db.replace(GROCERY_STORE_TABLE, null, values);
}
}
db.close();
return true;
}
public boolean updateGroceryStore(final GroceryStore store) {
if (store == null || store.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", store.getName());
values.put("nameClean", store.getNameClean());
values.put("lastUpdateTime", store.getLastUpdateTime());
values.put("deleteFlag", store.isDeleteFlag() ? 1 : 0);
// updating row
int r = db.update(GROCERY_STORE_TABLE, values, "id = ?", new String[] { String.valueOf(store.getId()) });
db.close();
return r == 1;
}
public boolean deleteGroceryStore(final GroceryStore store) {
if (store == null || store.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
int r = db.delete(GROCERY_STORE_TABLE, "id = ?", new String[] { String.valueOf(store.getId()) });
db.close();
return r == 1;
}
}
| Java |
package edu.gatech.gro.model.dao;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import edu.gatech.gro.model.Item;
import edu.gatech.gro.model.ListItem;
public class ItemDao extends DatabaseHandler {
private static final String TAG = "ITEM_DAO";
public ItemDao(Context context) {
super(context);
}
@Override
public void clear() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(ITEM_TABLE, "id > 0", null);
db.close();
}
public ArrayList<Item> getAllItems() {
ArrayList<Item> list = new ArrayList<Item>();
String selectQuery = "SELECT * FROM " + ITEM_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Item item = new ListItem();
item.setId(cursor.getInt(0));
item.setItemTypeId(cursor.getInt(1));
item.setGroceryStoreId(cursor.getInt(2));
item.setName(cursor.getString(3));
item.setNameClean(cursor.getString(4));
item.setBarCode(cursor.getString(5));
item.setBarCodeHash(cursor.getString(6));
item.setPrice(cursor.getDouble(7));
item.setCurrency(cursor.getInt(8));
item.setCreationTime(cursor.getInt(9));
item.setLastUpdateTime(cursor.getInt(10));
item.setDeleteFlag(cursor.getInt(11) == 1);
list.add(item);
} while (cursor.moveToNext());
}
db.close();
return list;
}
public int count() {
String countQuery = "SELECT * FROM " + ITEM_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
public boolean saveItem(Item item) {
if (item == null) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("itemTypeId", item.getItemTypeId());
values.put("groceryStoreId", item.getGroceryStoreId());
values.put("name", item.getName());
values.put("nameClean", item.getNameClean());
values.put("barCode", item.getBarCode());
values.put("barCodeHash", item.getBarCodeHash());
values.put("price", item.getPrice());
values.put("currency", item.getCurrency());
values.put("creationTime", item.getCreationTime());
values.put("lastUpdateTime", item.getLastUpdateTime());
values.put("deleteFlag", 0);
long id = db.insert(ITEM_TABLE, null, values);
if (id == -1) {
// TODO: error
return false;
} else {
item.setId((int) id);
}
db.close();
return true;
}
public boolean upgrade(ArrayList<Item> items) {
if (items == null) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for (Item item : items) {
if (item.isDeleteFlag()) {
db.delete(ITEM_TABLE, "id = ?", new String[] { String.valueOf(item.getId()) });
} else {
values.clear();
values.put("id", item.getId());
values.put("itemTypeId", item.getItemTypeId());
values.put("groceryStoreId", item.getGroceryStoreId());
values.put("name", item.getName());
values.put("nameClean", item.getNameClean());
values.put("barCode", item.getBarCode());
values.put("barCodeHash", item.getBarCodeHash());
values.put("price", item.getPrice());
values.put("currency", item.getCurrency());
values.put("creationTime", item.getCreationTime());
values.put("lastUpdateTime", item.getLastUpdateTime());
values.put("deleteFlag", 0);
db.replace(ITEM_TABLE, null, values);
}
}
db.close();
return true;
}
public boolean updateListItem(Item item) {
if (item == null || item.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("itemTypeId", item.getItemTypeId());
values.put("groceryStoreId", item.getGroceryStoreId());
values.put("name", item.getName());
values.put("nameClean", item.getNameClean());
values.put("barCode", item.getBarCode());
values.put("barCodeHash", item.getBarCodeHash());
values.put("price", item.getPrice());
values.put("currency", item.getCurrency());
values.put("lastUpdateTime", item.getLastUpdateTime());
values.put("deleteFlag", item.isDeleteFlag() ? 1 : 0);
int r = db.update(ITEM_TABLE, values, "id = ?", new String[] { String.valueOf(item.getId()) });
db.close();
return r == 1;
}
public boolean deleteListItem(ListItem listItem) {
if (listItem == null || listItem.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
int r = db.delete(ITEM_TABLE, "id = ?", new String[] { String.valueOf(listItem.getId()) });
db.close();
return r == 1;
}
}
| Java |
package edu.gatech.gro.model.dao;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import edu.gatech.gro.model.Item;
import edu.gatech.gro.model.ListGroup;
import edu.gatech.gro.model.ListItem;
import edu.gatech.gro.model.NamedList;
public class NamedListDao extends DatabaseHandler {
private static final String TAG = "NAMED_LIST_DAO";
public NamedListDao(Context context) {
super(context);
}
@Override
public void clear() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(NAMED_LIST_TABLE, "id > 0", null);
db.close();
}
public ArrayList<NamedList> getAllNamedLists(final int userId) {
ArrayList<NamedList> list = new ArrayList<NamedList>();
String selectQuery = "SELECT * FROM " + NAMED_LIST_TABLE + " WHERE userId = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(userId) });
if (cursor.moveToFirst()) {
do {
NamedList namedList = new NamedList();
namedList.setId(cursor.getInt(0));
namedList.setUserId(cursor.getInt(1));
namedList.setName(cursor.getString(2));
namedList.setNameClean(cursor.getString(3));
namedList.setCreationTime(cursor.getInt(4));
namedList.setLastUpdateTime(cursor.getInt(5));
namedList.setDeleteFlag(cursor.getInt(6) == 1);
list.add(namedList);
} while (cursor.moveToNext());
}
db.close();
return list;
}
public NamedList getNamedListByNameClean(final int userId, final String nameClean) {
NamedList list = null;
SQLiteDatabase db = this.getReadableDatabase();
String sql = "SELECT * FROM " + NAMED_LIST_TABLE + " WHERE userId = ? AND nameClean = ?";
Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(userId), nameClean });
if (cursor != null) {
cursor.moveToFirst();
list = new NamedList();
list.setId(cursor.getInt(0));
list.setUserId(cursor.getInt(1));
list.setName(cursor.getString(2));
list.setNameClean(cursor.getString(3));
list.setCreationTime(cursor.getInt(4));
list.setLastUpdateTime(cursor.getInt(5));
list.setDeleteFlag(cursor.getInt(6) == 1);
}
cursor.close();
db.close();
return list;
}
public ArrayList<ListGroup> getAllItems(final int listId) {
ArrayList<ListGroup> arr = new ArrayList<ListGroup>();
String sql = "SELECT Item.*, ItemType.name AS typeName, NamedListItem.checked, NamedListItem.quantity, NamedListItem.currentQuantity FROM Item JOIN NamedListItem ON NamedListItem.itemId = Item.id JOIN ItemType ON ItemType.id = Item.itemTypeId WHERE NamedListItem.namedListId = ? ORDER BY ItemType.name ASC, Item.name ASC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(listId) });
int previousCategory = 0;
ArrayList<Item> items = null;
int lastTypeId = 0;
String lastTypeName = "";
if (cursor.moveToFirst()) {
int colItemTypeId = cursor.getColumnIndex("itemTypeId");
int colTypeName = cursor.getColumnIndex("typeName");
int colChecked = cursor.getColumnIndex("checked");
int colQuantity = cursor.getColumnIndex("quantity");
int colCurrentQuantity = cursor.getColumnIndex("currentQuantity");
do {
if (cursor.getInt(colItemTypeId) != previousCategory) {
if (items != null) {
ListGroup group = new ListGroup();
group.setId(lastTypeId);
group.setName(lastTypeName);
group.setItems(items);
arr.add(group);
}
previousCategory = cursor.getInt(colItemTypeId);
items = new ArrayList<Item>();
}
ListItem item = new ListItem();
item.setId(cursor.getInt(0));
item.setItemTypeId(cursor.getInt(1));
item.setGroceryStoreId(cursor.getInt(2));
item.setName(cursor.getString(3));
item.setNameClean(cursor.getString(4));
item.setBarCode(cursor.getString(5));
item.setBarCodeHash(cursor.getString(6));
item.setPrice(cursor.getDouble(7));
item.setCurrency(cursor.getInt(8));
item.setCreationTime(cursor.getInt(9));
item.setLastUpdateTime(cursor.getInt(10));
item.setDeleteFlag(cursor.getInt(11) == 1);
item.setChecked(cursor.getInt(colChecked) == 1);
item.setQuantity(cursor.getInt(colQuantity));
item.setCurrentQuantity(cursor.getInt(colCurrentQuantity));
item.setNamedListId(listId);
items.add(item);
lastTypeId = cursor.getInt(colItemTypeId);
lastTypeName = cursor.getString(colTypeName);
} while (cursor.moveToNext());
}
if (items != null) {
ListGroup group = new ListGroup();
group.setId(lastTypeId);
group.setName(lastTypeName);
group.setItems(items);
arr.add(group);
}
db.close();
return arr;
}
public int count() {
String countQuery = "SELECT * FROM " + NAMED_LIST_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
public boolean saveNamedList(NamedList namedList) {
if (namedList == null) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", namedList.getId());
values.put("userId", namedList.getUserId());
values.put("name", namedList.getName());
values.put("nameClean", namedList.getNameClean());
values.put("creationTime", namedList.getCreationTime());
values.put("lastUpdateTime", namedList.getLastUpdateTime());
values.put("deleteFlag", namedList.isDeleteFlag() ? 1 : 0);
long id = db.insert(NAMED_LIST_TABLE, null, values);
if (id == -1) {
// TODO: error
return false;
} else {
namedList.setId((int) id);
}
db.close();
return true;
}
public boolean updateNamedList(NamedList namedList) {
if (namedList == null || namedList.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", namedList.getName());
values.put("nameClean", namedList.getNameClean());
values.put("lastUpdateTime", namedList.getLastUpdateTime());
values.put("deleteFlag", namedList.isDeleteFlag() ? 1 : 0);
// updating row
int r = db.update(NAMED_LIST_TABLE, values, "id = ?", new String[] { String.valueOf(namedList.getId()) });
db.close();
return r == 1;
}
public boolean deleteNamedList(NamedList namedList) {
if (namedList == null || namedList.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
int r = db.delete(NAMED_LIST_TABLE, "id = ?", new String[] { String.valueOf(namedList.getId()) });
db.close();
return r == 1;
}
}
| Java |
package edu.gatech.gro.model.dao;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import edu.gatech.gro.model.User;
public class UserDao extends DatabaseHandler {
private static final String TAG = "USER_DAO";
public UserDao(Context context) {
super(context);
}
@Override
public void clear() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(USER_TABLE, "id > 0", null);
db.close();
}
public ArrayList<User> getAllUsers() {
ArrayList<User> list = new ArrayList<User>();
String selectQuery = "SELECT * FROM " + USER_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
User user = new User();
user.setId(cursor.getInt(0));
user.setUsername(cursor.getString(1));
user.setUsernameClean(cursor.getString(2));
user.setEmail(cursor.getString(3));
user.setPassword(cursor.getString(4));
user.setCreationTime(cursor.getInt(5));
user.setLastUpdateTime(cursor.getInt(6));
user.setDeleteFlag(cursor.getInt(7) == 1);
list.add(user);
} while (cursor.moveToNext());
}
db.close();
return list;
}
public User getUserByUsernameAndPassword(String username, String password) {
User user = null;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + USER_TABLE + " WHERE username = ? AND password = ?", new String[] { username, password });
if (cursor != null) {
cursor.moveToFirst();
user = new User();
user.setId(cursor.getInt(0));
user.setUsername(cursor.getString(1));
user.setUsernameClean(cursor.getString(2));
user.setEmail(cursor.getString(3));
user.setPassword(cursor.getString(4));
user.setCreationTime(cursor.getInt(5));
user.setLastUpdateTime(cursor.getInt(6));
user.setDeleteFlag(cursor.getInt(7) == 1);
}
cursor.close();
db.close();
return user;
}
public int count() {
String countQuery = "SELECT * FROM " + USER_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
public boolean saveUser(User user) {
if (user == null) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", user.getId());
values.put("username", user.getUsername());
values.put("usernameClean", user.getUsernameClean());
values.put("email", user.getEmail());
values.put("password", user.getPassword());
values.put("creationTime", user.getCreationTime());
values.put("lastUpdateTime", user.getLastUpdateTime());
values.put("deleteFlag", user.isDeleteFlag() ? 1 : 0);
long id = db.insert(USER_TABLE, null, values);
if (id == -1) {
// TODO: error
return false;
} else {
user.setId((int) id);
}
db.close();
return true;
}
public boolean updateUser(User user) {
if (user == null || user.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("username", user.getUsername());
values.put("usernameClean", user.getUsernameClean());
values.put("email", user.getEmail());
values.put("lastUpdateTime", user.getLastUpdateTime());
values.put("deleteFlag", user.isDeleteFlag() ? 1 : 0);
// updating row
int r = db.update(USER_TABLE, values, "id = ?", new String[] { String.valueOf(user.getId()) });
db.close();
return r == 1;
}
public boolean deleteUser(User user) {
if (user == null || user.getId() < 1) {
return false;
}
SQLiteDatabase db = this.getWritableDatabase();
int r = db.delete(USER_TABLE, "id = ?", new String[] { String.valueOf(user.getId()) });
db.close();
return r == 1;
}
}
| Java |
package edu.gatech.gro.model;
import edu.gatech.gro.utils.Utils;
public abstract class AbstractObject {
protected int id;
protected int creationTime;
protected int lastUpdateTime;
protected boolean deleteFlag;
protected AbstractObject() {
int now = Utils.getCurrentTimestamp();
this.creationTime = now;
this.lastUpdateTime = now;
this.deleteFlag = false;
}
public final int getId() {
return id;
}
public final void setId(int id) {
this.id = id;
}
public final int getCreationTime() {
return creationTime;
}
public final void setCreationTime(int creationTime) {
this.creationTime = creationTime;
}
public final int getLastUpdateTime() {
return lastUpdateTime;
}
public final void setLastUpdateTime(int lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public final boolean isDeleteFlag() {
return deleteFlag;
}
public final void setDeleteFlag(boolean deleteFlag) {
this.deleteFlag = deleteFlag;
}
}
| Java |
package edu.gatech.gro.model;
public class ListItem extends Item {
private int namedListId;
private boolean checked;
private int quantity;
private int currentQuantity;
public ListItem() {
super();
}
public ListItem(Item i) {
super();
setId(i.getId());
setCreationTime(i.getCreationTime());
setLastUpdateTime(i.getLastUpdateTime());
setDeleteFlag(i.isDeleteFlag());
setItemTypeId(i.getItemTypeId());
setGroceryStoreId(i.getGroceryStoreId());
setName(i.getName());
setNameClean(i.getNameClean());
setBarCode(i.getBarCode());
setBarCodeHash(i.getBarCodeHash());
setPrice(i.getPrice());
setCurrency(i.getCurrency());
}
public int getNamedListId() {
return namedListId;
}
public void setNamedListId(int namedListId) {
this.namedListId = namedListId;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getCurrentQuantity() {
return currentQuantity;
}
public void setCurrentQuantity(int currentQuantity) {
this.currentQuantity = currentQuantity;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append(super.toString());
b.append(quantity).append(" ");
return b.toString();
}
}
| Java |
package edu.gatech.gro;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import edu.gatech.gro.http.IResponseAdapter;
import edu.gatech.gro.model.Currency;
import edu.gatech.gro.model.GroceryStore;
import edu.gatech.gro.model.Item;
import edu.gatech.gro.model.ItemType;
import edu.gatech.gro.model.ListGroup;
import edu.gatech.gro.model.ListItem;
import edu.gatech.gro.model.ObjectResponse;
import edu.gatech.gro.utils.Utils;
public class ItemLookUpActivity extends Activity {
/* Tag For Log Cat */
private static final String TAG = "ITEM_LOOKUP_ACTIVITY";
/* Constants */
private static final int GOT_ITEM_TYPES = 0;
private static final int GOT_GROCERY_STORES = 1;
private static final int GOT_SEARCH_RESULTS = 2;
private static final int ITEM_CREATED = 10;
private static final int ITEM_ADDED = 11;
/* Handler */
private final IncomingHandler mHandler = new IncomingHandler();
/* Main Class */
private static GroceryListManagerApplication app;
/* View Variables */
private EditText mItemAdderSearchText;
private ExpandableListView mResults;
private LinearLayout mAdderFieldsLayout;
private Spinner mItemAdderStoreChooser;
private Spinner mItemAdderTypeChooser;
private Spinner mItemAdderCurrencyChooser;
private EditText mItemAdderPriceText;
private Button mItemAdderAddButton;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressSearch;
private ProgressDialog mProgressAddingItem;
/* Others */
private String mCurrentSearch;
private ArrayList<ListGroup> mCurrentResults;
private ArrayList<ListGroup> mOriginalResults;
private ArrayList<ItemType> mCurrentItemTypes;
private ArrayList<GroceryStore> mCurrentGroceryStores;
private int mListId;
private String mListNameClean;
private String mLastFilter;
private SearchItemAdapter mSearchItemAdapter;
private Item mLastCreatedItem;
/**
* onCreate Create the main view of the search screen
*/
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
app = (GroceryListManagerApplication) getApplicationContext();
setContentView(R.layout.search_manager);
mLastFilter = "";
mItemAdderSearchText = (EditText) findViewById(R.id.itemAdderSearchText);
mResults = (ExpandableListView) findViewById(R.id.expandableListSearchResults);
mAdderFieldsLayout = (LinearLayout) findViewById(R.id.itemAdderFieldsLayout);
mItemAdderStoreChooser = (Spinner) findViewById(R.id.itemAdderGroceryChooser);
mItemAdderTypeChooser = (Spinner) findViewById(R.id.itemAdderTypeChooser);
mItemAdderCurrencyChooser = (Spinner) findViewById(R.id.itemAdderCurrencyChooser);
mItemAdderPriceText = (EditText) findViewById(R.id.itemAdderPriceText);
mItemAdderAddButton = (Button) findViewById(R.id.itemAdderAddButton);
Bundle extra = getIntent().getExtras();
mListId = extra.getInt("namedList_id");
mListNameClean = extra.getString("namedList_nameClean");
mAlertDialog = new AlertDialog.Builder(ItemLookUpActivity.this).create();
mAlertDialog.setButton(this.getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mItemAdderAddButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "Save clicked!");
waitForSavingItem();
}
});
mItemAdderSearchText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String name = Utils.cleanName(mItemAdderSearchText.getText().toString());
if (name.length() > 2) {
String s1 = name.substring(0, 3);
String s2 = mLastFilter.length() > 2 ? mLastFilter.substring(0, 3) : "";
if (!s1.equals(s2)) {
mCurrentSearch = name;
waitForSearch();
} else if (mOriginalResults != null && mOriginalResults.size() > 0) {
if (name.startsWith(mLastFilter) && mCurrentResults.size() == 0) {
// Do NOT search
} else {
Log.d(TAG, "Filtering results");
filterResults(name);
}
}
mLastFilter = name;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
ArrayAdapter<String> currencyAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Currency.allSymbols());
mItemAdderCurrencyChooser.setAdapter(currencyAdapter);
waitForItemTypes();
waitForGroceryStores();
}
@Override
public void onResume() {
super.onResume();
}
private void waitForItemTypes() {
// Hidden by default. Progress bar should be useless
app.getAllItemTypes(mItemTypesListener);
}
private void waitForGroceryStores() {
// Hidden by default. Progress bar should be useless
app.getAllGroceryStores(mGroceryStoresListener);
}
private void waitForSearch() {
if (mProgressSearch != null && mProgressSearch.isShowing()) {
return;
}
if (!mCurrentSearch.equals(mLastFilter)) {
mProgressSearch = ProgressDialog.show(ItemLookUpActivity.this, "", this.getString(R.string.progressSearchItem), true, false);
app.searchItem(mCurrentSearch, mSearchListener);
}
}
private void waitForAddingListItem(final ListItem item) {
if (mProgressAddingItem != null && mProgressAddingItem.isShowing()) {
return;
}
mProgressSearch = ProgressDialog.show(ItemLookUpActivity.this, "", this.getString(R.string.progressAddingItem), true, false);
app.addItemToNamedList(mListNameClean, item, mItemAddedListener);
}
private boolean waitForSavingItem() {
if (mProgressAddingItem != null && mProgressAddingItem.isShowing()) {
return false;
}
Item item = new Item();
item.setName(mItemAdderSearchText.getText().toString());
item.setGroceryStoreId(mCurrentGroceryStores.get(mItemAdderStoreChooser.getSelectedItemPosition()).getId());
item.setItemTypeId(mCurrentItemTypes.get(mItemAdderTypeChooser.getSelectedItemPosition()).getId());
item.setBarCode("RANDOM");
item.setPrice(Double.parseDouble(mItemAdderPriceText.getText().toString()));
item.setCurrency(mItemAdderCurrencyChooser.getSelectedItemPosition() + 1);
mProgressAddingItem = ProgressDialog.show(ItemLookUpActivity.this, "", this.getString(R.string.progressItemCreation), true, false);
app.saveItem(item, mItemSavedListener);
return true;
}
private void askForQuantity(final Item item) {
ListItem li = new ListItem();
li.setId(item.getId());
li.setNamedListId(mListId);
li.setQuantity(1);
li.setCurrency(0);
li.setChecked(false);
waitForAddingListItem(li);
}
private void refreshResults() {
if (mCurrentResults != null) {
if (mSearchItemAdapter == null) {
mSearchItemAdapter = new SearchItemAdapter(mCurrentResults);
mResults.setAdapter(mSearchItemAdapter);
} else {
mSearchItemAdapter.setGroups(mCurrentResults);
mSearchItemAdapter.notifyDataSetChanged();
}
if (mCurrentResults.size() > 0) {
mResults.setVisibility(View.VISIBLE);
mAdderFieldsLayout.setVisibility(View.GONE);
} else {
mResults.setVisibility(View.GONE);
mAdderFieldsLayout.setVisibility(View.VISIBLE);
}
}
}
private void filterResults(String nameClean) {
if (!nameClean.equals(mLastFilter)) {
mCurrentResults.clear();
ArrayList<ListGroup> copy = new ArrayList<ListGroup>();
for (ListGroup g : mOriginalResults) {
ArrayList<Item> ni = new ArrayList<Item>();
for (Item i : g.getItems()) {
if (i.getNameClean().startsWith(nameClean)) {
ni.add(i);
}
}
if (ni.size() > 0) {
ListGroup ng = new ListGroup();
ng.setId(g.getId());
ng.setName(g.getName());
ng.setItems(ni);
mCurrentResults.add(ng);
}
}
refreshResults();
}
}
private void refreshItemTypes() {
if (mCurrentItemTypes != null) {
// mItemAdderTypeChooser.setAdapter(new
// ItemTypeAdapter(ItemAdder.this,
// R.layout.spinner_item_type, mCurrentItemTypes));
String[] array = new String[mCurrentItemTypes.size()];
for (int i = 0; i < mCurrentItemTypes.size(); i++) {
array[i] = mCurrentItemTypes.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array);
mItemAdderTypeChooser.setAdapter(adapter);
}
}
private void refreshGroceryStores() {
if (mCurrentGroceryStores != null) {
String[] array = new String[mCurrentGroceryStores.size()];
for (int i = 0; i < mCurrentGroceryStores.size(); i++) {
array[i] = mCurrentGroceryStores.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array);
mItemAdderStoreChooser.setAdapter(adapter);
}
}
/**
* Helper function to dismiss a progress dialog
*
* @param theProgress
* the progress dialog to dismiss
*/
private void dismissProgress(ProgressDialog theProgress) {
if (theProgress != null && theProgress.isShowing()) {
theProgress.dismiss();
}
}
/**
* Handler of incoming messages from the Service
*/
private class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case GOT_ITEM_TYPES:
refreshItemTypes();
break;
case GOT_GROCERY_STORES:
refreshGroceryStores();
break;
case GOT_SEARCH_RESULTS:
refreshResults();
break;
case ITEM_CREATED:
askForQuantity(mLastCreatedItem);
break;
case ITEM_ADDED:
finish();
break;
default:
super.handleMessage(msg);
break;
}
}
}
private final IResponseAdapter mItemTypesListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
if (response.isSuccessful()) {
mCurrentItemTypes = (ArrayList<ItemType>) response.getData();
mHandler.sendEmptyMessage(GOT_ITEM_TYPES);
} else {
displayError(R.string.failRetrieveTypesTitle, response.getErrorsAsString());
}
}
};
private final IResponseAdapter mGroceryStoresListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
if (response.isSuccessful()) {
mCurrentGroceryStores = (ArrayList<GroceryStore>) response.getData();
mHandler.sendEmptyMessage(GOT_GROCERY_STORES);
} else {
displayError(R.string.failRetrieveStoresTitle, response.getErrorsAsString());
}
}
};
private final IResponseAdapter mSearchListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressSearch);
Log.d(TAG, "Search results!");
if (response.isSuccessful()) {
mOriginalResults = (ArrayList<ListGroup>) response.getData();
mCurrentResults = (ArrayList<ListGroup>) mOriginalResults.clone();
} else {
if (mOriginalResults != null) {
mOriginalResults.clear();
mCurrentResults.clear();
} else {
mOriginalResults = new ArrayList<ListGroup>();
mCurrentResults = mOriginalResults;
}
// displayError(R.string.failSearchItemTitle,
// response.getErrorsAsString());
}
mHandler.sendEmptyMessage(GOT_SEARCH_RESULTS);
}
};
private final IResponseAdapter mItemAddedListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressAddingItem);
if (response.isSuccessful()) {
Log.d(TAG, "Item added");
mHandler.sendEmptyMessage(ITEM_ADDED);
} else {
displayError(R.string.failAddItemTitle, response.getErrorsAsString());
}
}
};
private final IResponseAdapter mItemSavedListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressAddingItem);
if (response.isSuccessful()) {
mLastCreatedItem = (Item) response.getData();
mHandler.sendEmptyMessage(ITEM_CREATED);
} else {
displayError(R.string.failCreateItemTitle, response.getErrorsAsString());
}
}
};
private void displayError(final int titleId, final String message) {
mAlertDialog.setTitle(titleId);
mAlertDialog.setMessage(message);
mAlertDialog.show();
}
private class SearchItemAdapter extends BaseExpandableListAdapter {
private ArrayList<ListGroup> mGroups;
public SearchItemAdapter(ArrayList<ListGroup> groups) {
super();
this.mGroups = groups;
}
@Override
public Item getChild(int groupPosition, int childPosition) {
return mGroups.get(groupPosition).getItems().get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return mGroups.get(groupPosition).getItems().get(childPosition).getId();
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.search_type_item, null);
}
final Item li = getChild(groupPosition, childPosition);
if (li != null) {
final TextView textName = (TextView) v.findViewById(R.id.search_type_item_name);
textName.setText(li.getName());
textName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
askForQuantity(li);
}
});
}
return v;
}
@Override
public int getChildrenCount(int groupPosition) {
return mGroups.get(groupPosition).getItems().size();
}
@Override
public ListGroup getGroup(int groupPosition) {
return mGroups.get(groupPosition);
}
@Override
public int getGroupCount() {
return mGroups.size();
}
@Override
public long getGroupId(int groupPosition) {
return mGroups.get(groupPosition).getId();
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.search_type, null);
}
final ListGroup g = getGroup(groupPosition);
if (g != null) {
TextView textName = (TextView) v.findViewById(R.id.search_type_name);
textName.setText(g.getName());
}
ExpandableListView parentGroup = (ExpandableListView) parent;
parentGroup.expandGroup(groupPosition);
return v;
}
@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return false;
}
public void setGroups(ArrayList<ListGroup> groups) {
this.mGroups = groups;
}
}
}
| Java |
package edu.gatech.gro;
public class Options {
private static final Options instance = new Options();
private boolean offline = false;
private Options() {
}
public static Options getInstance() {
return instance;
}
public boolean isOffline() {
return offline;
}
public void setOffline(boolean o) {
this.offline = o;
}
}
| Java |
package edu.gatech.gro;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import edu.gatech.gro.http.IResponseAdapter;
import edu.gatech.gro.model.NamedList;
import edu.gatech.gro.model.ObjectResponse;
public class NamedListDisplayActivity extends Activity {
private static final String TAG = "NAMED_LIST_DISPLAY_ACTIVITY";
private final IncomingHandler mHandler = new IncomingHandler();
private static final int GOT_NAMED_LIST = 0;
private static final int NAMED_LIST_CREATED = 10;
private static final int NAMED_LIST_UPDATED = 11;
private static final int NAMED_LIST_DELETED = 12;
private static GroceryListManagerApplication app;
private Button mAddNamedListButton;
private ListView mNamedLists;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressNamedList;
private ProgressDialog mProgressDelete;
private ArrayList<NamedList> mCurrentNamedLists;
private int mUserId;
private NamedList mCurrentNamedList;
private NamedList mLastNamedListDeleted;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (GroceryListManagerApplication) getApplicationContext();
setContentView(R.layout.named_list_manager);
mAlertDialog = new AlertDialog.Builder(NamedListDisplayActivity.this).create();
mAlertDialog.setButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Bundle extra = getIntent().getExtras();
mUserId = extra.getInt("userId");
mAddNamedListButton = (Button) findViewById(R.id.addNamedListButton);
mNamedLists = (ListView) findViewById(R.id.namedLists);
mAddNamedListButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "mAddNamedListButton clicked");
mCurrentNamedList = null;
displayNamedListAdderPanel();
}
});
}
@Override
public void onResume() {
super.onResume();
waitForNamedLists();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case NAMED_LIST_UPDATED:
if (resultCode == RESULT_OK) {
Bundle b = data.getExtras();
updateNamedListAfterEdit(b.getString("name"));
}
break;
}
}
private void updateNamedListAfterEdit(String name) {
mCurrentNamedList.setName(name);
mNamedListAdapter.notifyDataSetChanged();
}
private void waitForNamedLists() {
if (mProgressNamedList != null && mProgressNamedList.isShowing()) {
return;
}
mProgressNamedList = ProgressDialog.show(NamedListDisplayActivity.this, "", // this.getString(R.string.pleaseWait),
this.getString(R.string.progressNamedList), true, false);
app.getAllNamedList(mUserId, mNamedListsListener);
}
private void waitForDeleteNamedList() {
if (mProgressDelete != null && mProgressDelete.isShowing()) {
return;
}
mProgressDelete = ProgressDialog.show(NamedListDisplayActivity.this, "", // this.getString(R.string.pleaseWait),
this.getString(R.string.progressUserDelete), true, false);
mLastNamedListDeleted = mCurrentNamedList;
app.deleteNamedList(mCurrentNamedList, mDeleteListener);
}
private void refreshNamedLists() {
if (mCurrentNamedLists != null && mCurrentNamedLists.size() > 0) {
mNamedListAdapter = new NamedListAdapter(NamedListDisplayActivity.this, R.layout.named_list_item, mCurrentNamedLists);
mNamedLists.setAdapter(mNamedListAdapter);
}
}
private void displayNamedListAdderPanel() {
Intent i = new Intent(this, NamedListEditActivity.class);
i.putExtra("hasNamedList", mCurrentNamedList != null);
i.putExtra("userId", mUserId);
if (mCurrentNamedList == null) {
startActivityForResult(i, NAMED_LIST_CREATED);
} else {
i.putExtra("listId", mCurrentNamedList.getId());
i.putExtra("listName", mCurrentNamedList.getName());
startActivityForResult(i, NAMED_LIST_UPDATED);
}
}
private void displayItems(NamedList nl) {
Intent i = new Intent(this, ItemDisplayActivity.class);
i.putExtra("userId", mUserId);
i.putExtra("namedListId", nl.getId());
i.putExtra("namedListName", nl.getName());
i.putExtra("namedListNameClean", nl.getNameClean());
startActivity(i);
}
private void editNamedList(NamedList list) {
mCurrentNamedList = list;
displayNamedListAdderPanel();
}
private void deleteNamedList(NamedList list) {
mCurrentNamedList = list;
waitForDeleteNamedList();
}
private void promptAvailableActions(final NamedList list) {
String[] items = new String[2];
items[0] = this.getString(R.string.edit);
items[1] = this.getString(R.string.delete);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.whattodo);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0: // Edit
editNamedList(list);
break;
case 1: // Delete
deleteNamedList(list);
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
private final IResponseAdapter mNamedListsListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse obj) {
dismissProgress(mProgressNamedList);
if (obj.isSuccessful()) {
// Save the current list of users
mCurrentNamedLists = (ArrayList<NamedList>) obj.getData();
Log.d(TAG, "Named lists received!");
mHandler.sendEmptyMessage(GOT_NAMED_LIST);
} else {
displayError(R.string.failRetrieveListsTitle, obj.getErrorsAsString());
}
}
};
private final IResponseAdapter mDeleteListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressDelete);
if (response.isSuccessful()) {
mHandler.sendEmptyMessage(NAMED_LIST_DELETED);
} else {
mLastNamedListDeleted = null;
}
}
};
/**
* Helper function to dismiss a progress dialog
*
* @param theProgress
* the progress dialog to dismiss
*/
private void dismissProgress(ProgressDialog theProgress) {
if (theProgress != null && theProgress.isShowing()) {
theProgress.dismiss();
}
}
/**
* Handler of incoming messages from the Service
*/
private class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case GOT_NAMED_LIST:
refreshNamedLists();
break;
case NAMED_LIST_DELETED:
if (mLastNamedListDeleted != null) {
mCurrentNamedLists.remove(mLastNamedListDeleted);
mNamedListAdapter.notifyDataSetChanged();
mLastNamedListDeleted = null;
mCurrentNamedList = null;
}
break;
default:
super.handleMessage(msg);
break;
}
}
}
private void displayError(final int titleId, final String message) {
mAlertDialog.setTitle(titleId);
mAlertDialog.setMessage(message);
mAlertDialog.show();
}
private NamedListAdapter mNamedListAdapter;
private class NamedListAdapter extends ArrayAdapter<NamedList> {
private final ArrayList<NamedList> mLists;
public NamedListAdapter(Context context, int textViewResourceId, ArrayList<NamedList> items) {
super(context, textViewResourceId, items);
this.mLists = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.named_list_item, null);
}
final NamedList nl = mLists.get(position);
if (nl != null) {
TextView tt = (TextView) v.findViewById(R.id.named_list_item_line1);
TextView bt = (TextView) v.findViewById(R.id.named_list_item_line2);
if (tt != null) {
tt.setText(nl.getName());
}
if (bt != null) {
// bt.setText(nl.getEmail());
}
tt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "named list #" + nl.getId() + " clicked!");
displayItems(nl);
}
});
tt.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Log.d(TAG, "Long click on list #" + nl.getId());
promptAvailableActions(nl);
return false;
}
});
}
return v;
}
}
}
| Java |
package edu.gatech.gro.http;
import edu.gatech.gro.model.ObjectResponse;
public interface IResponseAdapter {
public void onResponse(ObjectResponse response);
}
| Java |
package edu.gatech.gro.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import android.util.Log;
import edu.gatech.gro.model.ObjectResponse;
import edu.gatech.gro.model.parser.JsonHandler;
public class CommonResponseHandler implements ResponseHandler<ObjectResponse> {
private static final String TAG = "COMMON_RESPONSE_HANDLER";
private final JsonHandler mJsonHandler;
public CommonResponseHandler(JsonHandler jsonHandler) {
this.mJsonHandler = jsonHandler;
}
@Override
public ObjectResponse handleResponse(HttpResponse r) {
StringBuilder result = new StringBuilder();
try {
// First, we retrieve the xml string from the server
BufferedReader br = new BufferedReader(new InputStreamReader(r.getEntity().getContent()));
String line;
while ((line = br.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
mJsonHandler.parse(result.toString());
return mJsonHandler.getResponse();
}
}
| Java |
package edu.gatech.gro.http;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.net.http.AndroidHttpClient;
import android.os.Looper;
import android.util.Log;
import edu.gatech.gro.model.ObjectResponse;
import edu.gatech.gro.model.parser.JsonHandler;
public class HttpRequest implements Runnable {
private static final String TAG = "HTTP_REQUEST";
private static final String USER_AGENT = "GroceryList211";
public static final int GET = 0;
public static final int POST = 1;
public static final int PUT = 2;
public static final int DELETE = 3;
private static List<NameValuePair> mCookies = new ArrayList<NameValuePair>();
private final int mType;
private final String mUrl;
private final HashMap<String, String> mGetParameters;
private final CommonResponseHandler mJsonHandler;
private String mHttpUrl;
private HttpEntity mContentEntity;
private boolean sendJson = false;
private IResponseAdapter mListener;
public HttpRequest(int reqType, String url, JsonHandler jsonHandler) {
mType = reqType;
mUrl = url;
mGetParameters = new HashMap<String, String>();
mJsonHandler = new CommonResponseHandler(jsonHandler);
}
public void addGetParameter(String name, String value) {
mGetParameters.put(name, value);
}
public void setContent(JSONObject json) {
mContentEntity = null;
sendJson = false;
try {
mContentEntity = new StringEntity(json.toString());
sendJson = true;
} catch (UnsupportedEncodingException e) {
Log.d(TAG, e.getMessage());
}
}
public void setContent(JSONArray json) {
mContentEntity = null;
sendJson = false;
try {
mContentEntity = new StringEntity(json.toString());
sendJson = true;
} catch (UnsupportedEncodingException e) {
Log.d(TAG, e.getMessage());
}
}
public void setContent(List<NameValuePair> params) {
mContentEntity = null;
sendJson = false;
try {
if (params != null) {
mContentEntity = new UrlEncodedFormEntity(params);
}
} catch (UnsupportedEncodingException e) {
Log.d(TAG, e.getMessage());
}
}
public void setResponseListener(IResponseAdapter listener) {
mListener = listener;
}
@Override
public void run() {
prepareUrl();
HttpUriRequest http = null;
switch (mType) {
case POST:
http = post();
break;
case PUT:
http = put();
break;
case DELETE:
http = delete();
break;
case GET:
default:
http = get();
break;
}
if (http != null) {
AndroidHttpClient httpclient = null;
try {
httpclient = AndroidHttpClient.newInstance(USER_AGENT);
setHeaders(http);
http.setHeader("Accept", "application/json");
if (sendJson) {
http.setHeader("Content-type", "application/json");
}
HttpResponse response = httpclient.execute(http);
ObjectResponse res = mJsonHandler.handleResponse(response);
saveCookies(response);
if (mListener != null) {
Looper.prepare();
mListener.onResponse(res);
}
} catch (Exception e) {
String msg = e != null && e.getMessage() != null ? e.getMessage() : "FATAL ERROR!";
Log.e(TAG, msg);
}
finally {
if (httpclient != null) {
httpclient.close();
}
}
}
}
private void prepareUrl() {
mHttpUrl = mUrl;
if (!mHttpUrl.contains("?") && mGetParameters.size() > 0) {
mHttpUrl += "?";
}
for (String key : mGetParameters.keySet()) {
mHttpUrl += key + "=" + mGetParameters.get(key);
}
}
private HttpUriRequest get() {
return new HttpGet(mUrl);
}
private HttpUriRequest post() {
HttpPost http = new HttpPost(mHttpUrl);
if (mContentEntity != null) {
http.setEntity(mContentEntity);
}
return http;
}
private HttpUriRequest put() {
HttpPut http = new HttpPut(mHttpUrl);
if (mContentEntity != null) {
http.setEntity(mContentEntity);
}
return http;
}
private HttpUriRequest delete() {
return new HttpDelete(mHttpUrl);
}
private synchronized void saveCookies(HttpResponse r) {
Header[] headers = r.getHeaders("Set-Cookie");
for (Header h : headers) {
String[] cc = h.getValue().split(";");
for (String c : cc) {
String[] nv = c.split("=");
if (nv.length == 2) {
updateCookie(nv[0], nv[1]);
}
}
}
}
private void updateCookie(String name, String value) {
NameValuePair co = getCookie(name);
if (co != null) {
removeCookie(name);
}
mCookies.add(new BasicNameValuePair(name, value));
}
private boolean removeCookie(String name) {
String n = name.toLowerCase();
for (int i = 0; i < mCookies.size(); i++) {
if (mCookies.get(i).getName().toLowerCase().equals(n)) {
mCookies.remove(i);
return true;
}
}
return false;
}
private NameValuePair getCookie(String name) {
String n = name.toLowerCase();
for (NameValuePair c : mCookies)
if (c.getName().toLowerCase().equals(n))
return c;
return null;
}
private synchronized void setHeaders(org.apache.http.HttpRequest r) {
StringBuilder sb = new StringBuilder();
for (NameValuePair c : mCookies) {
if (sb.length() > 0)
sb.append("; ");
sb.append(c.getName() + "=" + c.getValue());
}
if (sb.length() > 0) {
// Log.d(TAG, "Cookie:" + sb.toString());
r.addHeader("Cookie", sb.toString());
}
}
}
| Java |
package edu.gatech.gro;
import java.util.regex.Pattern;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import edu.gatech.gro.http.IResponseAdapter;
import edu.gatech.gro.model.NamedList;
import edu.gatech.gro.model.ObjectResponse;
public class NamedListEditActivity extends Activity {
private static final String TAG = "NAMED_LIST_EDIT_ACTIVITY";
private static final int ERROR_USERNAME_RULE = 0;
// private static final int ERROR_ONLINE = 1;
private static GroceryListManagerApplication app;
private ProgressDialog mProgressCreation;
private AlertDialog mAlertDialog;
private Button mCreateNamedListButton;
private EditText mName;
private int mUserId;
private NamedList mCurrentNamedList;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
app = (GroceryListManagerApplication) getApplicationContext();
setContentView(R.layout.named_list_adder);
mAlertDialog = new AlertDialog.Builder(NamedListEditActivity.this).create();
mAlertDialog.setButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mCreateNamedListButton = (Button) findViewById(R.id.namedListAdderCreateNamedListButton);
mName = (EditText) findViewById(R.id.namedListAdderNamedListText);
mCurrentNamedList = null;
Bundle extra = getIntent().getExtras();
mUserId = extra.getInt("userId");
if (extra.getBoolean("hasNamedList")) {
mCurrentNamedList = new NamedList();
mCurrentNamedList.setId(extra.getInt("listId"));
mCurrentNamedList.setName(extra.getString("listName"));
mName.setText(mCurrentNamedList.getName());
mCreateNamedListButton.setText(R.string.namedListAdderUpdateNamedListButtonLabel);
}
mCreateNamedListButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "Create list button clicked!");
if (mCurrentNamedList == null) {
saveList();
} else {
updateList();
}
}
});
}
private boolean saveList() {
if (mProgressCreation != null && mProgressCreation.isShowing()) {
return false;
}
String name = mName.getText().toString();
if (!isName(name)) {
return displayError(ERROR_USERNAME_RULE);
}
mCurrentNamedList = new NamedList();
mCurrentNamedList.setName(name);
mCurrentNamedList.setUserId(mUserId);
mProgressCreation = ProgressDialog.show(NamedListEditActivity.this, "", // this.getString(R.string.pleaseWait),
this.getString(R.string.progressNamedListCreation), true, false);
app.saveNamedList(mCurrentNamedList, mNamedListCreatedListener);
return true;
}
private boolean updateList() {
if (mProgressCreation != null && mProgressCreation.isShowing()) {
return false;
}
String name = mName.getText().toString();
if (!isName(name)) {
return displayError(ERROR_USERNAME_RULE);
}
mCurrentNamedList.setName(name);
mCurrentNamedList.setUserId(mUserId);
mProgressCreation = ProgressDialog.show(NamedListEditActivity.this, "", // this.getString(R.string.pleaseWait),
this.getString(R.string.progressNamedListUpdate), true, false);
app.updateNamedList(mCurrentNamedList, mNamedListUpdatedListener);
return true;
}
private boolean displayError(int errorCode) {
switch (errorCode) {
case ERROR_USERNAME_RULE:
displayError(R.string.errorNameRuleTitle, R.string.errorNameRuleMessage);
break;
}
return false;
}
private boolean isName(String name) {
String pattern = "^([a-zâêîôûŷäëïöüÿéèàçùA-ZÂÊÎÔÛŶÄËÏÖÜŸÉÈÀÇÙ0-9 '\\-]+)$";
return Pattern.compile(pattern).matcher(name).find();
}
/**
* Helper function to dismiss a progress dialog
*
* @param theProgress
* the progress dialog to dismiss
*/
private void dismissProgress(ProgressDialog theProgress) {
if (theProgress != null && theProgress.isShowing()) {
theProgress.dismiss();
}
}
private final IResponseAdapter mNamedListCreatedListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressCreation);
if (response.isSuccessful()) {
finish();
} else {
displayError(R.string.failCreateListTitle, response.getErrorsAsString());
}
}
};
private final IResponseAdapter mNamedListUpdatedListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressCreation);
if (response.isSuccessful()) {
Intent b = new Intent();
b.putExtra("id", mCurrentNamedList.getId());
b.putExtra("name", mCurrentNamedList.getName());
setResult(RESULT_OK, b);
finish();
} else {
displayError(R.string.failUpdateListTitle, response.getErrorsAsString());
}
}
};
private void displayError(final int titleId, final int messageId) {
mAlertDialog.setTitle(titleId);
mAlertDialog.setMessage(this.getString(messageId));
mAlertDialog.show();
}
private void displayError(final int titleId, final String message) {
mAlertDialog.setTitle(titleId);
mAlertDialog.setMessage(message);
mAlertDialog.show();
}
}
| Java |
package edu.gatech.gro;
import java.util.regex.Pattern;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import edu.gatech.gro.http.IResponseAdapter;
import edu.gatech.gro.model.ObjectResponse;
import edu.gatech.gro.model.User;
import edu.gatech.gro.utils.Utils;
public class UserEditActivity extends Activity {
private static final String TAG = "USER_EDIT_ACTIVITY";
private static final int ERROR_PASSWORD_DIFFERENT = 0;
private static final int ERROR_USERNAME_RULE = 1;
private static final int ERROR_PASSWORD_RULE = 2;
// private static final int ERROR_ONLINE = 3;
private static GroceryListManagerApplication app;
private ProgressDialog mProgressCreation;
private AlertDialog mAlertDialog;
private Button mCreateUserButton;
private EditText mUsername;
private EditText mEmail;
private EditText mPassword1;
private EditText mPassword2;
private User mCurrentUser;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
app = (GroceryListManagerApplication) getApplicationContext();
setContentView(R.layout.user_adder);
mAlertDialog = new AlertDialog.Builder(UserEditActivity.this).create();
mAlertDialog.setButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mCreateUserButton = (Button) findViewById(R.id.userAdderCreateUserButton);
mUsername = (EditText) findViewById(R.id.userAdderUsernameText);
mEmail = (EditText) findViewById(R.id.userAdderEmailText);
mPassword1 = (EditText) findViewById(R.id.userAdderPassword1Text);
mPassword2 = (EditText) findViewById(R.id.userAdderPassword2Text);
mCurrentUser = null;
Bundle extra = getIntent().getExtras();
if (extra.getBoolean("hasUser")) {
Log.d(TAG, "Has user");
mCurrentUser = new User();
mCurrentUser.setId(extra.getInt("id"));
mCurrentUser.setUsername(extra.getString("username"));
mCurrentUser.setEmail(extra.getString("email"));
mUsername.setText(mCurrentUser.getUsername());
mEmail.setText(mCurrentUser.getEmail());
mCreateUserButton.setText(R.string.userAdderUpdateUserButtonLabel);
mPassword1.setVisibility(EditText.GONE);
mPassword2.setVisibility(EditText.GONE);
((TextView) findViewById(R.id.userAdderPassword1)).setVisibility(TextView.GONE);
((TextView) findViewById(R.id.userAdderPassword2)).setVisibility(TextView.GONE);
}
mCreateUserButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "Create user button clicked!");
if (mCurrentUser == null) {
saveUser();
} else {
updateUser();
}
}
});
}
private boolean saveUser() {
if (mProgressCreation != null && mProgressCreation.isShowing()) {
return false;
}
String username = mUsername.getText().toString();
String email = mEmail.getText().toString();
String password1 = mPassword1.getText().toString();
String password2 = mPassword2.getText().toString();
if (!isUsername(username)) {
return displayError(ERROR_USERNAME_RULE);
}
if (!isPassword(password1)) {
return displayError(ERROR_PASSWORD_RULE);
}
if (!password1.equals(password2)) {
return displayError(ERROR_PASSWORD_DIFFERENT);
}
mCurrentUser = new User();
mCurrentUser.setId(0);
mCurrentUser.setUsername(username);
mCurrentUser.setEmail(email);
mCurrentUser.setPassword(Utils.hash(password1));
mProgressCreation = ProgressDialog.show(UserEditActivity.this, "", this.getString(R.string.progressUserCreation), true, false);
app.saveUser(mCurrentUser, mUserRegisteredListener);
return true;
}
private boolean updateUser() {
if (mProgressCreation != null && mProgressCreation.isShowing()) {
return false;
}
String username = mUsername.getText().toString();
String email = mEmail.getText().toString();
if (!isUsername(username)) {
return displayError(ERROR_USERNAME_RULE);
}
mCurrentUser.setUsername(username);
mCurrentUser.setEmail(email);
mProgressCreation = ProgressDialog.show(UserEditActivity.this, "", this.getString(R.string.progressUserUpdate), true, false);
app.updateUser(mCurrentUser, mUserUpdatedListener);
return true;
}
private boolean displayError(int errorCode) {
switch (errorCode) {
case ERROR_PASSWORD_DIFFERENT:
displayError(R.string.errorPasswordDifferentTitle, R.string.errorPasswordDifferentMessage);
break;
case ERROR_USERNAME_RULE:
displayError(R.string.errorUsernameRuleTitle, R.string.errorUsernameRuleMessage);
break;
case ERROR_PASSWORD_RULE:
displayError(R.string.errorPasswordRuleTitle, R.string.errorPasswordRuleMessage);
break;
}
return false;
}
private boolean isUsername(String username) {
String pattern = "^([a-zâêîôûŷäëïöüÿéèàçùA-ZÂÊÎÔÛŶÄËÏÖÜŸÉÈÀÇÙ0-9 '\\-]+)$";
return Pattern.compile(pattern).matcher(username).find();
}
private boolean isPassword(String password) {
String regMin = "a-zâêîôûŷäëïöüÿéèàçùæœ";
String regMaj = "A-ZÂÊÎÔÛŶÄËÏÖÜŸÉÈÀÇÙÆŒ";
String regNum = "0-9";
String regSym = "²&~\"'\\{\\(\\[\\-\\|`_\\^@\\)\\]=\\}\\*\\$£%<>,;:!§\\/\\.\\?";
String patternFull = "^([" + regMin + regMaj + regNum + regSym + "]{6,})$";
String patternLetter = "([" + regMin + "|" + regMaj + "]+)";
String patternNum = "([" + regNum + "]+)";
String patternSym = "([" + regSym + "]+)";
password = password.trim();
if (password.length() < 6) {
return false;
}
boolean b1 = Pattern.compile(patternFull).matcher(password).find();
boolean b2 = Pattern.compile(patternLetter).matcher(password).find();
boolean b3 = Pattern.compile(patternNum).matcher(password).find();
boolean b4 = Pattern.compile(patternSym).matcher(password).find();
return b1 && b2 && b3 && b4;
}
/**
* Helper function to dismiss a progress dialog
*
* @param theProgress
* the progress dialog to dismiss
*/
private void dismissProgress(ProgressDialog theProgress) {
if (theProgress != null && theProgress.isShowing()) {
theProgress.dismiss();
}
}
private final IResponseAdapter mUserRegisteredListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressCreation);
if (response.isSuccessful()) {
finish();
} else {
displayError(R.string.failCreateUserTitle, response.getErrorsAsString());
}
}
};
private final IResponseAdapter mUserUpdatedListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressCreation);
if (response.isSuccessful()) {
Intent b = new Intent();
b.putExtra("id", mCurrentUser.getId());
b.putExtra("username", mCurrentUser.getUsername());
b.putExtra("email", mCurrentUser.getEmail());
setResult(RESULT_OK, b);
finish();
} else {
displayError(R.string.failUpdateUserTitle, response.getErrorsAsString());
}
}
};
private void displayError(final int titleId, final int messageId) {
mAlertDialog.setTitle(titleId);
mAlertDialog.setMessage(this.getString(messageId));
mAlertDialog.show();
}
private void displayError(final int titleId, final String message) {
mAlertDialog.setTitle(titleId);
mAlertDialog.setMessage(message);
mAlertDialog.show();
}
}
| Java |
package edu.gatech.gro;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import edu.gatech.gro.http.IResponseAdapter;
import edu.gatech.gro.model.ObjectResponse;
import edu.gatech.gro.model.User;
public class UserDisplayActivity extends Activity {
private static final String TAG = "USER_EDIT_ACTIVITY";
private final IncomingHandler mHandler = new IncomingHandler();
private static final int GOT_USERS = 0;
private static final int GOT_LOGGED = 1;
private static final int FAILED_TO_LOG = 2;
private static final int USER_CREATED = 10;
private static final int USER_UPDATED = 11;
private static final int USER_DELETED = 12;
private static final int AFTER_LOGIN_LIST = 20;
private static final int AFTER_LOGIN_EDIT = 21;
private static final int AFTER_LOGIN_DELETE = 22;
private static GroceryListManagerApplication app;
private Button mAddUserButton;
private ListView mUserList;
private UserAdapter mUserAdapter;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressUser;
private ProgressDialog mProgressDelete;
private ProgressDialog mProgressLogin;
private ProgressDialog mProgressSynchronization;
private int mDoAfterLogin = 0;
private User mCurrentUser;
private boolean mCurrentPasswordOk = false;
private ArrayList<User> mCurrentUsers;
private User mLastUserDeleted;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (GroceryListManagerApplication) getApplicationContext();
setContentView(R.layout.user_manager);
mAlertDialog = new AlertDialog.Builder(UserDisplayActivity.this).create();
mAlertDialog.setButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mAddUserButton = (Button) findViewById(R.id.addUserButton);
mUserList = (ListView) findViewById(R.id.userList);
mAddUserButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "mAddUserButton clicked");
mCurrentUser = null;
displayUserAdderPanel();
}
});
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "Resume");
waitForSynchronization();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case USER_UPDATED:
if (resultCode == RESULT_OK) {
Bundle b = data.getExtras();
updateUserAfterEdit(b.getString("username"), b.getString("email"));
}
break;
}
}
private void updateUserAfterEdit(String username, String email) {
mCurrentUser.setUsername(username);
mCurrentUser.setEmail(email);
mUserAdapter.notifyDataSetChanged();
}
private void waitForSynchronization() {
if (mProgressSynchronization == null || !mProgressSynchronization.isShowing()) {
mProgressSynchronization = ProgressDialog.show(UserDisplayActivity.this, "", this.getString(R.string.progressSynchronization), true, false);
app.synchronize(mSynchronizationListener);
}
}
private void waitForUserList() {
if (mProgressUser == null || !mProgressUser.isShowing()) {
mProgressUser = ProgressDialog.show(UserDisplayActivity.this, "", this.getString(R.string.progressUserList), true, false);
app.getAllUsers(mUsersListener);
}
}
private void waitForLogin(String username, String password) {
if (mProgressLogin == null || !mProgressLogin.isShowing()) {
mProgressLogin = ProgressDialog.show(UserDisplayActivity.this, "", this.getString(R.string.progressLogin), true, false);
app.login(username, password, mLoginListener);
}
}
private void waitForDelete() {
if (mProgressDelete == null || !mProgressDelete.isShowing()) {
mLastUserDeleted = mCurrentUser;
mProgressDelete = ProgressDialog.show(UserDisplayActivity.this, "", this.getString(R.string.progressUserDelete), true, false);
app.deleteUser(mCurrentUser, mDeleteListener);
}
}
private void refreshUserList() {
if (mCurrentUsers != null && mCurrentUsers.size() > 0) {
mUserAdapter = new UserAdapter(UserDisplayActivity.this, R.layout.user_list_item, mCurrentUsers);
mUserList.setAdapter(mUserAdapter);
}
}
private void displayUserAdderPanel() {
Intent i = new Intent(this, UserEditActivity.class);
i.putExtra("hasUser", mCurrentUser != null);
if (mCurrentUser == null) {
startActivityForResult(i, USER_CREATED);
} else {
i.putExtra("userId", mCurrentUser.getId());
i.putExtra("username", mCurrentUser.getUsername());
i.putExtra("email", mCurrentUser.getEmail());
startActivityForResult(i, USER_UPDATED);
}
}
private void displayNamedLists(final User user) {
if (loginRequired(user)) {
mDoAfterLogin = AFTER_LOGIN_LIST;
promptLogin(user);
} else if (mCurrentPasswordOk) {
mCurrentUser = user;
Intent i = new Intent(this, NamedListDisplayActivity.class);
i.putExtra("userId", mCurrentUser.getId());
startActivity(i);
}
}
private void editUser(final User user) {
if (loginRequired(user)) {
mDoAfterLogin = AFTER_LOGIN_EDIT;
promptLogin(user);
} else if (mCurrentPasswordOk) {
mCurrentUser = user;
displayUserAdderPanel();
}
}
private void deleteUser(final User user) {
if (loginRequired(user)) {
mDoAfterLogin = AFTER_LOGIN_DELETE;
promptLogin(user);
} else if (mCurrentPasswordOk) {
mCurrentUser = user;
waitForDelete();
}
}
private boolean loginRequired(final User user) {
return mCurrentUser == null || user.getId() != mCurrentUser.getId() || !mCurrentPasswordOk;
}
private void promptLogin(final User user) {
mCurrentUser = null;
mCurrentPasswordOk = false;
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.login_password, null);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Login");
alert.setMessage(R.string.loginEnterPasswordLabel);
alert.setView(textEntryView);
alert.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
EditText mPassword = (EditText) textEntryView.findViewById(R.id.loginPasswordText);
String password = mPassword.getText().toString();
Log.d(TAG, "Password: " + password);
waitForLogin(user.getUsername(), password);
}
});
alert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alert.show();
}
private void promptAvailableActions(final User user) {
String[] items = new String[2];
items[0] = this.getString(R.string.edit);
items[1] = this.getString(R.string.delete);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.whattodo);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0: // Edit
editUser(user);
break;
case 1: // Delete
deleteUser(user);
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
/**
* Helper function to dismiss a progress dialog
*
* @param theProgress
* the progress dialog to dismiss
*/
private void dismissProgress(ProgressDialog theProgress) {
if (theProgress != null && theProgress.isShowing()) {
theProgress.dismiss();
}
}
private User getUser(int id) {
for (User u : mCurrentUsers) {
if (u.getId() == id) {
return u;
}
}
return null;
}
private final IResponseAdapter mSynchronizationListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
Log.d(TAG, "Synchronization completed.");
dismissProgress(mProgressSynchronization);
waitForUserList();
}
};
private final IResponseAdapter mUsersListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressUser);
if (response.isSuccessful()) {
// Save the current list of users
mCurrentUsers = (ArrayList<User>) response.getData();
Log.d(TAG, "Users received!");
// Send a message to the activity to update the view (on the UI thread)
mHandler.sendEmptyMessage(GOT_USERS);
} else {
displayError(R.string.failRetrieveUsersTitle, response.getErrorsAsString());
}
}
};
private final IResponseAdapter mLoginListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressLogin);
mCurrentPasswordOk = response.isSuccessful();
if (response.isSuccessful()) {
User cUser = (User) response.getData();
mCurrentUser = getUser(cUser.getId());
mCurrentUser.setUsername(cUser.getUsername());
mCurrentUser.setEmail(cUser.getEmail());
mHandler.sendEmptyMessage(GOT_LOGGED);
} else {
mHandler.sendEmptyMessage(FAILED_TO_LOG);
}
}
};
private final IResponseAdapter mDeleteListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressDelete);
if (response.isSuccessful()) {
mHandler.sendEmptyMessage(USER_DELETED);
} else {
mLastUserDeleted = null;
}
}
};
/**
* Handler of incoming messages from the Service
*/
private class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case GOT_USERS:
refreshUserList();
break;
case GOT_LOGGED:
switch (mDoAfterLogin) {
case AFTER_LOGIN_DELETE:
deleteUser(mCurrentUser);
break;
case AFTER_LOGIN_EDIT:
editUser(mCurrentUser);
break;
case AFTER_LOGIN_LIST:
displayNamedLists(mCurrentUser);
break;
}
break;
case FAILED_TO_LOG:
userFailedLog();
break;
case USER_DELETED:
userDeleted();
break;
default:
super.handleMessage(msg);
break;
}
}
}
private void userFailedLog() {
displayError(R.string.errorLoginTitle, R.string.errorLoginMessage);
}
private void userDeleted() {
if (mLastUserDeleted != null) {
mCurrentUsers.remove(mLastUserDeleted);
mUserAdapter.notifyDataSetChanged();
mLastUserDeleted = null;
mCurrentUser = null;
}
}
private void displayError(final int titleId, final int messageId) {
mAlertDialog.setTitle(titleId);
mAlertDialog.setMessage(this.getString(messageId));
mAlertDialog.show();
}
private void displayError(final int titleId, final String message) {
mAlertDialog.setTitle(titleId);
mAlertDialog.setMessage(message);
mAlertDialog.show();
}
private class UserAdapter extends ArrayAdapter<User> {
private static final String TAG = "USER_ADAPTER";
private final ArrayList<User> mItems;
public UserAdapter(Context context, int textViewResourceId, ArrayList<User> items) {
super(context, textViewResourceId, items);
this.mItems = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.user_list_item, null);
}
final User u = mItems.get(position);
if (u != null) {
TextView tt = (TextView) v.findViewById(R.id.user_item_line1);
TextView bt = (TextView) v.findViewById(R.id.user_item_line2);
if (tt != null) {
tt.setText(u.getUsername());
}
if (bt != null) {
// bt.setText(u.getEmail());
}
tt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "user #" + u.getId() + " clicked!");
displayNamedLists(u);
}
});
tt.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Log.d(TAG, "Long click on user #" + u.getId());
promptAvailableActions(u);
return true;
}
});
}
return v;
}
}
}
| Java |
package edu.gatech.gro;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import android.app.Application;
import edu.gatech.gro.http.HttpRequest;
import edu.gatech.gro.http.IResponseAdapter;
import edu.gatech.gro.model.GroceryStore;
import edu.gatech.gro.model.Item;
import edu.gatech.gro.model.ItemType;
import edu.gatech.gro.model.ListGroup;
import edu.gatech.gro.model.ListItem;
import edu.gatech.gro.model.NamedList;
import edu.gatech.gro.model.ObjectResponse;
import edu.gatech.gro.model.User;
import edu.gatech.gro.model.dao.GroceryStoreDao;
import edu.gatech.gro.model.dao.ItemDao;
import edu.gatech.gro.model.dao.ItemTypeDao;
import edu.gatech.gro.model.dao.ListItemDao;
import edu.gatech.gro.model.dao.NamedListDao;
import edu.gatech.gro.model.dao.UserDao;
import edu.gatech.gro.model.parser.GroceryStoreJsonHandler;
import edu.gatech.gro.model.parser.ItemJsonHandler;
import edu.gatech.gro.model.parser.ItemTypeJsonHandler;
import edu.gatech.gro.model.parser.JsonHandler;
import edu.gatech.gro.model.parser.ListGroupItemJsonHandler;
import edu.gatech.gro.model.parser.NamedListJsonHandler;
import edu.gatech.gro.model.parser.UserJsonHandler;
import edu.gatech.gro.utils.JSONHelper;
import edu.gatech.gro.utils.Utils;
public class GroceryListManagerApplication extends Application {
private static final String TAG = "GROCERY_LIST_MANAGER_APPLICATION";
private static final String ROOT_URL = "http://www.fabienrenaud.com/gro2/";
private static final String REQ_LOGIN = ROOT_URL + "login.php";
// private static final String REQ_LOGOUT = ROOT_URL + "logout.php";
private static final String REST_URL = ROOT_URL + "rest/";
private static final String REQ_USER = REST_URL + "user";
private static final String REST_SEARCH = REST_URL + "search";
private static final String REST_ITEM = REST_URL + "item";
private static final String REST_GROCERY_STORES = REST_URL + "grocery";
private static final String REQ_NAMED_LIST = REQ_USER + "/list";
private static final String REQ_SEARCH_ITEM = REST_SEARCH + "/item";
private static final String REQ_ITEM_TYPES = REST_ITEM + "/type";
private UserDao userDao;
private NamedListDao namedListDao;
private ListItemDao listItemDao;
private GroceryStoreDao groceryStoreDao;
private ItemTypeDao itemTypeDao;
private ItemDao itemDao;
public GroceryListManagerApplication() {
if (Options.getInstance().isOffline()) {
userDao = new UserDao(this);
namedListDao = new NamedListDao(this);
listItemDao = new ListItemDao(this);
itemDao = new ItemDao(this);
groceryStoreDao = new GroceryStoreDao(this);
itemTypeDao = new ItemTypeDao(this);
}
}
public ArrayList<User> getAllUsers() {
if (userDao != null) {
return userDao.getAllUsers();
}
return null;
}
public void getAllUsers(IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(getAllUsers(), responseAdapter);
} else {
HttpRequest r = new HttpRequest(HttpRequest.GET, REQ_USER, new UserJsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
}
public ArrayList<NamedList> getAllNamedList(final int userId) {
if (userId > 0 && namedListDao != null) {
return namedListDao.getAllNamedLists(userId);
}
return null;
}
public void getAllNamedList(final int userId, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(getAllNamedList(userId), responseAdapter);
} else {
HttpRequest r = new HttpRequest(HttpRequest.GET, REQ_NAMED_LIST, new NamedListJsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
}
public ArrayList<ItemType> getAllItemTypes() {
if (itemTypeDao != null) {
return itemTypeDao.getAllItemTypes();
}
return null;
}
public void getAllItemTypes(IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(getAllItemTypes(), responseAdapter);
} else {
HttpRequest r = new HttpRequest(HttpRequest.GET, REQ_ITEM_TYPES, new ItemTypeJsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
}
public ArrayList<GroceryStore> getAllGroceryStores() {
if (groceryStoreDao != null) {
return groceryStoreDao.getAllGroceryStores();
}
return null;
}
public void getAllGroceryStores(IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(getAllGroceryStores(), responseAdapter);
} else {
HttpRequest r = new HttpRequest(HttpRequest.GET, REST_GROCERY_STORES, new GroceryStoreJsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
}
public NamedList getNamedList(final int userId, final String listNameClean) {
NamedList list = null;
if (namedListDao != null) {
list = namedListDao.getNamedListByNameClean(userId, listNameClean);
if (list != null) {
ArrayList<ListGroup> groups = namedListDao.getAllItems(list.getId());
list.setItemGroups(groups);
}
}
return list;
}
public void getNamedList(final int userId, final String listNameClean, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(getNamedList(userId, listNameClean), responseAdapter);
} else {
if (listNameClean != null) {
String url = REQ_NAMED_LIST + "/" + listNameClean;
HttpRequest r = new HttpRequest(HttpRequest.GET, url, new NamedListJsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
}
}
public void searchItem(String itemNameClean, IResponseAdapter responseAdapter) {
String url = REQ_SEARCH_ITEM + "/" + itemNameClean;
HttpRequest r = new HttpRequest(HttpRequest.GET, url, new ListGroupItemJsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
public boolean saveUser(final User user) {
if (userDao != null) {
return userDao.saveUser(user);
}
return false;
}
public void saveUser(final User user, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(saveUser(user), responseAdapter);
} else {
if (user != null) {
HttpRequest r = new HttpRequest(HttpRequest.POST, REQ_USER, new UserJsonHandler());
r.setResponseListener(responseAdapter);
r.setContent(JSONHelper.getJSON(user));
new Thread(r).start();
}
}
}
public boolean saveNamedList(final NamedList namedList) {
if (namedListDao != null) {
return namedListDao.saveNamedList(namedList);
}
return false;
}
public void saveNamedList(final NamedList namedList, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(saveNamedList(namedList), responseAdapter);
} else {
if (namedList != null) {
HttpRequest r = new HttpRequest(HttpRequest.POST, REQ_NAMED_LIST, new NamedListJsonHandler());
r.setResponseListener(responseAdapter);
r.setContent(JSONHelper.getJSON(namedList));
new Thread(r).start();
}
}
}
public boolean saveItem(final Item item) {
if (itemDao != null) {
return itemDao.saveItem(item);
}
return false;
}
public void saveItem(final Item item, IResponseAdapter responseAdapter) {
if (item != null) {
if (Options.getInstance().isOffline()) {
sendResponse(saveItem(item), item, responseAdapter);
} else {
HttpRequest r = new HttpRequest(HttpRequest.POST, REST_ITEM, new ItemJsonHandler());
r.setResponseListener(responseAdapter);
r.setContent(JSONHelper.getJSONItem(item));
new Thread(r).start();
}
}
}
public boolean addItemToNamedList(final ListItem item) {
if (listItemDao != null) {
return listItemDao.saveListItem(item);
}
return false;
}
public void addItemToNamedList(final String namedListNameClean, final ListItem item, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(addItemToNamedList(item), item, responseAdapter);
} else {
if (item.getNamedListId() > 0 && namedListNameClean != null && item != null) {
String url = REQ_NAMED_LIST + "/" + namedListNameClean;
HttpRequest r = new HttpRequest(HttpRequest.POST, url, new JsonHandler());
r.setResponseListener(responseAdapter);
r.setContent(JSONHelper.getJSON(item));
new Thread(r).start();
}
}
}
public boolean updateUser(final User user) {
if (userDao != null) {
return userDao.updateUser(user);
}
return false;
}
public void updateUser(final User user, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(updateUser(user), user, responseAdapter);
} else {
if (user != null) {
String url = REQ_USER + "/" + user.getId();
HttpRequest r = new HttpRequest(HttpRequest.PUT, url, new JsonHandler());
r.setContent(JSONHelper.getJSON(user));
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
}
}
public boolean updateNamedList(final NamedList list) {
if (namedListDao != null) {
return namedListDao.updateNamedList(list);
}
return false;
}
public void updateNamedList(final NamedList list, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(updateNamedList(list), list, responseAdapter);
} else {
if (list != null) {
String url = REQ_NAMED_LIST + "/" + list.getId();
HttpRequest r = new HttpRequest(HttpRequest.PUT, url, new NamedListJsonHandler());
r.setResponseListener(responseAdapter);
r.setContent(JSONHelper.getJSON(list));
new Thread(r).start();
}
}
}
public boolean updateListItem(final ListItem item) {
if (listItemDao != null) {
return listItemDao.updateListItem(item);
}
return false;
}
public void updateListItem(final String namedListNameClean, final ListItem item, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(updateListItem(item), item, responseAdapter);
} else {
if (item.getNamedListId() > 0 && namedListNameClean != null && item != null) {
String url = REQ_NAMED_LIST + "/" + namedListNameClean + "/" + item.getId();
HttpRequest r = new HttpRequest(HttpRequest.PUT, url, new JsonHandler());
r.setResponseListener(responseAdapter);
r.setContent(JSONHelper.getJSON(item));
new Thread(r).start();
}
}
}
public boolean deleteUser(final User user) {
if (userDao != null) {
return userDao.deleteUser(user);
}
return false;
}
public void deleteUser(final User user, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(deleteUser(user), responseAdapter);
} else {
if (user != null) {
String url = REQ_USER + "/" + user.getId();
HttpRequest r = new HttpRequest(HttpRequest.DELETE, url, new JsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
}
}
public boolean deleteNamedList(final NamedList list) {
if (namedListDao != null) {
return namedListDao.deleteNamedList(list);
}
return false;
}
public void deleteNamedList(final NamedList list, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(deleteNamedList(list), responseAdapter);
} else {
if (list != null) {
String url = REQ_NAMED_LIST + "/" + list.getId();
HttpRequest r = new HttpRequest(HttpRequest.DELETE, url, new JsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
}
}
public boolean deleteListItem(final ListItem item) {
if (listItemDao != null) {
return listItemDao.deleteListItem(item);
}
return false;
}
public void deleteListItem(final String listNameClean, final ListItem item, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(deleteListItem(item), responseAdapter);
} else {
if (listNameClean != null && item != null) {
String url = REQ_NAMED_LIST + "/" + listNameClean + "/" + item.getId();
HttpRequest r = new HttpRequest(HttpRequest.DELETE, url, new JsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
}
}
public User login(final String username, final String password) {
User user = null;
if (userDao != null) {
user = userDao.getUserByUsernameAndPassword(username, Utils.hash(password));
}
return user;
}
public void login(final String username, final String password, IResponseAdapter responseAdapter) {
if (Options.getInstance().isOffline()) {
sendResponse(login(username, password), responseAdapter);
} else {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
HttpRequest r = new HttpRequest(HttpRequest.POST, REQ_LOGIN, new UserJsonHandler());
r.setResponseListener(responseAdapter);
r.setContent(params);
new Thread(r).start();
}
}
private void sendResponse(Object o, IResponseAdapter responseAdapter) {
if (responseAdapter != null) {
ObjectResponse r = new ObjectResponse();
r.setSuccess(o != null);
r.setData(o);
if (o == null) {
List<String> errors = new ArrayList<String>();
errors.add("Unexpected error while processing data.");
r.setErrors(errors);
}
responseAdapter.onResponse(r);
}
}
private void sendResponse(boolean success, IResponseAdapter responseAdapter) {
if (responseAdapter != null) {
ObjectResponse r = new ObjectResponse();
r.setSuccess(success);
if (!success) {
List<String> errors = new ArrayList<String>();
errors.add("Unexpected error while processing data.");
r.setErrors(errors);
}
responseAdapter.onResponse(r);
}
}
private void sendResponse(boolean success, Object o, IResponseAdapter responseAdapter) {
if (responseAdapter != null) {
ObjectResponse r = new ObjectResponse();
r.setSuccess(success);
if (success) {
r.setData(o);
} else {
List<String> errors = new ArrayList<String>();
errors.add("Unexpected error while processing data.");
r.setErrors(errors);
}
responseAdapter.onResponse(r);
}
}
private int synchronizationSteps;
private final int synchronizationTotalSteps = 4;
private boolean isSynchronizing = false;
public void synchronize(final IResponseAdapter responseAdapter) {
if (!Options.getInstance().isOffline()) {
if (responseAdapter != null) {
responseAdapter.onResponse(null);
}
return;
}
if (!isSynchronizing) {
isSynchronizing = true;
synchronizationSteps = 0;
sendAndFetchUsers(new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
if (response.isSuccessful()) {
clearAndUpdateAllUsers((ArrayList<User>) response.getData());
}
synchronizationSteps++;
confirmEndOfSynchronization(responseAdapter);
}
});
fetchGroceryStores(new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
if (response.isSuccessful()) {
groceryStoreDao.upgrade((ArrayList<GroceryStore>) response.getData());
}
synchronizationSteps++;
confirmEndOfSynchronization(responseAdapter);
}
});
fetchItemTypes(new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
if (response.isSuccessful()) {
itemTypeDao.upgrade((ArrayList<ItemType>) response.getData());
}
synchronizationSteps++;
confirmEndOfSynchronization(responseAdapter);
}
});
fetchItems(new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
if (response.isSuccessful()) {
itemDao.upgrade((ArrayList<Item>) response.getData());
}
synchronizationSteps++;
confirmEndOfSynchronization(responseAdapter);
}
});
}
}
private void confirmEndOfSynchronization(final IResponseAdapter responseAdapter) {
boolean doSend = true;
if (isSynchronizing) {
doSend = synchronizationSteps == synchronizationTotalSteps;
}
if (doSend) {
isSynchronizing = false;
if (responseAdapter != null) {
responseAdapter.onResponse(null);
}
}
}
private void clearAndUpdateAllUsers(List<User> userList) {
userDao.clear(); // should auto delete lists and items
namedListDao.clear();
listItemDao.clear();
if (userList != null) {
for (User user : userList) {
userDao.saveUser(user);
if (user.getLists() != null) {
for (NamedList list : user.getLists()) {
namedListDao.saveNamedList(list);
if (list.getItemGroups() != null) {
for (ListGroup group : list.getItemGroups()) {
if (group.getItems() != null) {
for (Item item : group.getItems()) {
ListItem lItem = (ListItem) item;
lItem.setNamedListId(list.getId());
listItemDao.saveListItem(lItem);
}
}
}
}
}
}
}
}
}
private void sendAndFetchUsers(final IResponseAdapter responseAdapter) {
ArrayList<User> users = getAllUsers();
HttpRequest r = new HttpRequest(HttpRequest.POST, REQ_USER, new UserJsonHandler());
r.addGetParameter("fullsync", "true");
JSONArray arr = JSONHelper.getJSONUsers(users, this);
// Log.d(TAG, arr.toString());
r.setContent(arr);
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
private void fetchGroceryStores(IResponseAdapter responseAdapter) {
HttpRequest r = new HttpRequest(HttpRequest.GET, REST_GROCERY_STORES, new GroceryStoreJsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
private void fetchItemTypes(IResponseAdapter responseAdapter) {
HttpRequest r = new HttpRequest(HttpRequest.GET, REQ_ITEM_TYPES, new ItemTypeJsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
private void fetchItems(IResponseAdapter responseAdapter) {
HttpRequest r = new HttpRequest(HttpRequest.GET, REST_ITEM, new ItemJsonHandler());
r.setResponseListener(responseAdapter);
new Thread(r).start();
}
}
| Java |
package edu.gatech.gro;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import edu.gatech.gro.http.IResponseAdapter;
import edu.gatech.gro.model.ListGroup;
import edu.gatech.gro.model.ListItem;
import edu.gatech.gro.model.NamedList;
import edu.gatech.gro.model.ObjectResponse;
public class ItemDisplayActivity extends Activity {
private static final String TAG = "ITEM_DISPLAY_ACTIVITY";
private final IncomingHandler mHandler = new IncomingHandler();
private static final int GOT_LIST = 0;
private static final int GOT_CHECK = 1;
private static final int LIST_ITEM_DELETED = 10;
private static GroceryListManagerApplication app;
private ExpandableListView mTree;
private Button mAddItemButton;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressList;
private ProgressDialog mProgressDelete;
private NamedList mCurrentList;
private ItemAdapter mItemDisplayAdapter;
private int mUserId;
private int mListId;
// private String mListName;
private String mListNameClean;
private CheckBox mLastCheck;
private ProgressBar mLastProgress;
private boolean mLastCheckStatus;
private int mLastListItemDeletedGroupIndex;
private int mLastListItemDeletedIndex;
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
app = (GroceryListManagerApplication) getApplicationContext();
setContentView(R.layout.items_manager);
mTree = (ExpandableListView) findViewById(R.id.expandableListViewItems);
Bundle extra = getIntent().getExtras();
mUserId = extra.getInt("userId");
mListId = extra.getInt("namedListId");
// mListName = extra.getString("namedListName");
mListNameClean = extra.getString("namedListNameClean");
// Search Button
mAddItemButton = (Button) findViewById(R.id.addItemButton);
mAddItemButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "mAddItemButton clicked");
displayItemAdderPanel();
}
});
}
@Override
public void onResume() {
super.onResume();
waitForList();
}
private void waitForList() {
if (mProgressList != null && mProgressList.isShowing()) {
return;
}
mProgressList = ProgressDialog.show(ItemDisplayActivity.this, "", // this.getString(R.string.pleaseWait),
this.getString(R.string.progressList), true, false);
app.getNamedList(mUserId, mListNameClean, mListListener);
}
private void waitForDeleteListItem(final ListItem item) {
if (mProgressDelete != null && mProgressDelete.isShowing()) {
return;
}
mProgressDelete = ProgressDialog.show(ItemDisplayActivity.this, "", // this.getString(R.string.pleaseWait),
this.getString(R.string.progressDelete), true, false);
app.deleteListItem(mListNameClean, item, mListItemDeletedListener);
}
private void refreshList() {
if (mCurrentList != null) {
mItemDisplayAdapter = new ItemAdapter(mCurrentList);
mTree.setAdapter(mItemDisplayAdapter);
}
}
private void displayItemAdderPanel() {
Intent i = new Intent(this, ItemLookUpActivity.class);
i.putExtra("namedList_nameClean", mListNameClean);
i.putExtra("namedList_id", mListId);
startActivity(i);
}
private void alterCheck() {
if (mLastCheck != null && mLastProgress != null) {
mLastProgress.setVisibility(ProgressBar.INVISIBLE);
mLastCheck.setChecked(mLastCheckStatus);
mLastCheck.setEnabled(!mLastCheckStatus);
mLastCheck.setVisibility(CheckBox.VISIBLE);
}
}
private void deleteListItem(ListItem item) {
if (mLastListItemDeletedGroupIndex > -1 && mLastListItemDeletedIndex > -1) {
waitForDeleteListItem(item);
}
}
/**
* Helper function to dismiss a progress dialog
*
* @param theProgress
* the progress dialog to dismiss
*/
private void dismissProgress(ProgressDialog theProgress) {
if (theProgress != null && theProgress.isShowing()) {
theProgress.dismiss();
}
}
/**
* Handler of incoming messages from the Service
*/
private class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case GOT_LIST:
refreshList();
break;
case GOT_CHECK:
alterCheck();
break;
case LIST_ITEM_DELETED:
if (mLastListItemDeletedGroupIndex != -1 && mLastListItemDeletedIndex != -1) {
mCurrentList.getItemGroups().get(mLastListItemDeletedGroupIndex).getItems().remove(mLastListItemDeletedIndex);
if (mCurrentList.getItemGroups().get(mLastListItemDeletedGroupIndex).getItems().size() == 0) {
mCurrentList.getItemGroups().remove(mLastListItemDeletedGroupIndex);
}
mItemDisplayAdapter.notifyDataSetChanged();
mLastListItemDeletedGroupIndex = -1;
mLastListItemDeletedIndex = -1;
}
break;
default:
super.handleMessage(msg);
break;
}
}
}
private final IResponseAdapter mListListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressList);
if (response.isSuccessful()) {
mCurrentList = (NamedList) response.getData();
Log.d(TAG, "Types received!");
// Send a message to the activity to update the view (on the UI
// thread)
mHandler.sendEmptyMessage(GOT_LIST);
} else {
displayError(R.string.failRetriveListContentTitle, response.getErrorsAsString());
}
}
};
private final IResponseAdapter mCheckListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
mLastCheckStatus = response.isSuccessful();
mHandler.sendEmptyMessage(GOT_CHECK);
}
};
private final IResponseAdapter mListItemDeletedListener = new IResponseAdapter() {
@Override
public void onResponse(ObjectResponse response) {
dismissProgress(mProgressDelete);
if (response.isSuccessful()) {
mHandler.sendEmptyMessage(LIST_ITEM_DELETED);
} else {
displayError(R.string.failDeleteItemTitle, response.getErrorsAsString());
}
}
};
private void displayError(final int titleId, final String message) {
mAlertDialog.setTitle(titleId);
mAlertDialog.setMessage(message);
mAlertDialog.show();
}
private class ItemAdapter extends BaseExpandableListAdapter {
private static final String TAG = "ITEM_DISPLAY_ADAPTER";
private final NamedList mCurrentList;
public ItemAdapter(NamedList currentList) {
super();
this.mCurrentList = currentList;
}
@Override
public ListItem getChild(int groupPosition, int childPosition) {
return (ListItem) mCurrentList.getItemGroups().get(groupPosition).getItems().get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return mCurrentList.getItemGroups().get(groupPosition).getItems().get(childPosition).getId();
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_type_item, null);
}
final ListItem li = getChild(groupPosition, childPosition);
if (li != null) {
final TextView textQuantity = (TextView) v.findViewById(R.id.list_type_item_quantity);
final TextView textName = (TextView) v.findViewById(R.id.list_type_item_name);
final CheckBox checkbox = (CheckBox) v.findViewById(R.id.list_type_item_check);
final ProgressBar progress = (ProgressBar) v.findViewById(R.id.list_type_item_progress);
/*
* if it is checked, display the number of items bought otherwise,
* display the number of remaining items to buy.
*/
int q = li.isChecked() ? li.getQuantity() : li.getQuantity() - li.getCurrentQuantity();
textName.setText(li.getName());
textQuantity.setText(Integer.toString(q));
checkbox.setChecked(li.isChecked());
checkbox.setEnabled(!li.isChecked());
checkbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!li.isChecked()) {
Log.d(TAG, "Checkbox clicked for item #" + li.getId());
checkbox.setVisibility(CheckBox.INVISIBLE);
progress.setVisibility(ProgressBar.VISIBLE);
mLastCheck = checkbox;
mLastProgress = progress;
li.setChecked(true);
li.setNamedListId(mCurrentList.getId());
app.updateListItem(mCurrentList.getNameClean(), li, mCheckListener);
}
}
});
textName.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
deleteListItem(li);
mLastListItemDeletedIndex = childPosition;
mLastListItemDeletedGroupIndex = groupPosition;
return false;
}
});
}
return v;
}
@Override
public int getChildrenCount(int groupPosition) {
return mCurrentList.getItemGroups().get(groupPosition).getItems().size();
}
@Override
public ListGroup getGroup(int groupPosition) {
return mCurrentList.getItemGroups().get(groupPosition);
}
@Override
public int getGroupCount() {
return mCurrentList.getItemGroups().size();
}
@Override
public long getGroupId(int groupPosition) {
return mCurrentList.getItemGroups().get(groupPosition).getId();
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_type, null);
}
final ListGroup g = getGroup(groupPosition);
if (g != null) {
TextView textName = (TextView) v.findViewById(R.id.list_type_name);
TextView textCount = (TextView) v.findViewById(R.id.list_type_count);
textName.setText(g.getName());
textCount.setText(Integer.toString(g.getItems().size()));
}
return v;
}
@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return false;
}
}
}
| Java |
package edu.gatech.gro.utils;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import edu.gatech.gro.model.AbstractObject;
import edu.gatech.gro.model.Item;
import edu.gatech.gro.model.ListGroup;
import edu.gatech.gro.model.ListItem;
import edu.gatech.gro.model.NamedList;
import edu.gatech.gro.model.User;
public class JSONHelper {
private static final String TAG = "JSON_HELPER";
public static JSONArray getJSONUsers(List<User> users, Context ctx) {
JSONArray arr = new JSONArray();
if (users != null) {
for (User u : users) {
arr.put(getJSON(u, ctx));
}
}
return arr;
}
public static JSONObject getJSON(User user) {
return getJSON(user, null);
}
public static JSONObject getJSON(User user, Context ctx) {
JSONObject json = getJSONAbstract(user);
if (user != null) {
try {
json.put("username", user.getUsername());
json.put("usernameClean", user.getUsernameClean());
json.put("email", user.getEmail());
json.put("password", user.getPassword());
if (ctx != null) {
json.put("lists", getJSONLists(user.getLists(ctx), ctx));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
return json;
}
public static JSONArray getJSONLists(List<NamedList> lists, Context ctx) {
JSONArray arr = new JSONArray();
if (lists != null) {
for (NamedList l : lists) {
arr.put(getJSON(l, ctx));
}
}
return arr;
}
public static JSONObject getJSON(NamedList namedList) {
return getJSON(namedList, null);
}
public static JSONObject getJSON(NamedList namedList, Context ctx) {
JSONObject json = getJSONAbstract(namedList);
if (namedList != null) {
try {
json.put("name", namedList.getName());
json.put("nameClean", namedList.getNameClean());
if (ctx != null) {
json.put("groups", getJSONItemGroups(namedList.getItemGroups(ctx), ctx));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
return json;
}
public static JSONArray getJSONItemGroups(List<ListGroup> groups, Context ctx) {
JSONArray arr = new JSONArray();
if (groups != null) {
for (ListGroup lg : groups) {
arr.put(getJSON(lg, ctx));
}
}
return arr;
}
public static JSONObject getJSON(ListGroup group) {
return getJSON(group, null);
}
public static JSONObject getJSON(ListGroup group, Context ctx) {
JSONObject json = getJSONAbstract(group);
if (group != null) {
try {
json.put("name", group.getName());
json.put("nameClean", group.getNameClean());
if (ctx != null) {
json.put("items", getJSONItems(group.getItems()));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
return json;
}
public static JSONArray getJSONItems(List<Item> items) {
JSONArray arr = new JSONArray();
if (items != null) {
for (Item li : items) {
arr.put(getJSON((ListItem) li));
}
}
return arr;
}
/**
* Returns a JSON object modelising the NamedListItem object.
*
* @param namedList
* @param item
* @return A NamedListItem
*/
public static JSONObject getJSON(ListItem item) {
JSONObject json = getJSONAbstract(item);
if (item != null) {
try {
json.put("checked", item.isChecked());
json.put("quantity", item.getQuantity());
json.put("currentQuantity", item.getCurrentQuantity());
json.put("namedListId", item.getNamedListId());
json.put("itemId", item.getId());
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
return json;
}
public static JSONObject getJSONItem(Item item) {
JSONObject json = getJSONAbstract(item);
if (item != null) {
try {
json.put("itemTypeId", item.getItemTypeId());
json.put("groceryStoreId", item.getGroceryStoreId());
json.put("name", item.getName());
json.put("nameClean", item.getNameClean());
json.put("barCode", item.getId());
json.put("price", item.getPrice());
json.put("currency", item.getCurrency());
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
return json;
}
public static JSONObject getJSON(int namedListId, ListItem item) {
JSONObject json = getJSONAbstract(item);
if (item != null) {
try {
json.put("checked", item.isChecked());
json.put("quantity", item.getQuantity());
json.put("currentQuantity", item.getCurrentQuantity());
json.put("namedListId", namedListId);
json.put("itemId", item.getId());
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
return json;
}
public static JSONObject getJSONAbstract(AbstractObject ao) {
JSONObject json = new JSONObject();
if (ao != null) {
try {
json.put("id", ao.getId());
json.put("creationTime", ao.getCreationTime());
json.put("lastUpdateTime", ao.getLastUpdateTime());
json.put("deleteFlag", ao.isDeleteFlag());
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
return json;
}
}
| Java |
package edu.gatech.gro.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import android.util.Log;
public class Utils {
private static final String TAG = "UTILS";
public static int getCurrentTimestamp() {
return (int) (Calendar.getInstance().getTimeInMillis() / 1000);
}
public static String cleanName(String name) {
if (name != null) {
name = name.replaceAll("â|ä|à|Â|Ä|À", "a");
name = name.replaceAll("ê|ë|é|è|Ê|Ë|É|È", "e");
name = name.replaceAll("î|ï|Î|Ï", "i");
name = name.replaceAll("ô|ö|Ô|Ö", "o");
name = name.replaceAll("û|ü|ù|Û|Ü|Ù", "u");
name = name.replaceAll("ŷ|ÿ|Ŷ|Ÿ", "y");
name = name.replaceAll("ç|Ç", "c");
name = name.replaceAll("'| |&", "-");
name = name.toLowerCase().trim();
}
return name;
}
public static String hash(String text) {
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(text.getBytes());
StringBuilder sb = new StringBuilder(64);
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, e.getMessage());
}
return "";
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
/**
*
* @author Administrator
*/
public class jCLass_PhanPre implements Interface_CacThanhPhanDacTa {
private jClass_TruongHopDacTa _CacDieuKieu;
private static String _BieuThucDinhDang = ".*";//jClass_TruongHopDacTa.getBieuThucDinhDang();
public jCLass_PhanPre(){
_CacDieuKieu = new jClass_TruongHopDacTa();
//_BieuThucDinhDang = jClass_TruongHopDacTa.getBieuThucDinhDang();
}
/**
* @return the _CacDieuKieu
*/
public jClass_TruongHopDacTa getCacDieuKieu() {
return _CacDieuKieu;
}
/**
* @param CacDieuKieu the _CacDieuKieu to set
*/
public void setCacDieuKieu(jClass_TruongHopDacTa CacDieuKieu) {
this._CacDieuKieu = CacDieuKieu;
}
/**
* @return the _BieuThucDinhDang
*/
public static String getBieuThucDinhDang() {
return _BieuThucDinhDang;
}
/**
* @param aBieuThucDinhDang the _BieuThucDinhDang to set
*/
public static void setBieuThucDinhDang(String aBieuThucDinhDang) {
_BieuThucDinhDang = aBieuThucDinhDang;
}
public void jCapNhatTuChuoi(String Str_KhaiBao) {
//throw new UnsupportedOperationException("Not supported yet.");
if (!Str_KhaiBao.startsWith("(") && Str_KhaiBao.length() > 0)
Str_KhaiBao = "(" + Str_KhaiBao + ")";
if (!jKiemTraChuoiHopDinhDang(Str_KhaiBao)){
String mess = "Chuoi:\n" + Str_KhaiBao + "\n khong hop dinh dang cua mot phan Pre!!!";
JOptionPane.showMessageDialog(null, mess);
throw new ExceptionInInitializerError(Str_KhaiBao);
}
_CacDieuKieu = new jClass_TruongHopDacTa();
if (Str_KhaiBao.equals(""))
return;
_CacDieuKieu.jCapNhatTuChuoi(Str_KhaiBao);
}
public Boolean jKiemTraChuoiHopDinhDang(String str_ChuoiCanKienTra) {
//throw new UnsupportedOperationException("Not supported yet);
Pattern pat=Pattern.compile(getBieuThucDinhDang());
Matcher matcher =pat.matcher(str_ChuoiCanKienTra);
return matcher.matches();
}
public String jToCCode(int DoLui) {
String str_Kq = "";
if (_CacDieuKieu.getCacDieuKien().length != 0){
str_Kq = jClass_BoTaoCode.jTaoCapDo(DoLui) + "if (!(";
}
for (jClass_BieuThucLogic bieuThucLogic : _CacDieuKieu.getCacDieuKien()){
str_Kq += bieuThucLogic.jToCCode(DoLui) + " && ";
}
//loai bo dau && cuoi cung neu co
if (str_Kq.contains(" && ")){
str_Kq = str_Kq.substring(0, str_Kq.lastIndexOf(" && "));
str_Kq += "))\n";
str_Kq += jClass_BoTaoCode.jTaoCapDo(DoLui + 1) + "return false;\n";
}
str_Kq += jClass_BoTaoCode.jTaoCapDo(DoLui) + "return true;";
return str_Kq;
}
public String jCSharpCode(int DoLui) {
String str_Kq = "";
if (_CacDieuKieu.getCacDieuKien().length != 0){
str_Kq = jClass_BoTaoCode.jTaoCapDo(DoLui) + "if (!(";
}
for (jClass_BieuThucLogic bieuThucLogic : _CacDieuKieu.getCacDieuKien()){
str_Kq += bieuThucLogic.jToCCode(DoLui) + " && ";
}
//loai bo dau && cuoi cung neu co
if (str_Kq.contains(" && ")){
str_Kq = str_Kq.substring(0, str_Kq.lastIndexOf(" && "));
str_Kq += "))\n";
str_Kq += jClass_BoTaoCode.jTaoCapDo(DoLui + 1) + "return false;\n";
}
str_Kq += jClass_BoTaoCode.jTaoCapDo(DoLui) + "return true;";
return str_Kq;
}
public String jVBNetCode(int DoLui) {
String str_Kq = "";
if (_CacDieuKieu.getCacDieuKien().length != 0){
str_Kq = jClass_BoTaoCode.jTaoCapDo(DoLui) + "if (!(";
}
for (jClass_BieuThucLogic bieuThucLogic : _CacDieuKieu.getCacDieuKien()){
str_Kq += bieuThucLogic.jToCCode(DoLui) + " AND ";
}
//loai bo dau && cuoi cung neu co
if (str_Kq.contains(" AND ")){
str_Kq = str_Kq.substring(0, str_Kq.lastIndexOf(" AND "));
str_Kq += "))\n";
str_Kq += jClass_BoTaoCode.jTaoCapDo(DoLui + 1) + "return false;\n";
}
str_Kq += jClass_BoTaoCode.jTaoCapDo(DoLui) + "return true;";
return str_Kq;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.