Monday, December 1, 2014

JList Sample







import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class myJList extends JFrame implements ActionListener
{
    String months[]={"January","February","March","April",
            "May","June","July","August","September",
            "October","November", "December"};
    JList jlist1;
    JPanel pane,pane2;
    JScrollPane jsp;
    JButton jbadd,jbdel,jbrall;
    DefaultListModel dlm;
    public myJList()
    {
        super("JList Example");
        setSize(300,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        dlm=new DefaultListModel();
        int i;
        for(i=0;i<months.length;i++)
            dlm.addElement(months[i]);
        jlist1=new JList(dlm);
        jsp=new JScrollPane(jlist1);
        pane=new JPanel();
        pane2=new JPanel();
        jbadd=new JButton("Add");
        jbdel=new JButton("Remove");
        jbrall=new JButton("Remove All");
        pane2.add(jbadd);
        pane2.add(jbdel);
        pane2.add(jbrall);
        jbadd.addActionListener(this);
        jbdel.addActionListener(this);
        jbrall.addActionListener(this);
        pane.setLayout(new BorderLayout());
        pane.add("Center",new JPanel().add(jsp));
        pane.add("North",pane2);
        setContentPane(pane);
       
        setVisible(true);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==jbrall)
        {    dlm.removeAllElements();
        }
        if(e.getSource()==jbdel)
            dlm.removeElementAt(jlist1.getSelectedIndex());
        if(e.getSource()==jbadd)
        {
            String inputValue = JOptionPane.showInputDialog("Please input a value");
            if(!inputValue.equals(""))
            {
                dlm.addElement(inputValue);
            }
        }
    }
    public static void main(String args[])
    {
        new myJList();
    }
}

Sunday, November 30, 2014

Test Input String Palindrone or not. (Palindrone mean symmetrical string)

class palindrone2
{    public static void main(String args[])
    {    if(args.length==0)
            System.out.println("java palindrone YourString");
        else
        {    String st1=new String(args[0]);
            boolean palin=true;
            int i,j=st1.length()-1;
            for(i=0;i<st1.length()/2;i++)
                if(st1.charAt(i)!=st1.charAt(j--))
                {    palin=false;
                    break;
                }
            if(palin)
                System.out.println("Palindrone");
            else
                System.out.println("Not palindrone");
        }
    }
}

Sunday, November 16, 2014

JTable and TableModel

import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;

public class SimpleTableDemo extends JFrame {
    private boolean DEBUG = true;

    public SimpleTableDemo() {
        super("SimpleTableDemo");

        Object[][] data = {
            {"Mary", "Campione",
             "Snowboarding", new Integer(5), new Boolean(false)},
            {"Alison", "Huml",
             "Rowing", new Integer(3), new Boolean(true)},
            {"Kathy", "Walrath",
             "Chasing toddlers", new Integer(2), new Boolean(false)},
            {"Mark", "Andrews",
             "Speed reading", new Integer(20), new Boolean(true)},
            {"Angela", "Lih",
             "Teaching high school", new Integer(4), new Boolean(false)}
        };

        String[] columnNames = {"First Name",
                                "Last Name",
                                "Sport",
                                "# of Years",
                                "Vegetarian"};

        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));

        if (DEBUG) {
            table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    printDebugData(table);
                }
            });
        }

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this window.
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    private void printDebugData(JTable table) {
        int numRows = table.getRowCount();
        int numCols = table.getColumnCount();
        javax.swing.table.TableModel model = table.getModel();

        System.out.println("Value of data: ");
        for (int i=0; i < numRows; i++) {
            System.out.print("    row " + i + ":");
            for (int j=0; j < numCols; j++) {
                System.out.print("  " + model.getValueAt(i, j));
            }
            System.out.println();
        }
        System.out.println("--------------------------");
    }

    public static void main(String[] args) {
        SimpleTableDemo frame = new SimpleTableDemo();
        frame.pack();
        frame.setVisible(true);
    }
}

Wednesday, October 15, 2014

JFileChooser with multiple FileFilters


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;
class FileTypeFilter extends FileFilter
{
    private String extension;
    private String description;

    public FileTypeFilter(String extension, String description)
    {
        this.extension = extension;
        this.description = description;
    }

    public boolean accept(File file)
    {
        if (file.isDirectory()) {
            return true;
        }
        return file.getName().endsWith(extension);
    }

    public String getDescription()
    {
        return description + String.format(" (*%s)", extension);
    }
}
class JFCtest extends JFrame implements ActionListener
{
    JButton jb1;
    JFileChooser fileChooser;
   
    public JFCtest()
    {
        super("JFileChooser MultiFilters");
        setSize(300,100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().add(new JPanel().add(jb1=new JButton("Open")));
        jb1.addActionListener(this);
        setVisible(true);
       

    }
    public void actionPerformed(ActionEvent e)
    {
        fileChooser =new JFileChooser();
        fileChooser.setCurrentDirectory(new File("D:\\myjava"));
        FileFilter jpgFilter = new FileTypeFilter(".jpg", "JPEG Image");
        FileFilter txtFilter = new FileTypeFilter(".txt", "Text File");
        FileFilter javaFilter = new FileTypeFilter(".java", "Java File");

        
        fileChooser.addChoosableFileFilter(jpgFilter);
        fileChooser.addChoosableFileFilter(txtFilter);
        fileChooser.addChoosableFileFilter(javaFilter);
        int result = fileChooser.showOpenDialog(this);
            if (result == JFileChooser.APPROVE_OPTION)
        {
                File selectedFile = fileChooser.getSelectedFile();
                    System.out.println("Selected file: " + selectedFile.getAbsolutePath());
                }
    }
    public static void main(String args[])
    {
        try {
                    // Set System L&F
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            }   catch (UnsupportedLookAndFeelException e) {// handle exception
                                  }
                catch (ClassNotFoundException e) {// handle exception
                             }
                catch (InstantiationException e) {// handle exception
                             }
            catch (IllegalAccessException e) {// handle exception
                             }
        new JFCtest();
    }
}

Monday, February 3, 2014

Caps Lock Status Displaying

import java.awt.*;
import java.awt.event.*;
class statuscaps
{
   public static void main(String args[])
   {
      boolean status = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
      if(status)
         System.out.println("You Caps Lock is on");
      else
         System.out.println("You Caps Lock is off");
   }
}

Set Caps Lock on Program

class capslockon
{
   public static void main(String args[])
   {
      java.awt.Toolkit.getDefaultToolkit().setLockingKeyState(java.awt.event.KeyEvent.VK_CAPS_LOCK, Boolean.TRUE);
   }
}

Sunday, January 26, 2014

Sine value table generating

//Write a program
//to print out the following sin table
//as follow
/*
sin(0)=0.0
sin(10)=0.17364817766693033
sin(20)=0.3420201433256687
sin(30)=0.49999999999999994
sin(40)=0.6427876096865393
sin(50)=0.766044443118978
sin(60)=0.8660254037844386
sin(70)=0.9396926207859083
sin(80)=0.984807753012208
sin(90)=1.0
*/
public class sintable
{
    public static void main(String args[])
    {
        int i;
        double r,sv;
        for(i=0;i<=90;i+=10)
        {
            r=i*Math.PI/180;
            sv=Math.sin(r);
            System.out.println("sin(" + i + ")=" +sv);
        }
    }
}

jToggleButton with JToolBar === Sample


//jTobbleButton with JToolBar
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class jf0005 extends JFrame implements ActionListener
{
    JToggleButton jt1,jt2,jt3,jt4,jt5;
    JPanel pane;
    JToolBar jtb;
    JTextField jtf1;
    String st;
    public jf0005()
    {
        super("JToggle button");
        setSize(300,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        st=new String();
        jt1=new JToggleButton("B");
        jtf1=new JTextField("B(off)I(off)U(off)A(off)K(off)",33);
        jt2=new JToggleButton("I");
        jt3=new JToggleButton("U");
        jt4=new JToggleButton("A");
        jt5=new JToggleButton("K");
        jtf1=new JTextField();
        jtb=new JToolBar();
        jtb.add(jt1);
        jtb.add(jt2);
        jtb.add(jt3);
        jtb.add(jt4);
        jtb.add(jt5);
        jt1.addActionListener(this);
        jt2.addActionListener(this);
        jt3.addActionListener(this);
        jt4.addActionListener(this);
        jt5.addActionListener(this);
       
        pane=new JPanel();
        pane.setLayout(new BorderLayout());
        pane.add("Center",jtf1);
        pane.add("North",jtb);
        setContentPane(pane);
        setVisible(true);
       

    }
    public void actionPerformed(ActionEvent e)
    {
        st="";
        if(jt1.isSelected())
            st=st+"B(on)";
        else
            st=st+"B(off)";

        if(jt2.isSelected())
            st=st+"I(on)";
        else
            st=st+"I(off)";

        if(jt3.isSelected())
            st=st+"U(on)";
        else
            st=st+"U(off)";

        if(jt4.isSelected())
            st=st+"A(on)";
        else
            st=st+"A(off)";

        if(jt5.isSelected())
            st=st+"K(on)";
        else
            st=st+"K(off)";
       
        jtf1.setText(st);

    }
    public static void main(String args[])
    {
        jf0005 a=new jf0005 ();
    }
}

Wednesday, January 22, 2014

Multiplication table of parsed argument number

//Write a program which accepts an int
//from command line argument and display
// the multiplication table for its number
class p405
{
        public static void main(String args[])
        {
                int n=Integer.parseInt(args[0]);
                int i;
                for(i=1;i<=12;i++)
                    System.out.println(i + "*" + n + "=" + i*n);
              
        }
}

Tuesday, January 21, 2014

A function which will print in reverse order of a number.

//Write a java program which accepts
//an integer from command line argument
//and with a function which will print
//in reverse order as follow.

// java p502 345
// 543

class p502
{ public static void printReverse(int num)
  { while(num>0)
    { System.out.print(num%10);
      num/=10;
    }
  }
  public static void main(String args[])
  {  int n;
     n=Integer.parseInt(args[0]);
     printReverse(n);
  }
}

Sunday, January 12, 2014

methods to find the highest and lowest integer values in the array.

// Write a getHighest(int[] arr)
// which returns the highest
// integer value in the array.
// And also write a getlowest(int[] arr)
// which returns the lowest
// integer value in the array.
class p429
{ public static int getHighest(int []arr)
  {  int i,m;
     m=arr[0];
     for(i=1;i<arr.length;i++)
        if(m<arr[i]) m=arr[i];
     return m;
  }
  public static int getLowest(int []arr)
  {  int i,m;
     m=arr[0];
     for(i=1;i<arr.length;i++)
        if(m>arr[i]) m=arr[i];
     return m;
  }
  public static void main(String args[])
  {
    int a[]={32,4,12,5,53,10};
    System.out.println("Highest Value = " + getHighest(a));
    System.out.println("Lowest Value = " + getLowest(a));
  }
}

To run windows based program from Java

class runpaint
{
  public static void main(String args[])
  {
    try{
     Runtime.getRuntime().exec("mspaint");
     }catch(Exception e){}

  }
}

Thursday, January 9, 2014

Write a program to display the name of the month of the accepted month number from command-line argument.

/*
Write a program to
display the name of
the month of the
accepted month number
from command-line
argument.
*/
class p422
{   public static String monthName(int month)
    {   String str=new String();
        switch(month)
        {  case 1 : str="January"; break;
           case 2 : str="February"; break;
           case 3 : str="March"; break;
           case 4 : str="April"; break;
           case 5 : str="May"; break;
           case 6 : str="June"; break;
           case 7 : str="July"; break;
           case 8 : str="August"; break;
           case 9 : str="September"; break;
           case 10: str="October"; break;
           case 11: str="November"; break;
           case 12: str="December"; break;
           default: str="Wrong Month value";
        }
        return str;
    }
    public static void main(String args[])
    {   int m=Integer.parseInt(args[0]);
        System.out.println(monthName(m));
    }
}

Pattern of numbers

/*
Write a java program
to print the following
pattern of numbers
Use nested loop.

1 3 5 7
3 5 7
5 7
7

*/

class p410
{
        public static void main(String args[])
        {
                int i,j,k=3;
                for(i=1;i<=7;i+=2)
                {  
                    for(j=0;j<=k;j++)
                       System.out.print(i+(j*2) + " ");
                    k--;
                    System.out.println();
                }
        }
}

Base no to the power exponent no

/*
Write a java program which will
accept base number and exponent
number from command line argument
and find the value of base to
the power of exponent
The exponent value may be negative
value.
*/

class p411b
{
   public static double power(double b,double p)
   {
        double i,v;
        v=1;
        for(i=1;i<=Math.abs(p);i++)
           v=v*b;
        if(p<0)
           v=1/v;
        return v;
   }
   public static void main(String args[])
   {
        double b,p;
        b=Double.parseDouble(args[0]);
        p=Double.parseDouble(args[1]);
        System.out.println("Result = " + power(b,p) );
   }
}

Recursive Function call at java

// Recursive Function call
// function call to itself
class recursive
{
  public static int sum(int n)
  {
    if(n==1)
      return 1;
    else
      return n+sum(n-1);
  }
  public static void main(String args[])
  {
    int a;
    a=sum(10);
    System.out.println(" Sum of 1 to 10 is "+a);
  }
}

How to add Menu Bar to JFrame


Wednesday, January 8, 2014

Simulation program to find the probability of getting 5 throwing a dice 100 times.

//Write a simulation program
//to find the probability of
//getting 5 throwing a dice
//100 times
class dice2
{
  public static void main(String args[])
  {
    int i,n,c=0;
    double r,p;
    for(i=1;i<=100;i++)
    {
      r=Math.random();
      n=(int)(r*6)+1;
      if(n==5) c++;
    }
    p=c/100.0;
    System.out.println("P(5)="+p);
  }
}

Tuesday, January 7, 2014

Finding the area of the triangle whose 3 sides are given. ....

class trianglearea
{
  public static void main(String args[])
  {
    int a,b,c;
    double s,area;
    a=Integer.parseInt(args[0]);
    b=Integer.parseInt(args[1]);
    c=Integer.parseInt(args[2]);
    s=(a+b+c)/2.0;
    System.out.println(s);
    area=Math.sqrt(s*(s-a)*(s-b)*(s-c));
    System.out.println("Area =" + area);
  }
}


The applied calculation method is shown underneath.



Understanding javax.swing.Timer

//When you want to do a process every one second
//you can use javax.swing.timer. You need to add
//actionLisenter for this like JButton
//the number n in the following will incremented
//and displayed in the JTextField after the timer
//has started for every one second

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class timertest extends JFrame implements ActionListener
{
  JTextField jtf1;
  JPanel pane;
  int n=1;
  javax.swing.Timer t1;
 
  public timertest()
  {
    super("Timer test");
    setSize(200,100);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jtf1=new JTextField(n+"",10);
    t1=new javax.swing.Timer(1000,this);
    t1.start();
    pane=new JPanel();
    pane.add(jtf1);
    setContentPane(pane);
    setVisible(true); 
  }
  public void actionPerformed(ActionEvent e)
  {
     if(e.getSource()==t1)
     {
         n=n+1;
         jtf1.setText(""+n);
     }
  }
  public static void main(String args[])
  {
    timertest one=new timertest();
  }
}

Monday, January 6, 2014

Beep from your speaker

//The following program will generate 5 beeps per 2 second.
class testforbeep
{
  public static void main(String args[])
  {
    int i;
    for(i=1;i<=5;i++)
    {
        try{Thread.sleep(2000);}catch(InterruptedException ie){}
        java.awt.Toolkit.getDefaultToolkit().beep();
    }
  }
}


To generate beep from your computer speaker, write the following code.
 
java.awt.Toolkit.getDefaultToolkit().beep();

How to generate random numbers.



// The following program will generate 
// random number like the numbers gained by throwing a dice.
class dice
{
  public static void main(String args[])
  {
    int i,n;
    double r;
    for(i=1;i<=10;i++)
    {
      r=Math.random();
      n=(int)(r*6)+1;
      System.out.println(n);
    }
  }
}

The following illustration show how to write code for generating random numbers starting from 17 to 20. This mean the generated random numbers will be 17, 18, 19, 20.