You are on page 1of 7

JAVA

Advance codes

Imal Hasaranga perera

Getting a image from a URL and setting it to a label


ImageIcon icon = new ImageIcon("E:/warning_64.png", ""); jLabel1.setIcon(icon); you can use relative path /warning_64.png like this path starts from source package so the image should be in the souce package (default pagckage) , if image is in a different package u can use /packagename/warning_64.png

Working with the time


Date d1 = new Date(); // creating a new date object DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); // date format Converting a string to a date object using dateformat method DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); String y = "2008/12/21"; Date y1 = dateFormat.pars(y); Formatting a Date according to a format DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); String = dateFormat.format(new Date()); Getting the time from milliseconds Date d1 = new Date(); Long x = d1.getTime();

Massage dialogs
Normal massage dialog JOptionPane.showMessageDialog(null, "click"); Warning massage dialog box Object[] options = { "YES", "CANCEL" }; int respon = JOptionPane.showOptionDialog(null, "Are You Sure You want to Proceed", "Warning",JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null, options, options[0]); if(respon==0){ System.out.println( this is YES ); }

Imal Hasaranga perera

Playing a sound track


(plays a sound using url of the track) try { String gongFile = "E:/button117.wav"; InputStream in = new FileInputStream(gongFile); AudioStream audioStream = new AudioStream(in); AudioPlayer.player.start(audioStream); } catch (Exception e) { System.out.println(e); } }

Sql Queries
Sql query to get the last row SELECT * FROM users ORDER BY userid DESC LIMIT 1

Sql inner queries (nested queries )


SELECT Model FROM Product WHERE ManufacturerID IN (SELECT ManufacturerID FROM Manufacturer WHERE Manufacturer = 'Dell')

Sql query example to use logics select* from project where (ProjectType = '"+Type+"')&&(RequestID = '"+RequesId1+"')

Adding a image to Database using prepared statement(sql data type should set to blob)
String fName = "C:/Documents and Settings/PC/My Documents/My Pictures/birthday-cat.jpg"; File f = new File(fName); FileInputStream in; try { in = new FileInputStream(f); byte[] image = new byte[(int) f.length()]; in.read(image); Connection con = DB.getMyConnection(); Statement st = con.createStatement(); String sql = "insert into students(studentpic,name) values(?,?)"; PreparedStatement stmt = (PreparedStatement) con.prepareStatement(sql); stmt.setBytes(1, image);

Imal Hasaranga perera

stmt.setString(2, id.getText()); stmt.executeUpdate(); stmt.close(); } catch (Exception e) { System.out.println(e+"gg"); }

Retriving image from Database


Blob b = (Blob) rs.getBlob("image"); ImageIcon icon = new ImageIcon(b.getBytes(1L, (int) b.length())); l1.setIcon(icon);

Password encrypt
import java.security.MessageDigest; public class EncryptExample { public static void main(String[] args) { String password = "secret"; String algorithm = "SHA"; byte[] plainText = password.getBytes(); MessageDigest md = null; try { md = MessageDigest.getInstance(algorithm); } catch (Exception e) { e.printStackTrace(); } md.reset(); md.update(plainText); byte[] encodedPassword = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < encodedPassword.length; i++) { if ((encodedPassword[i] & 0xff) < 0x10) { sb.append("0"); } sb.append(Long.toString(encodedPassword[i] & 0xff, 16)); } System.out.println("Plain : " + password); System.out.println("Encrypted: " + sb.toString()); } }

Imal Hasaranga perera

Using java runtime methord


Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler C:/Windows/imal.pdf );

Setting border of a image by code


Jlabel1.setBorder(BorderFactory.createLineBorder(Color.black)); Selecting a image file from a jfile Chooser(code inside of the action performe of the jfeile chooser ) try { if (JFileChooser.CANCEL_SELECTION.equals(evt.getActionCommand())) { this.setVisible(false); } if (evt.getActionCommand().equals("ApproveSelection")) { File file = jFileChooser1.getSelectedFile(); String s = file.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { String extension = s.substring(i + 1).toLowerCase(); if ("tiff".equals(extension) || "png".equals(extension) || "gif".equals(extension) || "jpeg".equals(extension) || "jpg".equals(extension)) { System.out.println(file); System.out.println( this is a image file ); } else { JOptionPane.showMessageDialog(null, "please select a valid file type"); } } } } catch (Exception e) { System.out.println("dffdfd"); }

Creating an unlimited Array (Array list)


Creating the array ArrayList al = new ArrayList(); Adding data al.add("a"); al.add("b"); Removing data

Imal Hasaranga perera

al.remove("F"); al.remove(2);

getting elements out Object a[] = al.toArray(); System.out.println(String.valueOf(a[0]));

Java ternary operator example


int d = a<b ? a:b;

Absolute path
this.getClass().getResource("zero.au").toString() System.getProperty("user.dir") + "/src/" + path

Keybord key events when no text fields .etc


Just implement keylistener to your frame, panel and do like this way And by this.requestFocusInWindow(); way you can call the focuse again to the frame if you click a button on frame using mouse
class MyPanel extends JPanel implements KeyListener { . . . //=================================== constructor public MyPanel() { this.setFocusable(true); // Allow this panel to get focus.

this.addKeyListener(this); // listen to our own key events. . . . }

//-- Define one or more of these to handle keyboard events public void keyPressed(KeyEvent e) {. . .} public void keyReleased(KeyEvent e){. . .} public void keyTyped(KeyEvent e) } {. . .}

Imal Hasaranga perera

Jasper notes you can get from


http://aspalliance.com/1229_Creating_and_Designing_Report_Using_iReport__Part_1.4 http://aspalliance.com/1229_Creating_and_Designing_Report_Using_iReport__Part_1.4 http://ireport.sourceforge.net/cap8.html http://record-editor.sourceforge.net/re2Jasper.htm http://mdahlman.wordpress.com/category/ireport/

Imal Hasaranga perera

You might also like