Pikopong

It's all about knowledge

Archive for the ‘programming’ tag

Auto Resize JTable Column Width

View Comments

This code should resize your JTable column width based on the contents of the header and data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    public JTable autoResizeColWidth(JTable table, DefaultTableModel model) {
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setModel(model);

        int margin = 5;

        for (int i = 0; i < table.getColumnCount(); i++) {
            int                     vColIndex = i;
            DefaultTableColumnModel colModel  = (DefaultTableColumnModel) table.getColumnModel();
            TableColumn             col       = colModel.getColumn(vColIndex);
            int                     width     = 0;

            // Get width of column header
            TableCellRenderer renderer = col.getHeaderRenderer();

            if (renderer == null) {
                renderer = table.getTableHeader().getDefaultRenderer();
            }

            Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);

            width = comp.getPreferredSize().width;

            // Get maximum width of column data
            for (int r = 0; r < table.getRowCount(); r++) {
                renderer = table.getCellRenderer(r, vColIndex);
                comp     = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
                        r, vColIndex);
                width = Math.max(width, comp.getPreferredSize().width);
            }

            // Add margin
            width += 2 * margin;

            // Set the width
            col.setPreferredWidth(width);
        }

        ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(
            SwingConstants.LEFT);

        // table.setAutoCreateRowSorter(true);
        table.getTableHeader().setReorderingAllowed(false);

        return table;
    }

Example:

1
2
3
// Must pass the model
DefaultTableModel model = new DefaultTableModel();
jTable = autoResizeColWidth(jTable, model);

Tested on JRE v5 and JRE v6

Written by amree

August 13th, 2008 at 2:49 pm

Posted in programming

Tagged with , ,

Reading MyKad using Visual Basic

View Comments

It seems that a lot of people asking how to read MyKad using Visual Basic, but since I don’t have the slightest idea on how to code in VB, I started to search around. To my surprise, Xenon (the one who reverse engineered MyKad to get the APDU) actually wrote a small application in VB to read MyKad. So, for those who can’t afford to buy SDK from commercial company, you can download the code here for FREE !

VB Application to read MyKad


View the discussion
Download the code

Written by amree

May 28th, 2008 at 12:32 am

Posted in programming

Tagged with , , ,

Printing to Zebra S4M Using Java and ZPL II

View Comments

Apparently there’re some codes scattered on the net telling people that you can print to a Zebra printer by sending ZPL II codes using PrintService. But the problem is, it’s not working, I don’t know why, maybe because of a different version of printer or model but I’m pretty sure the thing that came out from the printer is just ordinary text not barcode which is what the code was supposed to output.

New Version

Thanks to Oleg for pointing out on how to print using Zebra S4M connected either via USB or network.

The solution is pretty simple, all you have to do is do not install Zebra S4M as a Zebra S4M (sounds weird, I know), instead, just install it as a local raw printer (Linux) or generic text printer (Windows).

For CUPS user in Linux, this is the example for the correct configurations:

#/etc/cups/printers.conf
<Printer Zebra>
Info
Location
DeviceURI socket://10.1.1.5:9100
State Idle
StateTime 1223445299
Accepting Yes
Shared Yes
JobSheets none none
QuotaPeriod 0
PageLimit 0
KLimit 0
OpPolicy default
ErrorPolicy stop-printer
Option orientation-requested 3
</Printer>

You can always add the printer using the web interface, just make sure you choose the RAW as the Make/Manufacturer and Model/Driver.

For Windows user, please take a look at Oleg comment.

Test this Java code, it should print out a barcode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.PrintServiceAttribute;
import javax.print.attribute.standard.PrinterName;

public class SimplePrint {

   public static void main(String[] args) {
       
       try {
           
           PrintService psZebra = null;
           String sPrinterName = null;
           PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
           
           for (int i = 0; i < services.length; i++) {
               
               PrintServiceAttribute attr = services[i].getAttribute(PrinterName.class);
               sPrinterName = ((PrinterName) attr).getValue();
               
               if (sPrinterName.toLowerCase().indexOf("zebra") >= 0) {
                   psZebra = services[i];
                   break;
               }
           }
           
           if (psZebra == null) {
               System.out.println("Zebra printer is not found.");
               return;
           }
           DocPrintJob job = psZebra.createPrintJob();

           String s = "^XA^FO100,40^BY3^B3,,30^FD123ABC^XZ";

           byte[] by = s.getBytes();
           DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
           Doc doc = new SimpleDoc(by, flavor, null);
           job.print(doc, null);
           
       } catch (PrintException e) {
           e.printStackTrace();
       }      
   }
}
</pre>

<h3>Old Version</h3>
So, I started looking around for other methods. I even tried posting on java's forum and offered 10 duke points, but no one seems to answer my question. After googling around, I found out that I could upload a file containing the ZPL II to the printer, so, I tried and it did work. But another problem arise, Two people cannot ftp simultaneously due to the limited access set by the printer.

Printing using FTP (I'
m using <a href="http://commons.apache.org/net/">Apache Commons Net</a> library)
<code lang="java" line_numbers="true">
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

public class FtpPrint {

   public static void main(String[] args) {

       try {

           FTPClient f = new FTPClient();            

           f.connect("10.1.127.3");
           f.login("anonymous", "");
           f.setFileType(FTP.ASCII_FILE_TYPE);                            

           FileInputStream in = new FileInputStream("/path/to/file");
           if (f.storeFile("filename", in)) {
               System.out.println("Upload ok");
           }                

           f.logout();
           f.disconnect();

       } catch (Exception e) {
           e.printStackTrace();
       }
   }
}

In the end I had to find another solution. After 3 days of searching the internet up and down, I found out that Zebra’s website offered a piece of code in Java to print using ZPL II using socket programming which automatically solve all of my problems, I was like, what the.. Note to myself, always search for the manufacturer site before googling around. However, a few modifications needed for the given code such as the printer port and the language sent. You can get the codes below:

Printing using socket (Got it from Zebra website)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.io.DataOutputStream;
import java.net.Socket;

public class SocketPrint {

   public static void main(String argv[]) throws Exception {

       for (int i = 0; i &lt; 10; i++) {
           Socket clientSocket = new Socket("10.1.127.3", 9100);
           DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
           outToServer.writeBytes("^XA^FO100,40^BY3^B3,,30^FD123ABC^XZ");
           clientSocket.close();
       }
   }
}

Download guide to ZPL II

Written by amree

May 11th, 2008 at 9:44 am

Posted in programming

Tagged with ,

Automatically Sign JARs using Ant and Bash

View Comments

This guide is more towards Netbeans project, but it can be used as a reference for you to customize the script to suit your needs.

The signer bash file:

1
2
3
4
#!/bin/bash
find . -name "*.jar" -exec jarsigner -keystore /path/to/your/key -storepass yourpassword '{}' yourkeystorename \;
echo 'JARs signed';
exit 0

This script will actually search all files ending with .jar from the current directory recursively and then sign it. This means, it can be used separately without ant script. Just make it executeable and run it.

Put this in the last line of your build.xml but it must before the closing tag of the “project” (build.xml can be found in your main project directory)

1
2
3
4
5
6
7
8
<project>
    .
    .
    .
    <target name="-post-jar">
        <exec dir="${dist.dir}" executable="/path/to/your/signer" os="Linux" />
    </target>
</project>

This script will basically sign the jars after all the jars has been build. Please note that it’s better if you set all the path using absolute type of path.

After this, you just have to use Clean and Build to automatically generate the JARs and also automatically sign it. This script will also sign all of your libraries. Good luck :)

Written by amree

April 14th, 2008 at 8:48 am

Posted in programming

Tagged with , , , ,

Reading MyKad in Linux

View Comments

If this is your first time reading my guide in reading MyKad, I suggest you read my first post regarding MyKad. It will give you the basic idea what this is all about.

This article will only guide you what you should do so that you can read MyKad in Linux. However, your success rate still depends on the type of hardware you use, especially the reader since there are not so many reader that support Linux. These are my working environment in Linux:

For more info about the application used at the end of this guide, please refer to my post about Reading MyKad in Windows. I would like to thanks my colleague for guiding me on how to do this before. So, here it goes:

  1. Login as root first.
  2. Since my reader use USB, I need to get libusb library.
  3. Install libusb library
    1
    2
    3
    4
    5
    6
    7
    8
    9
    tar zxvf libusb-0.1.12.tar.gz

    cd libusb-0.1.12.

    ./configure

    make

    make install
  4. Get the latest version of PCSC Lite.
  5. Install PCSC Lite
    1
    2
    3
    4
    5
    6
    7
    8
    9
    tar zxvf pcsc-lite-1.4.4.tar.gz

    cd pcsc-lite-1.4.4

    ./configure

    make

    make install
  6. For pcsc-lite-1.5.1, change the 3rd line to
    ./configure --enable-libusb --disable-libhal

    Thanks to pakdo for the update :)

  7. Download the driver for the reader first. In this case, I’m using a reader from Athena.
  8. Install the driver
    tar -xjvf asedriveiiie-usb-3.5.tar.bz2

    cd asedriveiiie-usb-3.5

    ./configure

    make

    make install
  9. Get Windows Binary of JPC/SC Java API, I know it’s for Windows but it also has precompiled linux library in it.
  10. Extract, copy and update
    1
    2
    3
    4
    5
    6
    7
    unzip jpcsc-0.8.0.zip

    cd jpcsc/bin/linux

    cp libjpcsc.so /usr/lib

    ldconfig
  11. Start the pcsc service
    pcscd -d -f
  12. Download the application here.
  13. Run. It should be working now.

Written by amree

January 6th, 2008 at 6:36 pm

Posted in programming

Tagged with , ,