Java Basic Problems

JTable Cell Click Event: Click on the JTable Cell and show the Value of that cell.

Sometimes while programming we may need to check and show the value of JTable Cell in click event.

Here, in the given example, I did the coding in such a way that while clicking on a cell of  JTable

It will show the value of that JTable cell in MessageDialog Box.

Code Example:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.table.*;

class SimpleTableTest extends JFrame

                {

private JPanel topPanel ;

private JTable table;

private JScrollPane scrollPane;

private String[] columnNames= new String[3];

private String[][] dataValues=new String[3][3] ;
Continue reading “JTable Cell Click Event: Click on the JTable Cell and show the Value of that cell.”

Java Basic Problems

Java :How to know in which Row and Column I have clicked on JTable

In this post I have shared you the solution about how to know in which Row and Column of JTable I have clicked.

According to the solution, wherever you have clicked on the JTable the result will be shown using

Message Dialog Box (Check the OUTPUT picture below).

 

Code Example:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.table.*;

class SimpleTableTest extends JFrame

                {

private JPanel topPanel ;

private JTable table;

private JScrollPane scrollPane;

private String[] columnNames= new String[3];

private String[][] dataValues=new String[3][3] ;

public SimpleTableTest()

    {

setTitle(“JTable Cell Click”);

setSize(300,300);

topPanel= new JPanel();

topPanel.setLayout(new BorderLayout());

getContentPane().add(topPanel);

setDefaultCloseOperation(EXIT_ON_CLOSE);

columnNames=new String[] {“Column 1” , “Column 2” , “Column 3”};

 dataValues = new String[][]   {

                                    {“1″,”2″,”3”},

                                    {“4″,”5″,”6”},

                                    {“7″,”8″,”9″}

                                          };

 TableModel model=new myTableModel();

 table =new JTable( );

 table.setRowHeight(50);

 table.setModel(model);

 scrollPane=new JScrollPane(table);

  topPanel.add(scrollPane,BorderLayout.CENTER);   

  table.addMouseListener(new java.awt.event.MouseAdapter()

            {

public void mouseClicked(java.awt.event.MouseEvent e)

{

int row=table.rowAtPoint(e.getPoint());

int col= table.columnAtPoint(e.getPoint());

JOptionPane.showMessageDialog(null,”You have Clicked on Column :” +(col+1)+ ” : and Row : ” +(row+1));

System.out.println(table.getValueAt(row,col).toString());

}

}

);

}

            public class myTableModel extends DefaultTableModel

                                                {

                                                    myTableModel( )

                                                 {

                                                  super(dataValues,columnNames);

                                                  System.out.println(“Inside myTableModel”);

                                                 }

                                                public boolean isCellEditable(int row,int cols)

                                                 {

                                   return false;                                                                                         

                                                }

                                                }         

            public static void main(String args[])

            {

            SimpleTableTest mainFrame=new SimpleTableTest();

            mainFrame.setVisible(true);

            }         

                 }
OUTPUT:

JTable Row and Column Click

Java Basic Problems

JTable Java : How to make JTable cells editable or not editable using DefaultTableModel.

Here is a little solution to make the cells of JTable  editable or not editable.

Here I have coded to make the cells of  Column-1 not editable but cells of Column-2 and Column-3 are editable.

Code Example:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.table.*;

class SimpleTableTest extends JFrame

                {

private JPanel topPanel ;

private JTable table;

private JScrollPane scrollPane;

private String[] columnNames= new String[3];

private String[][] dataValues=new String[3][3] ;

public SimpleTableTest()

    {

setTitle(“JTable Cell Not Editable”);

setSize(300,300);

topPanel= new JPanel();

topPanel.setLayout(new BorderLayout());

getContentPane().add(topPanel);

setDefaultCloseOperation(EXIT_ON_CLOSE);

columnNames=new String[] {“Column 1” , “Column 2” , “Column 3”};

 dataValues = new String[][]   {

                        {“1″,”2″,”3”},

                        {“4″,”5″,”6”},

                        {“7″,”8″,”9”}

                                            };

 TableModel model=new myTableModel();

 table =new JTable( );

 table.setRowHeight(50);

 table.setModel(model);

 scrollPane=new JScrollPane(table);

 topPanel.add(scrollPane,BorderLayout.CENTER);    

            }

            public class myTableModel extends DefaultTableModel

                        {

                myTableModel( )

                         {

                          super(dataValues,columnNames);

                          System.out.println(“Inside myTableModel”);

                                     }

                        public boolean isCellEditable(int row,int cols)

                         {

                           if(cols==0 ){return false;}

      //It will make the cells of Column-1 not Editable

                              return true;                                                                                    

                                                }

                                                }         

            public static void main(String args[])

            {

            SimpleTableTest mainFrame=new SimpleTableTest();

            mainFrame.setVisible(true);

            }         

            }

OUTPUT:

JTable cell editable or non editable

Java Basic Problems

Java:How to add data to JTable by declaring and using DefaultTableModel.

If you want to add data in JTable by using DefaultTableModel then this solution will be helpful for you. But,if you don’t want to use DefaultTablelModel then CLICK HERE.

Code Example:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.table.*;

class SimpleTableTest extends JFrame

                {

private JPanel topPanel ;

private JTable table;

private JScrollPane scrollPane;

private String[] columnNames= new String[3];

private String[][] dataValues=new String[3][3] ;

public SimpleTableTest()

    {

setTitle(“JTable and DefaultTableModel”);

setSize(300,300);

topPanel= new JPanel();

topPanel.setLayout(new BorderLayout());

getContentPane().add(topPanel);

setDefaultCloseOperation(EXIT_ON_CLOSE);

columnNames=new String[] {“Column 1” , “Column 2” , “Column 3”};

 dataValues = new String[][]   {

                                                                        {“1″,”2″,”3”},

                                                                        {“4″,”5″,”6”},

                                                                        {“7″,”8″,”9”}

                                                                    };

  TableModel model=new myTableModel(“owntable”);

  table =new JTable( );

  table.setRowHeight(50);

  table.setModel(model);

  scrollPane=new JScrollPane(table);

  topPanel.add(scrollPane,BorderLayout.CENTER);   

            }

            public class myTableModel extends DefaultTableModel

                                                                                    {

                                                                                     myTableModel(String tname)

                                                                                                 {

                                                                                       super(dataValues,columnNames);

                                                                                       System.out.println(“Inside myTableModel”);

                                                                                                 }

                                                                                    public boolean isCellEditable(int row,int cols)

                                                                                                 {

                                                                                                  return true;

                                                                                                 }

                                                                                    }         

            public static void main(String args[])

            {

            SimpleTableTest mainFrame=new SimpleTableTest();

            mainFrame.setVisible(true);

            }         

                        }

                        

OUTPUT:

JTable using DefaultTableModel

Java Basic Problems

Java: How to know it is AM or PM using Time / DateFormat in java.

If you are trying to separate the AM or PM from the Time or DateFormat using java, then the following solution will be helpful for you.

Code Example:

import java.text.*;

import java.util.*;

import java.util.StringTokenizer;

class DateFormatDemo {

public static void main(String args[]) {

Date date = new Date();

DateFormat df;

df = DateFormat.getDateInstance(DateFormat.SHORT);

System.out.println(“\n”);

System.out.println(“Short form: ” + df.format(date));

df = DateFormat.getDateInstance(DateFormat.LONG);

System.out.println(“Long form: ” + df.format(date));

System.out.println();

df = DateFormat.getTimeInstance(DateFormat.SHORT);

System.out.println(“Short form: ” + df.format(date));

df = DateFormat.getTimeInstance(DateFormat.LONG);

System.out.println(“Long form: ” + df.format(date));

String daate=df.format(date).toString();

System.out.println(“\n”);

StringTokenizer st_time=new StringTokenizer(daate,” “);

                         String timeStr[] = new String[7];

                         int i=0;

                         while ( st_time.hasMoreElements()) {

                         timeStr[i++] = st_time.nextToken();   

                         }

System.out.println(“It is AM or PM ?:”+timeStr[1]);

}

}

OUTPUT:

AM or PM java

Java Basic Problems

Java: Final Variables, Methods and Final Classes

In my last post I have shared about  JButton and JMenuItem ActionListener.

Here I have shared about Final Variables, Methods and Final Class.

By default all methods and variables can be overridden in subclasses.

It is possible to prevent the subclasses from overriding the members of super class; we can declare them as final using the keyword final as a modifier.

The value of a final variable  can never be changed.

Ex : final int age=45;

Making a method final ensures that the functionality defined in this method will never be altered in any way.

Ex: final void age()

{

——

}

Final Classes

It may happen that  we want to prevent a class being subclassed for security reasons or for any other reason related to our software . We can do it easily using final class.  So,  the class that cannot be subclassed is called a final class.

Ex: final class age

{

}

If we try to inherit the above class will cause an error and the compiler will not allow it. It prevents any unwanted extension to the class.

Java Basic Problems

Java: How to add TextField (JTextField)in java?

Suppose you are trying to prepare a Calculator using java programming language and also you are trying to prepare your calculator using JTextField (javax.swing.JTextField).

Here I have given a little example how to use TextField (JTextField) of java in JFrame.

Using the following code you will be able to learn how to put or use or show 🙂 TextField (JTextField) in java  and how to position the TextField in JFrame.

 

 Here is the Code Example:

import javax.swing.*;

import java.awt.Dimension;

import java.awt.Toolkit;

public class Calc extends JFrame

{

   JTextField ques, answer;

   private Toolkit toolkit;

        public Calc()

                        {                     

                        JPanel panel =new JPanel();

        getContentPane().add(panel);

                        panel.setLayout(null);

                        // UIManager.LookAndFeelInfo laf[]=UIManager.getInstalledLookAndFeels();

                setSize(300,200);

                setTitle(“Easy Calculator”);

                setDefaultCloseOperation(EXIT_ON_CLOSE);

                 toolkit=getToolkit();

                Dimension size=toolkit.getScreenSize();

                 setLocation(size.width/2-getWidth()/2, size.height/2-getHeight()/2);

                 ques=new JTextField();

                 answer=new JTextField();

        JButton calculate=new JButton(“Calculate”);

        calculate.setBounds(75,50,90,30);

        ques.setBounds(10,10,220,30);     // Positioning of TextField(JTextField)

        answer.setBounds(10,100,220,30); //Positioning  of TextField(JTextField)

        panel.add(calculate);

        panel.add(ques );    // Adding TextField(JTextField) in JPanel

        panel.add(answer );  // Adding TextField(JTextField) in JPanel

                                       }

          public static void main(String args[])

              {

              Calc  cal=new Calc();

              cal.setVisible(true);

              }

}

Java Basic Problems

Java: Add value to a vector which is inside another vector.

Sometimes what we do in java programming, we add value to a vector and then adds that vector to another vector (Vector inside another vector).

For example

(“X”,”Y”,”Z”) is in Vector    name

name.add(“X”);

name.add(“Y”);

name.add(“Z”);

(“M”, “N”,”O”) is in Vector name1

name1.add(“M”);

name1.add(“N”);

name1.add(“O”);

Add  this  name and  name1 vector in nameContainer Vector

nameContainer.add(name);

nameContainer.add(name1);

So, if you want to add another value  or    modify  the vector  name and name1  which are inside nameContainer Vector,  do the following  according to the given code.

Code Example

 import java.util.Vector;

public class VectorDemo

{

 VectorDemo()

{

Vector name=new Vector();

Vector name1=new Vector();

Vector name2=new Vector();

name2.add(“Its me”);

Vector nameContainer=new Vector();

name.add(“X”);

name.add(“Y”);

name.add(“Z”);

nameContainer.add(name);

name1.add(“M”);

name1.add(“N”);

name1.add(“O”);

nameContainer.add(name1);

System.out.println(“Before NameContainer Value:”+nameContainer.get(0));

((Vector)nameContainer.get(0)).add(“HI”);

System.out.println(“name get 0 and 1:”+name.get(0)+” “+name.get(1));

System.out.println(“AfterNameContainer Value:”+nameContainer.get(0));

((Vector)nameContainer.get(0)).add(name2.get(0));

System.out.println(“AfterNameContainer Value:”+nameContainer.get(0).toString());

}

public static void main(String args[])

{

VectorDemo x=new VectorDemo();

}

}

OUTPUT: