Setting tooltip for columns in a JTable

Hi!
I have a JTable inside a JScrollPane. How do I set tooltip for each columnheader of the JTable?
I have noted that if I don�t have the JTable within the JScrollPane, the columnheaders are not shown.
Regards
Johan

1) You need to set the tooptip text on the renderer for the column (yourTable.getColumnModel().getColumn(...).getHeaderRenderer()).
2) The header is a separate component to the table. When you add a table to a scroll pane it automatically adds the header to the scroll pane too. You can get the component (yourTable.getTableHeader()) and add it to your own container if you wish.

Similar Messages

  • Problem with setting tooltips for items of a JCombobox

    hi guys,
    I want to set tooltips for items of JComboBox & the code that i have written is given below , but the tooltip text is set for all the items of Nonitindustrycombo but the tooltips remain the same even for Nonitdesgcombo's items.
    Is that we need to refresh the ComboboxRenderer every time ?
    I am not able to trace out the exact reason for this,please if anyone can suggest me something regarding this would be of great use to me.
    class Searchpanel extends JPanel {
    String[] str = null;
    public SearchPanel(){
    Nonitindustrycombo.addItem("--Select--");
    ArrayList NonITindus = ERPModel.getAllNonitIndustry(); //gets all the items(strings) for Nonitindustrycombo
    for (Iterator iter = NonITindus.iterator(); iter.hasNext();) {
    String str = iter.next().toString();
    Nonitindustrycombo.addItem(str);
    SetTooltip(Nonitindustrycombo,NonITindus);
    Nonitdesgcombo.addItem("--Select---");
    ArrayList desg = ERPModel.getAllNonitDesg(); //gets all the items(strings) for Nonitdesgcombo
    for (Iterator iter = desg.iterator(); iter.hasNext();) {
    Nonitdesgcombo.addItem(iter.next());
    SetTooltip(Nonitdesgcombo,desg);
    class MyComboBoxRenderer extends BasicComboBoxRenderer
    public Component getListCellRendererComponent(JList list, Object value,
    int index, boolean isSelected,
    boolean cellHasFocus)
    if (isSelected)
    setBackground(list.getSelectionBackground());
    setForeground(list.getSelectionForeground());
    if (0 < (index))
    list.setToolTipText(str[index - 1]);
    else
    setBackground(list.getBackground());
    setForeground(list.getForeground());
    setFont(list.getFont());
    setText((value == null) ? "" : value.toString());
    return this;
    private void SetTooltip(JComboBox combo,ArrayList arr){
    str = (String []) arr.toArray (new String [arr.size ()]);
    combo.setRenderer(new MyComboBoxRenderer());
    public static void main(String[] args){
    new SearchPanel();
    Thanks ,
    vishal

    1) You where given a working example in your last posting on this topic. Compare your code with the working code to see whats different and fix it.
    2) The code you posted doesn't compile.
    3) You didn't use the "Code Formatting Tags" when you posted your code so it not readable.

  • Can i set only 1 column in a jtable to resize?

    Hi,
    I want to set only the columns with "Strings" as content to be resizable inside my jtable. and leave those which are ints, as a fixed size, but I haven't been able to find a way of setting the resizing options for a specific column...
    any ideas?

    You would need to check the column number and the data type in the column being resized and force it back to a set value if it was not a column with a string in it. Remember the user can swap the columns.
    rykk

  • Unable to set tooltip for item (sap.ui.core.Item)

    sap.ui.core.Item does not have the property 'tooltip'. But it borrows 'tooltip' property and setTooltip( ), getTooltip( ) methods from sap.ui.core.Element.
    Still, if I set the tooltip for item, it is not reflected. What might be wrong?
    Consider the following piece of code for example:
    var item = new sap.ui.core.Item({text:'Item'});
      item.setTooltip('tooltip');
      var oCollection = new sap.ui.ux3.Collection({ items: item
      var oCollectionInspector = new sap.ui.ux3.CollectionInspector({
      'fitParent' : false,
      'collections' : [
      new sap.ui.ux3.Collection({
      'title' : 'My Accounts',
      'items' : [ item]
      oCollectionInspector.placeAt('content');

    Tooltip is applied on the Item, but it seems Collection Inspector set its own tooltip for the Item. You can do something like this to set your own tooltip,
    var item = new sap.ui.core.Item("myItem",{text:'Item'});
    var oCollectionInspector = new sap.ui.ux3.CollectionInspector({
      'fitParent' : false,
      'collections' : [
      new sap.ui.ux3.Collection({
      'title' : 'My Accounts',
      'items' : [ item]
      oCollectionInspector.placeAt('content');
      oCollectionInspector.onAfterRendering = function(){
           sap.ui.ux3.CollectionInspector.prototype.onAfterRendering.apply(this,arguments);
           $('#myItem').attr('title','My Tooltip');

  • Various cell renders for cells (not for columns only) in JTable

    Hello, I need to create a property list with some various values (strings, colors, booleans) just like in Netbeans do. I will use JTable component, but I found I cannot have various cell editors for cells. In JTable cell editors can be only changed for COLUMNS. What sould I do?
    ps - is there any JPropertyPanel avaiable for free on the web?

    I had a similar problem recently whilst working on a Swing GUI designer (you're not doing the same are you? ;o). Presuming you already know how to create TableCellEditors you can use a very simple hack to achieve your goal.
    Either extend the JTable class and override the getCellEditor(int row, int column) method, or override the same method when constructing the JTable (this is what I did). You would need to write something like:
    JTable myTable = new JTable(){
        public TableCellEditor getCellEditor(int row, int column) {
            TableModel model = getModel();
            Object data = model.getValueAt(row, column);
            return getDefaultEditor(data.getClass());
    }The getCellEditor method is called by JTable whenever a cell is to edited, normally it would check to see if the TableColumn has an editor associated with it and return that, if there wasn't one it would get the class of data for the column and return the default editor for that type of class, which is similar to what it does here except it returns the default editor for the class of an individual item of datum.
    Now all you need to do is associate your TableCellEditors with the class types they are to edit with the setDefaultEditor(Class c, TableCellEditor editor) method of JTable. If, for instance, you had an editor for the Color class you would have a line something like:
    myTable.setDefaultEditor(Color.class, new ColorCellEditor());Good luck, and I hope this helps.
    MS.

  • Setting tooltip on column headers in a datagridview

    How to show the tooltip only on the column headers(not on other cells)  of a datagridview, when the datagridview is databound?

    Hi TuffyP,
    In order to display the tooltip only in the header cells but not other cells, you need to disable the built-in tooltip showing functionality, and defines a new tooltip and show it when your mouse enters into the column header cells.
    The following is steps and code:
    1.       Disable built-in tooltip by setting the showcelltooltip property of DataGridView to false.
    Code Snippet
      this.dataGridView1.ShowCellToolTips = false;
    2.       Add CellMouseEnter event handler for DataGridView.
    Code Snippet
    this.dataGridView1.CellMouseEnter += new DataGridViewCellEventHandler(dataGridView1_CellMouseEnter);
    3.       Implement dataGridView1_CellMouseEnter method
    Code Snippet
            void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
                if (e.RowIndex == -1 && e.ColumnIndex!=-1)
                    tt.SetToolTip( this.dataGridView1,this.dataGridView1.Columns[e.ColumnIndex].HeaderCell.FormattedValue.ToString());
                else
                    tt.Hide(this.dataGridView1);
    If you have problems with the code, please don’t hesitate to let me know.
    Best Regards,
    Bruce Zhou

  • Setting background for single row in JTable

    Hi,
    I have a table which uses the DefaultCellRenderer for cols0,1,3-5
    while column 2 uses a custom renderer.
    When user right clicks mouse on one of the rows i get the rowindex and colindex selected and tries to set background color for this row. but the whole table get painted(of course except 2nd column)...rather i need just the row to be colored.....any solution is greatly appreciated.the code is below....
    int rowIndex=table.rowAtPoint(p);
         int colIndex = table.columnAtPoint(p);           
         for (int i = 0; i < 6; i++) {                    
              if (i!=2){
                   DefaultTableCellRenderer r = (DefaultTableCellRenderer) table.getCellRenderer(rowIndex,i);
                   Component c = taskListTbl.prepareRenderer(r, rowIndex, i);
    c.setBackground(Color.yellow);
              }

    Maybe my reply in this posting will help:
    http://forum.java.sun.com/thread.jspa?forumID=57&messageID=1730267

  • Setting size for JPanel to fit JTable

    hi!
    Iam stuck with some grey area in JPanel or JScroolPanel with holds JTable, starting to get gray hair by trying to get rid of that
    public class MiniCalTopPane extends JPanel {
         private static final long serialVersionUID = 8490663735555155912L;
         private TableValues tv;
         private JTable table;
         private JLabel lable;
         public MiniCalTopPane() {
              //create pane with border layout
              super(new BorderLayout());
              //create components
              tv = new TableValues();
              table = new TableW(tv);
              lable = new JLabel("2006");
              lable.setSize(table.getWidth(), 25);
              System.out.println(table.getWidth());
              JScrollPane jsp = new JScrollPane(table);
              jsp.setPreferredSize(new Dimension(200,
                        (table.getHeight())));
              this.add(lable, BorderLayout.BEFORE_FIRST_LINE);
              this.add(jsp, BorderLayout.CENTER);
              setPreferredSize(jsp.getPreferredSize());
              setBackground(Color.GREEN);
              this.setOpaque(true);
    }JTable
    public class TableW extends JTable{
         private static final long serialVersionUID = 2480280947312015884L;
         private static final int ROW_HEIGHT             = 20;
        private static final int COL_WIDTH              = 20;
         public TableW(TableModel dm) {
              super(dm);
            this.changeSelection(0,0,false,false);
            this.setAutoCreateColumnsFromModel(true);
    //      initiate row height
            this.setRowHeight(ROW_HEIGHT);
            this.setAutoResizeMode(AUTO_RESIZE_ALL_COLUMNS);
            this.setRowSelectionAllowed(true);
            this.setColumnSelectionAllowed(true);
            //no dragible colums please!
            this.getTableHeader().setReorderingAllowed(false);
            //dont show grid in table
            this.setShowGrid(false);
            tableHeader.setBackground(Color.WHITE);
              TableColumnModel tcm = this.getColumnModel();       
            //add cutom render to
              for (int i = 0; i < this.getColumnCount(); i++) {
                   TableColumn tc = tcm.getColumn(i);
                   tc.setCellRenderer(new SmallCallRender());
         }I don't se whats is the proble, hope you can point me out :P
    and thanx in advance

    Well, the code you posted isn't executable, so we can't tell whats going on based on the code you posted.
    Here is a simple example that sizes the frame based on the tables size:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=627108
    If you want the frame to be bigger than the table then you can always add the table to the NORTH of the BorderLayout and set the color of the panel to whatever you want. Or, if you keep the table in the center then you need to set the background of the JViewport of the JScrollPane.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Setting ToolTips for items which are disabled.

    Folks,
    No offence meant if this is a repeat.
    I have a JPopupMenu with Action as its components.
    1) I have disabled certain menu items to false.
    2) I would like to use a ToolTipText to show a message 'You have no permission'
    when the user hovers over the menu items which are disabled/set to false
    3) I wrote my own ToolTipText,but what is happening is that I am getting the tool tip text
    for all menu items.
    Please can anyone help me in how to get tooltiptext for menu items which are enabled to false?
    Help much appreciated
    // JPopupMenu
    JPopupMenu pm = new JPopupMenu();
    // Add Action
    pm.add(new GraphAction());      
    pm.add(new DescendantsAction());
    pm.add(new DebugAction()).setEnabled(false);
    ToolTipTextForMenuItems.setToolTipForIndividualItem(pm.getComponent()) // Does not display any Tool Tip.
    pm.add(new ResetAction()).setEnabled(false);
    ToolTipTextForMenuItems.setToolTipTextForMenuItem(pm); // Shows ToolTipText for all menu items (disabled and enabled)
    ToolTip Code
    public class ToolTipTextForMenuItems {
    private static final String TOOL_TIP_TEXT = "You have no permission";
         public static void setToolTipTextForMenuItem(JPopupMenu popupMenu){
                 for (int i=0; i<popupMenu.getComponentCount(); i++){
                    Component c = popupMenu.getComponent(i);
                    if (c instanceof JComponent) {
                              ((JComponent)c).setToolTipText(TOOL_TIP_TEXT);
         public static void setToolTipForIndividualItem(Component c){
               if (c instanceof JComponent) {
                         ((JComponent)c).setToolTipText(TOOL_TIP_TEXT);
    }

    Yes,I have looked at the Abstract Action code sent in
    I have not used Action and Abstract Action before,hence if you can/could just
    modify this as per my requirement,then I can enhance on this.
    No offence meant for the above
    Thanks

  • Tooltip for column header sorting

    If I enable column header sorting, is there a way to put a tooltip (HTML 'title' property, I guess) on the column header saying 'Click here to sort by this column'?
    The triangle image shows this alt text but that triangle image is shown only next to the column that is currently sorted, not all the columns.
    [My column headings come from a custom PL/SQL function, not declaratively on the Report Attributes page]
    Thanks

    See
    http://htmldb.oracle.com/pls/otn/f?p=24317:28
    The following seems to work.
    Add this javascript to the Page Attributes Header section
    <script type="text/javascript">
    function AddTooltip()
    var l_link;
    var l_hrefs=document.links;
    for (var i=0; i < l_hrefs.length; i++) {
       l_link=l_hrefs;
    if (l_link.href && l_link.href.indexOf('fsp_sort_')>=1) {
    l_link.title="This is a tooltip"
    </script>
    Then call it from the onLoad as follows
    onLoad="AddTooltip();"
    Seems to work like a charm.
    Thanks
    BTW, anyone know how to prevent the [ i ] inside a [ pre ] from being interpreted as an italic tag? I thought all text inside a PRE tag is left untouched?

  • Set a tooltip for a shape, not a button

    Hi everybody,
    Hope you are all ok wherever you are :)
    I have this little problem guys; I want to set a tooltip button in my application but the problem is that i'm not using buttons but shapes instead, in which shapes i've added mouse click handle code.
    I need when the mouse goes over these shapes-buttons i have, some tooltip text to be displayed. I've tried to create a rectangle and display the small text i want into that rectangle and then call repaint for restoring the program to the previous state before the tooltip display, but unfortunately it is too slow.
    Can you please help me out of that? Can you give a way of setting tooltips for shapes instead of buttons?
    Any help would be appreciated.
    Thanks,
    -John

    Your trying to set a tooltip for a given area on some JComponent defined by a Shape which holds the points that make up the border of the Shape, like GeneralPath or something like that? Is that what you mean? I'm not sure but I think you can use Shape.contains(Point2D ...) without actually have drawn the Shape, so that you can test where the mouse is on your JComponent, then check contains to see if a tooltip needs to be displayed. You'll have to write your own tooltip frame that's not dependent on a JComponent, but thats fairly straightforward. Don't know if this is any help to you, but its a possibility.
    Tom
    ioannisc: the OP talks about the use of Shape's, where did subclasses of JComponent come into it?!

  • Hide a column in a JTable

    Hi All, hope you can help,
    I want to hide the last column of my table, but still access its data. Inside the last column certain information is present, the cell tooltips.
    In my extended JTable class my method getToolTipText looks like this:
            // implement table cell tool tip.
            public String getToolTipText(MouseEvent e) {
                String tip             = null;
                Point  p               = e.getPoint();
                int    rowIndex        = rowAtPoint(p);
                int    colIndex        = columnAtPoint(p);
                int    realColumnIndex = convertColumnIndexToModel(colIndex);
                if(rowIndex>=0 && rowIndex<=lastRow) {
                    if(realColumnIndex==0) {
                        MiniModel mml = (MiniModel)getValueAt(rowIndex, 5); // exception here
                        tip = "<html>" + replaceCRLFtoBR(mml.getComment()) + "</html>"; // replaceCRLFtoBR = custom method to replace \n by <br>
                    } else {
                        tip = columnTips[realColumnIndex]; // constant
                return tip;
            }As you can see at column 5 an object MiniModel is present containing the tooltip for column 0.
    When I use the method removeColumn on column 5 on my extended JTable variable, I get an java.lang.ArrayIndexOutOfBoundsException at the marked position and in more detail on getValueAt.
    As I read everywhere the actual data is not removed (only from the view) I wonder what I'm doing wrong...
    Michiel

    Thanks for the advice, I will prepare better next time, here is my sscce :
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    public class TableHide extends JFrame {
        private static final String[] colNames    = {"Column 1", "Column 2", "Column 3"};
        private static final String[] colHeadTips = {"Header tip 1", "Header tip 2", "Header tip 3"};
        private ExtTableModel    myTableModel;
        private ExtTable         myTable;
        private JScrollPane      myScrollPane;
        private int              lastRow = 0;
        // for example
        private MiniModel mmlRow1 = new MiniModel(1, "cell comment");
        private MiniModel mmlRow2 = new MiniModel(2, "other cell comment");
        // constructor
        public TableHide() {
            this.setTitle("Table column hide test");
            this.setResizable(true);
            this.setLayout(new BorderLayout());
            // build table containing all extended Model's id and name
            myTableModel = new ExtTableModel(null, colNames);
            myTable      = new ExtTable(myTableModel);
            myTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
            myTable.setPreferredScrollableViewportSize(new Dimension(500, 130));
            myTable.setFillsViewportHeight(true);
            myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            myTable.getTableHeader().setReorderingAllowed(false);
            myScrollPane = new JScrollPane(myTable);
            this.add(myScrollPane, BorderLayout.CENTER);
            // add some rows, in real application this is more complex
            myTableModel.insertRow(0, new Object[]{ "Basic string", new Boolean(false), mmlRow1 }); lastRow++;
            myTableModel.insertRow(0, new Object[]{ "Other string", new Boolean(true) , mmlRow2 }); lastRow++;
            myTable.setAutoCreateRowSorter(true);
            myTable.getRowSorter().toggleSortOrder(0);
            // this causes the exception
            myTable.removeColumn(myTable.getColumnModel().getColumn(2));
            this.setSize(new Dimension(500,200));
        // inner class to provide an own table model for the extended Models showed on screen. used for booleans
        class ExtTableModel extends DefaultTableModel {
            public ExtTableModel(Object[][] tableData, String[] columnNames) {
                super(tableData, columnNames);
            public boolean isCellEditable(int row, int col) {
                return false;
            public Class getColumnClass(int column){
                Object value=this.getValueAt(0,column);
                return (value==null?Object.class:value.getClass());
        // inner class to privide column header tooltips and cell tooltips
        class ExtTable extends JTable {
            public ExtTable(ExtTableModel extModel) {
                super(extModel);
            // implement table cell tool tip.
            public String getToolTipText(MouseEvent e) {
                String tip             = null;
                Point  p               = e.getPoint();
                int    rowIndex        = rowAtPoint(p);
                int    colIndex        = columnAtPoint(p);
                int    realColumnIndex = convertColumnIndexToModel(colIndex);
                if(rowIndex>=0 && rowIndex<=lastRow) {
                    if(realColumnIndex==0) {
                        MiniModel mml = (MiniModel)getValueAt(rowIndex, 2);
                        tip = mml.getMml_comment();
                    } else {
                        tip = "Some other tooltip function";
                return tip;
            // implement table header tool tip.
            protected JTableHeader createDefaultTableHeader() {
                return new JTableHeader(columnModel) {
                    public String getToolTipText(MouseEvent e) {
                        Point  p         = e.getPoint();
                        int    index     = columnModel.getColumnIndexAtX(p.x);
                        int    realIndex = columnModel.getColumn(index).getModelIndex();
                        return colHeadTips[realIndex];
        // simplified class for usage inside a cell
        public class MiniModel {
            private int        mml_id;
            private String     mml_comment;
            public MiniModel(int mml_id, String mml_comment) {
                this.mml_id      = mml_id;
                this.mml_comment = mml_comment;
            public String getMml_comment() {
                return mml_comment;
            public String toString() {
                return Integer.toString(mml_id); // called when object is displayed
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    new TableHide().setVisible(true);
    }When you show the last column the program works fine. Goal is to have the last column available since it contains extra information about the row, but not to show it.

  • How can I add custom right-click-menu to column headers in JTable?

    Can anyone point me to a topic on how to customize a popup menu for column headers in JTable? Specifically, I want to add things like "auto-size column" and "hide column".
    Thanks,
    Matt

    Right-click on your table.  Then go to Advanced->Runtime Shortcut Menu->Edit.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • DVT Graph - setting tooltip dynamically.

    Hello,
    How can I set tooltip for a graph in java class?
    I know setting tooltip in ".jsp" but I need to set it in java class.
    Thanks,
    Mina

    Hi Sumit,
    It worked creating the graph programmatically using the code below.
    Thanks for your help.
    Eduardo
    Vector graphs = new Vector();
    OAGraphTableBean graphTable = (OAGraphTableBean)webBean;
         Dictionary graphBarDetails = new ArrayMap(10);
    graphBarDetails.put("AGRFUNCTION", "none");
    graphBarDetails.put("GRAPHTYPE", "vertical clustered bar");
    graphBarDetails.put("GRAPHTITLE", "Cost Bar Graph");
    graphBarDetails.put("YAXISLABEL", "Allocation Amount");
    graphBarDetails.put("GRAPHSIZE", "medium");
    graphBarDetails.put("CUSTGRAPHWIDTH", "");
    graphBarDetails.put("CUSTGRAPHHEIGHT", "");
    graphBarDetails.put("DISPLAYTOOLTIP", BooleanUtils.getBoolean(true));
    graphBarDetails.put("XAXISLABEL", "");
    graphBarDetails.put("DRILLDOWNURL", "");
    graphBarDetails.put(DISPLAYED, BooleanUtils.getBoolean(true));
    Vector graphCols = new Vector();
    for(int j=0; j<2; j++) {
    Dictionary graphData = new ArrayMap(5);
    graphData.put("VIEWUSAGENAME", pViewUsage);
    if(j ==0) {
    graphData.put("VIEWATTRIBUTENAME", "AllocatedAmount");
    graphData.put("GRAPHDATASTYLE", "data");
    graphData.put("GRAPHDATAPROMPT", "Allocation Amount");
    else {
    graphData.put("VIEWATTRIBUTENAME", "AllocName");
    graphData.put("GRAPHDATASTYLE", "groupLabels");
    graphData.put("GRAPHDATAPROMPT","");
    graphData.put("GRAPHSTOCKVALUE","none");
    graphCols.addElement(graphData);
    graphBarDetails.put("GRAPHDATACOLS", graphCols);
    graphs.addElement(graphBarDetails);
    graphTable.setGraphDetails(graphs);

  • Tooltip for mousedragged

    I did a program in applet..I want to set tooltip for the drawing..i.e.,when the oval is dragged its new co-ordinates should be displayed by using the tooltip..How can i do this..
    .import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Line2D;
    import java.awt.geom.Point2D;
    import java.text.DateFormat;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.BorderLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    public class mouseevent extends JApplet
          private static final int BALL_DIAMETER = 40; // Diameter of ball
        //--- instance variables
        /** Ball coords.  Changed by mouse listeners.  Used by paintComponent. */
        private int _ballX     = 450;   // x coord - set from drag
        private int _ballY     = 50;   // y coord - set from drag
        /** Position in ball of mouse press to make dragging look better. */
        private int _dragFromX = 0;    // pressed this far inside ball's
        private int _dragFromY = 0;    // bounding box.
        /** true means mouse was pressed in ball and still in panel.*/
        private boolean _canDrag  = false;
        JLabel label;
        String s= "aswedfrtyhgqwsadrftlopqasnhfgrchildnode1";   
        int width = s.length();   
        int border = 2;    int margin = 10;   
        int rectx = margin+border,recty =margin+border+63;   
        int rectwidth = 8, rectheight = 6;   
        int imgborder = 10;   
        int imgline1 = 300;  
        int labellocx = rectx+imgborder+13;  
        int labellocy = recty+imgborder-1;   
        int circlex = rectx+rectwidth;
        int circley = recty+rectheight;  
        int x =rectx+rectwidth+10;  
        int y = recty+rectheight+10;
        int x1 = x+17; 
        int y1 = y+20;  
        int titlebarx= 300;
        int titlebary = 40;  
        boolean title = true;
        String date[] = {"0","4","8","12","16","20","24"}; 
        String day[] = {"Mon","Tue","Wed","Thu","Fri","Sat"};
        int width1 = 180;
    //    int f2= x+168;
        int n =180;
    //    int dayx = 385;
        long From ;
        long To ;
        ArrayList dateList;
         int rect1x= 300;
        int rect1y = 100;
        int rect1width= 50;
        int rect1heigth = 50;
        boolean candrag = false;
        public void init()     
            Container cont = getContentPane();   
            cont.setLayout(new BorderLayout());
            // to see the scrollpane, the scrollpane has to be smaller        
            // then the component held within its viewport             
            setPreferredSize(new Dimension(300, 300));             
            JScrollPane scroll = new JScrollPane();              
            getContentPane().add(scroll, BorderLayout.CENTER);        
            scroll.getViewport().add(new Imagepanel());       
    private class Imagepanel extends JPanel implements MouseListener,MouseMotionListener
            JScrollPane scroll = new JScrollPane();      
            Rectangle rect = new Rectangle(rectx,recty,rectwidth,rectheight);
            Rectangle rect1  = new Rectangle(rect1x,rect1y,rect1width,rect1heigth);
            Ellipse2D.Double circle = new Ellipse2D.Double(_ballX,_ballY,BALL_DIAMETER,BALL_DIAMETER);   
            Ellipse2D.Double circle1 = new Ellipse2D.Double(x+10,y+10,4,4);    
            boolean selected = false;  
            boolean selected1 = false;     
            int w ;     
        Imagepanel()       
            // setting the component to be largenr than the scrollpane           
            // just so we'll see scrollbars.
            setPreferredSize(new Dimension(32710,32710));      
            scroll = new JScrollPane();     
            add(scroll);                 
            addMouseListener(this);       
            addMouseMotionListener(this);
            setBorder(BorderFactory.createLineBorder(Color.BLACK, border));          
        protected void paintComponent(Graphics g)         
            int n = 168;
            int x = 300;
            int x1=300;
            int x2=x;
            int daydx=(width1/2);
            int dayx =(daydx+x);
            int f2= x+n;
            From = new java.util.GregorianCalendar(2007,01,01).getTime().getTime();
            To = new java.util.GregorianCalendar(2007,06,30).getTime().getTime();
            double Difference = To-From;
            long days = Math.round((Difference/(1000*60*60*24)));
            int noday = (int)days;
            Date fromDate = new java.util.GregorianCalendar(2007,01,01).getTime();
            Date toDate = new java.util.GregorianCalendar(2007,06,30).getTime();
            super.paintComponent(g);            
            Graphics2D g2 = (Graphics2D) g;             
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);       
            Font font = new Font("Ariel",Font.PLAIN,11); 
            Font font1 = new Font("Ariel",Font.PLAIN,9);
            g2.fillOval(_ballX, _ballY, BALL_DIAMETER-20, BALL_DIAMETER-20);
            g2.setBackground(Color.GRAY);
            //drawing the tilte bar     
            g2.setBackground(Color.WHITE);  
            g2.drawLine(imgline1,0,imgline1,getHeight()); 
            g2.setPaint(new Color(0,128,192));
            g2.fillRect(imgborder,imgborder,290,45);
            //g2.drawLine(margin,margin,titlebarx,titlebary);              
            //drawing the root node and labeling      
            g2.draw(rect);
            g2.setPaint(Color.WHITE);
            g2.drawLine(margin,margin,titlebarx,titlebary); 
            g2.drawString("RESOURCE",40,40);       
            g2.drawString("TIME",200,25);
            g2.setPaint(Color.green);
            g2.drawString("sadasd",344,22);
            g2.draw(circle);
            rect.setLocation(rectx,recty);      
            rect.setSize(rectwidth,rectheight);
            g2.setPaint(Color.BLACK);
            g2.drawString(" aswedfrtyhgqwsadrftlopqasnhfgrchildnode1",rectx+rectwidth+05,recty+rectheight);               
            for (int i = 0;i<noday;i++)
            Calendar  c = Calendar.getInstance(); // current date
                c.add(Calendar.DATE, i); // add one day
                SimpleDateFormat sdf = new  SimpleDateFormat("MM/dd/yy"); // use the pattern: day_of_month
                String str = sdf.format(c.getTime()); // fromat the date to string
                System.out.println(str); // print it at the console
                for (int j=0;j<6;j++)
                    g2.setFont(font1);
                    g2.drawLine(x1,40,x1,35);
                    g2.drawString(date[j],x1,35);
    //              g2.drawString(day[j],dayx,20);
                    g2.drawString("24",f2,35);
                    f2+=width1;
                    x1+=30;
    //              dayx=+170;
                g2.drawRect(x,10,width1,30);
                x+=width1;
                g2.drawString(str,dayx,20);
                dayx+=180;
            for(int k=0;k<n;k++)
                for(int l=0;l<6;l++)
                Calendar c = Calendar.getInstance(); // current datem
                c.add(Calendar.DAY_OF_WEEK, k); // add one day
                SimpleDateFormat sdf = new SimpleDateFormat("EEE"); // use the pattern: day_of_month
                String str = sdf.format(c.getTime()); // fromat the date to string
                System.out.println(str); // print it at the console
                g2.drawString(str,dayx,5);
    //          g2.drawString(day[l],dayx,20);
                dayx+=180;
            //dividing the drawing panel      
            //drawing for the click event       
            if(selected)       
                Color color = Color.orange; 
                g2.fill(circle);
                g2.draw(circle);          
                //              g2.drawRoundRect(x+30,y+15,200,12,5,5);        
                g2.drawString("aswedfrtyhgqwsadrftlopqasnhfgrchildnode1",x+15,y+5);     
                g2.drawRect(300,y,100,15);      
            if(selected1)      
                g2.setFont(new Font("Arial",Font.PLAIN,12)); 
                g2.fill(circle1);
                g2.draw(circle1);           
                g2.drawString(" aswedfrtyhgqwsadrftlopqmasnhfgrchildnode1",x1+15,y1+5);  
        public void update(Graphics g)    
            paint(g);   
        public void mouseClicked(MouseEvent e)          
            //imagePaneMouseClicked(e);              
        private void imagePaneMouseClicked(MouseEvent e)        
            Point p = e.getPoint();         
            if (rect.contains(p))                  
                if (!selected)              
                    selected = true;        
                    repaint();               
            if(circle.contains(p))     
                if(!selected1)           
                    selected1 = true;    
                    repaint();           
            if(rect.contains(p)) 
                if(e.getClickCount() == 2)    
                    selected = false;  
                    repaint();      
        public void mousePressed(MouseEvent e)        
             int x = e.getX();   // Save the x coord of the click
            int y = e.getY();   // Save the y coord of the click
            if (x >= _ballX && x <= (_ballX + BALL_DIAMETER)
                    && y >= _ballY && y <= (_ballY + BALL_DIAMETER)) {
                _canDrag = true;
                _dragFromX = x - _ballX;  // how far from left
                _dragFromY = y - _ballY;  // how far from top
            } else {
                _canDrag = false;
        public void mouseReleased(MouseEvent e) {        }               
        public void mouseEntered(MouseEvent e) {        }          
        public void mouseExited(MouseEvent e) { 
            candrag = false;
            public void mouseDragged(MouseEvent e) {
              if (_canDrag)
              {   // True only if button was pressed inside ball.
                //--- Ball pos from mouse and original click displacement
                _ballX = e.getX() - _dragFromX;
                _ballY = e.getY() - _dragFromY;
                //--- Don't move the ball off the screen sides
                _ballX = Math.max(_ballX, 0);
                _ballX = Math.min(_ballX, getWidth() - BALL_DIAMETER);
                //--- Don't move the ball off top or bottom
                _ballY = Math.max(_ballY, 0);
                _ballY = Math.min(_ballY, getHeight() - BALL_DIAMETER);
                this.repaint(); // Repaint because position changed.
                this.add(label);
                label.setText(""+_ballX+_ballY);
                label.setLocation(_ballX,_ballY);
            public void mouseMoved(MouseEvent e) {
    }

    The label is not getting displayed...the program throws some exception...
    Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
    at java.awt.Container.addImpl(Container.java:1015)
    at java.awt.Container.add(Container.java:351)
    at javaapplication5.mouseevent$Imagepanel.mouseDragged(mouseevent.java:346)
    at java.awt.Component.processMouseMotionEvent(Component.java:5536)
    at javax.swing.JComponent.processMouseMotionEvent(JComponent.java:3144)
    at java.awt.Component.processEvent(Component.java:5257)
    at java.awt.Container.processEvent(Container.java:1966)
    at java.awt.Component.dispatchEventImpl(Component.java:3955)
    at java.awt.Container.dispatchEventImpl(Container.java:2024)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3909)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
    at java.awt.Container.dispatchEventImpl(Container.java:2010)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

Maybe you are looking for