| free hosting image hosting hosting reseller online album e-shop famous people | ||
![]() ![]() |
||
Java Programming
@ Ratana Ty, U.S.A, 27-Sept-2004
ratanatycom@yahoo.com
The purpose of creating the site is to help people with some intructions of common basis of Java Programming Language.
1- Simple Technique:
€ Find Max Value:
public class max{
public static void main(String args[])
{
int[] arr = {1,3,12,4,5};
int max = arr[0];
for (int i=0; i<arr.length; i++)
{
if(max < arr[i])
{
max = arr[i];
}
}
System.out.println(max);
}
}
€ Find Second Max Value:
public class max2{
public static void main(String args[])
{
int[] arr = {1,3,12,4,5,11};
int max = arr[0];
int j=0;
int secondmax=0;
for (int i=0; i<arr.length; i++)
{
if(max < arr[i])
{
max = arr[i];
j = max;
}
}
max =0;
for (int i=0; i<arr.length; i++)
{
if((arr[i]!=j)&&(max < arr[i]))
{
secondmax = arr[i];
}
}
System.out.println(secondmax);
}
}
€ Find n Max Value:
// Actually Java already have the function to short arry
// but we just want to show you the simple logic the programmers should know
public class maxn{
public int sub(int n, int[] arr) {
boolean b= false;
// while not sorted
// for Bubble sort
while (!b)
{
b=true;
for (int i=0; i<arr.length-1; i++)
{
if(arr[i] > arr[i+1])
{
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
b = false;
}
}
}
return arr[arr.length-n];
}
public static void main(String args[])
{
int[] arr = {1,3,12,4,5,11,2,6,7,8};
maxn test = new maxn();
System.out.println("Result"+test.sub(3,arr));
}
}
€ Sort String in an array:
class test{
public static void main(String arg[])
{
String name[]={"yame","ratana","sey","ABC","122222","222"};
for(int i=0;i<name.length;i++)
{
for(int j=0; j<name.length-1-i; j++)
{
if(name[j].compareTo(name[j+1])>0)
{
String temp=name[j];
name[j]=name[j+1];
name[j+1]=temp;
}
}
}
// print out the result
for(int i=0;i<name.length;i++)
{
System.out.println(name[i]);
}
}
}
2- MySQL Connection:
download from mysql site: mysql-connector-java-3.0.14-production and the copy a file mysql-connector-java-3.0.14-production-bin to c:\j2sdk1.4.0_03\jre\lib\ext\ then you can connect to database. Then you should have database and table with one or two record in it. I suppose that you are able to create database by your own.
import java.beans.*;
import java.sql.*;
/**
* @author Soyapi
*
*/
public class ShowData extends Object implements java.io.Serializable {
//private PropertyChangeSupport propertySupport;
private static String db = "jdbc:mysql://localhost:3306/mynote";
private static Connection con;
private static String str = "select * from tbl_addr_book";
private static java.sql.Statement stmt;
private static ResultSet rs = null;
static String[] id = new String[2];
static String[] name = new String[2];
static String[] sex =new String[2];
static String[] tel =new String[2];
static String[] fax =new String[2];
static String[] e_mail=new String[2];
static String[] location =new String[2];
static String[] other =new String[2];
/**
*
*/
public static void main(String[] args) {
System.out.println("--------");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch(java.lang.ClassNotFoundException e) {
System.err.println(e.getMessage());
};
try {
con = DriverManager.getConnection(db, "root","123456");
stmt = con.createStatement();
rs = stmt.executeQuery(str);
int i = 0;
while(rs.next()){
// get records from DB into Bean using getXXX : getString,
//getFloat, getInt ...
System.out.println("ID:" + rs.getString("id") + ",
" +
rs.getString("name") + ", " +
rs.getString("sex") + ", " +
rs.getString("tel") + ", " +
rs.getString("fax") + ", " +
rs.getString("e_mail") + ", " +
rs.getString("location") + ", " +
rs.getString("other")
) ;
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println(ex.getMessage());
rs = null;
}
}
}
3- Applete and Event:
// All files Splash.java
and Royal.java and NewAccount.java
should be in the same project
Splash.java
import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class Splash extends JWindow {
private Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
public Splash(){
JLabel lbImage = new JLabel("Test",new ImageIcon("Splash.jpg"));
Color cl = new Color (0, 0, 0);
lbImage.setBorder (new LineBorder (cl, 1));
getContentPane().add(lbImage, BorderLayout.CENTER);
pack();
setSize (getSize().width, getSize().height);
setLocation (d.width/2-getWidth()/2, d.height/2 - getHeight()/2);;
show();
for (int i=0; i<=10000; i++){}
new Royal();
toFront();
dispose();
setVisible (false);
}
public static void main(String args[]) {
new Splash();
}
}
public static void main(String args[]) {
new Splash();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*; // For SimpleDateFormat
public class Royal extends JFrame implements ActionListener{
// Create a desktop
private JDesktopPane desktop= new JDesktopPane();
// Create menu bar
private JMenuBar bar;
// Create menu
private JMenu mnuFile, mnuHelp;
// Create menu items
private JMenuItem addNew, end;
private JMenuItem about;
// Create tool bar
private JToolBar toolBar;
// Create button for tool bar
private JButton btnNew;
// Create Panel
private JPanel statusBar = new JPanel();
private JLabel welcome;
private JLabel author;
// Getting the Current System Date
private java.util.Date CurrDate = new java.util.Date();
private SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy",
Locale.getDefault());
private String d = sdf.format(CurrDate);
public Royal(){
//System.out.println("Testing splash for the same
project");
super("My Address book, Ratana Ty, USA, ratanatycom@yahoo.com");
bar = new JMenuBar();
// put the icon for destop replace java cafe(default
form icon)
setIconImage (getToolkit().getImage("Splash.jpg"));
setSize(700, 500);
setJMenuBar(bar);
// set location of form
setLocation((Toolkit.getDefaultToolkit().getScreenSize().width
- getWidth())/2, (Toolkit.getDefaultToolkit().getScreenSize().height
- getHeight())/2);
mnuFile = new JMenu("File");
mnuFile.setMnemonic((int)'F');
mnuHelp = new JMenu("Help");
mnuHelp.setMnemonic((int)'H');
toolBar = new JToolBar();
addNew = new JMenuItem("Add new friend");
addNew.addActionListener(this);
end = new JMenuItem("Exit");
end.addActionListener(this);
about = new JMenuItem("About...");
about.addActionListener(this);
btnNew = new JButton("Add Friend");
btnNew.setToolTipText("Add new friends");
btnNew.addActionListener(this);
mnuFile.add(addNew);
mnuFile.addSeparator();
mnuFile.add(end);
mnuHelp.add(about);
toolBar.add(btnNew);
bar.add(mnuFile);
bar.add(mnuHelp);
// Creating the StatusBar of Program
author = new JLabel(" " +"Address book",Label.LEFT);
author.setForeground(Color.black);
author.setToolTipText("Program's Title");
welcome = new JLabel("Welcome Today is "+
d +" ", Label.RIGHT);
welcome.setForeground(Color.black);
welcome.setToolTipText("User & System Current
Date");
statusBar.setLayout(new BorderLayout());
statusBar.add(author, BorderLayout.WEST);
statusBar.add(welcome, BorderLayout.EAST);
getContentPane().add (toolBar, BorderLayout.NORTH);
getContentPane().add (desktop, BorderLayout.CENTER);
getContentPane().add (statusBar, BorderLayout.SOUTH);
// show desktop
setVisible (true);
}
public void actionPerformed(ActionEvent ae){
Object obj = ae.getSource();
if((obj==addNew) || (obj==btnNew))
{
boolean b= openChildWindow("Create
New Account");
if(b==false){
NewAccount newAcc=new NewAccount();
desktop.add(newAcc);
newAcc.show();
//System.out.println("TT");
}
}
else if (obj==end){
quitApp();
}
else if (obj==about){
String msg=" Address Book
[Pvt]\n"+ "Created & Designed By:\n" + "Ratana Ty, USA
\n"+"ratanatycom@yahoo.com";
JOptionPane.showMessageDialog
(this, msg, "Address Book",JOptionPane.PLAIN_MESSAGE);
}
}
private void quitApp(){
try{
int reply=JOptionPane.showConfirmDialog(this, "Want
to exit","Exit",JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
if (reply==JOptionPane.YES_OPTION){
setVisible(false);
dispose();
System.out.println("Thank
for using it-from: Ratana");
}
}
catch(Exception e){}
}
private boolean openChildWindow( String title){
JInternalFrame[] childs=desktop.getAllFrames();
for(int i=0; i < childs.length; i++){
if(childs[i].getTitle().equalsIgnoreCase(title)){
childs[i].show();
return true;
}
}
return false;
}
public static void main(String arg[]){
new Royal();
}
}
NewAccount.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class NewAccount extends JInternalFrame implements ActionListener {
private JPanel jpInfo = new JPanel();
private JLabel lbNo;
NewAccount () {
// super(Title, Resizable, Closable, Maximizable, Iconifiable)
super ("Create New Account", false, true, false,
true);
//setSize (335, 235);
setSize (400, 235);
jpInfo.setBounds (0, 0, 500, 115);
jpInfo.setLayout (null);
lbNo = new JLabel ("Account No:");
lbNo.setForeground (Color.black);
lbNo.setBounds (15, 20, 80, 25);
//Adding the All the Controls to Panel.
jpInfo.add (lbNo);
//Adding Panel to Window.
getContentPane().add (jpInfo);
//In the End Showing the New Account Window.
setVisible (true);
}
//Function use By Buttons of Window to Perform Action as User Click Them.
public void actionPerformed (ActionEvent ae) {
Object obj = ae.getSource();
}
}
4- Change Backgroud Color, Change Layout Style, Apply Theme:
Change Backgroud Color:
When clicking on submenu or menu we can call
this code to change the background
Color cl = new Color (153, 153, 204);
cl = JColorChooser.showDialog (this, "Choose Background Color", cl);
if (cl == null) { }
else {
desktop.setBackground (cl);
desktop.repaint ();
}
Change Layout Style:
There are 3 Layout available for you.
1- metal
It is something like the defualt from java applet => changeLookAndFeel(0);
2- motif => changeLookAndFeel(1);
3- windows => changeLookAndFeel(2);
import javax.swing.*;
private UIManager.LookAndFeelInfo looks[] = UIManager.getInstalledLookAndFeels
();
public void changeLookAndFeel (int val) {
try {
UIManager.setLookAndFeel (looks[val].getClassName());
SwingUtilities.updateComponentTreeUI
(this);
}
catch (Exception e) { }
}
Apply Theme:
we must have UISwitchListener.java, MetalThemeMenu.java, PropertiesMetalTheme.java
and them files(AquaTheme.java, GrayTheme.java, GreenTheme.java, MilkyTheme.java,
SandTheme.java, SolidTheme.java). What you have to do is copy those files into
on directory and then compile each file. In the main file we should:
in construction:
UIManager.addPropertyChangeListener (new UISwitchListener ((JComponent)getRootPane()));
// to apply the theme on desktop.
Add a code:
theme = new JMenuItem("Apply Theme");
theme.addActionListener(this);
MetalTheme[] themes = { new DefaultMetalTheme(), new GreenTheme(), new AquaTheme(),
new SandTheme(), new SolidTheme(), new MilkyTheme(), new GrayTheme() };
theme = new MetalThemeMenu ("Apply Theme", themes); //Putting
the Themes in ThemeMenu.
theme.setMnemonic ((int)'m');//Putting the Themes in ThemeMenu.
The bold must be the same to show the sub menu in that Apply Theme menu Item.
http://java.ittoolbox.com/code/d.asp?d=1631&a=s