How to make a cell in a JTable to be uneditable and handle events

I tried many things but failed,How do you make a cell in a JTable to be uneditable and also be able to handle events>Anyone who knows this please help.Thanx

Hello Klaas2001
You can add KeyListener ,MouseListener
Suppose you have set the value of cell using setValueAt()
table.addKeyListener(this);
public void keyTyped(KeyEvent src)
String val="";
int r= table.getEditingRow();
int c= table.getEditingColumn();
val=table.getValueAt(r,c).toString();
if (r!=-1 && c!=-1)
TableCellEditor tableCellEditor = table.getCellEditor(r, c);
tableCellEditor.stopCellEditing();
table.clearSelection();
table.setValueAt(val,r,c);
public void keyReleased(KeyEvent src)
public void keyPressed(KeyEvent src)
table.addMouseListener(this);
public void mouseClicked(MouseEvent e)
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e)
public void mousePressed(MouseEvent e)
public void mouseReleased(MouseEvent e)
if(e.getClickCount()>=2)//Double Click
table.clearSelection();
int r= table.getEditingRow();
int c= table.getEditingColumn();
if (r!=-1 && c!=-1)
TableCellEditor tableCellEditor = table.getCellEditor (
r,c);
tableCellEditor.stopCellEditing();
table.clearSelection();
table.setValueAt("",r,c);
}//Mouse Released
You can remove keyListener and Mouse Listener whenever You want to edit
then add it later.
Regarding handling events implement javax.swing.event.TableModelListener
table.getModel().addTableModelListener(this);
public void tableChanged(javax.swing.event.TableModelEvent source)
TableModel tabMod = (TableModel)source.getSource();
     switch (source.getType())
case TableModelEvent.UPDATE:
     break;
     }//Table Changed Method
//This method gets fired after table cell value is changed.

Similar Messages

  • How to make editing cell to show up caret and taking keyboard event

    Hello everyone:
    I have the following problem with table editing.
    1. using mouse clicking, the editing cell will have cursor and taking keyboard event.(no problem with it)
    2. just type in data, it will show up in the selected cell, but the editing cell do not have cursor visible and also do not fire the keyboard event.
    I have problem with this one. So how to make editing cell to have caret visible and taking keyboard event.
    Thank you very much!
    --tony                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Hi,
    you should subclass JTable and overwrite two methods.
    1. protected boolean processKeyBinding(javax.swing.KeyStroke ks,
    java.awt.event.KeyEvent e,
    int condition,
    boolean pressed)
    to store the current keyboard event,
    2.public boolean editCellAt(int row,int column,java.util.EventObject e)
    to fix the problem with isCellEditable and curret position and direct the event into proper place.

  • How to make table cell have certain width

    Hi
    i have 3 cells when i write text in any cell it effects the
    width of other cells !!!
    how to make every cell have certain? i mean i want to wrap
    the text not to effect the cell width
    thanks in advance.

    Hi Mac,
    Try this
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
    Transitional//EN">
    <HTML><HEAD><TITLE>Home</TITLE>
    <META http-equiv=Content-Type content="text/html;
    charset=iso-8859-1">
    <style>
    .text-content-green {
    FONT-SIZE: 11px;
    COLOR: #a5a834;
    LINE-HEIGHT: 20px;
    FONT-STYLE: normal;
    FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif;
    TEXT-DECORATION: none;
    .text-content-green:hover {
    FONT-SIZE: 11px;
    COLOR: #AE0B0B;
    LINE-HEIGHT: 20px;
    FONT-STYLE: normal;
    FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif;
    TEXT-DECORATION:underline;
    .margin {
    margin: 1px 1px 1px 1px;
    border-style: solid;
    border-top-width: 1px;
    border-left-width: 1px;
    border-right-width: 1px;
    border-bottom-width: 1px;
    border-color: gainsboro;
    </style
    </HEAD>
    <BODY topmargin="10px" leftmargin="0" rightmargin="0"
    class="body-style">
    <TABLE width="729" border="0" cellpadding="0"
    cellspacing="0" cellsadding="0" align="center" class="margin">
    <TBODY>
    <TR>
    <TD width="125" valign="top" bgcolor="#f0f0c1">
    <table width="125" border="0" cellspacing="0"
    cellpadding="0">
    <tr>
    <td width="25" height="25" align="middle"></td>
    <td width="108" class="text-content-green"><A
    class="text-content-green" href="default.html">LEFT
    NAV</A></td>
    </tr>
    <tr>
    <td colspan="2" align="middle"></td>
    </tr>
    <tr>
    <td width="25" height="25" align="middle"></td>
    <td width="108" class="text-content-green"></td>
    </tr>
    <tr>
    <td colspan="2"></td>
    </tr>
    </table>
    </TD>
    <TD vAlign=top width=539 bgColor="white" height=471>
    <P class="text-content-green" align=left
    style="padding-left:5px">Lorem ipsum dolor sit amet, consectetur
    adipisicing elit.Duis aute irure dolor in reprehenderit in
    voluptate velit esse cillum .
    </P>
    </TD>
    </TR>
    </TBODY>
    </TABLE>
    </TD>
    </TR>
    </TBODY>
    </TABLE>
    </BODY>
    </HTML>
    HTH
    Shanthi

  • I don´t know how to make a phone call whit my ipad...and how to sent a message? is it possible?

    i don´t know how to make a phone call whit my ipad...and how to senSeleneGMt a message? What do i need? or is it impossible?

    You can't; not natively, anyway, since the iPad is not a phone. If you want to make a call, you'll need to use some third-party Voice-Over-IP service such as Skype.
    I'm not sure what you're asking when you ask about sending a message. If you mean a text message, you can either use iMessage, which can send messages to other users also running iMessage, or you can look in the iTunes Store for SMS apps, a few of which are available. They use separate services to actually send the message and so require an Internet connection, either WiFi or 3G.
    Regards.

  • How to make a cell in JTable a different colour?

    Hi, i've been playing with JTables with a custom CellRenderer, which I'm trying to make so that in the JTable, when two values down a column are found to be the same, the back ground colour changes to something same (hoping that there is a way to randomize the colour values) the code i have atm is
    In the main program :
                        find.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent ae) {
                                  datahome = cC.data;
                                  TableColumnModel colModel = cC.jtable.getColumnModel();
                                  TableColumn column = colModel.getColumn(0);
                                  column.setCellRenderer(new RedCellRenderer(new int[] {1,2}));
    in the cellrenderer:
    package packageSolo;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.*;
    import java.awt.*;
    public class SetCellColour extends DefaultTableCellRenderer {
         private int arrVerifyColumns[] = null;
         public SetCellColour(int iTestColumns[]) {
              arrVerifyColumns = iTestColumns;
         public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
              this.setBackground(Color.RED); // All columns verified were empty - set
              // our background RED
              return this;
    }any my problem is that this cellrenderer will change the column and not just the cell, i've tried to pass where the cell is (the x and y of the cell) to the cellrenderer, but there is no way for me to interpret this value in cellrenderer and set that cell to that colour i'm not sure if there is a cell model instead of column model and be able to pass that onto the cellrenderer

    ell after several tries, i have determined that it may be something wrong with that my jtable is part of a JPanel, that is attached to a container with scroll pane that is then added to a JFrame's center... and somewhere here it freezes the display...
    my code for the actual JFrame:
    package packageSolo;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class ConflictCheckerGUIIntialization extends JFrame {
          * debugger
          * @param x
          *            takes in an int and prints a debug line when enabled to the
          *            console
         private void debug(int x) {
              // System.out.print("Flag: "+ x);
         private static int flag1 = 0;
         private static int flag2 = 0;
         private static int flag3 = 0;
         private static int flag4 = 0;
         private static int flag5 = 0;
         private static int flag6 = 0;
         private static int flag7 = 0;
         private static int flag8 = 0;
         private static int flag9 = 0;
         private Object[][] datahome;
         private JButton cConflict = new JButton("Check Conflict");
         private JButton find = new JButton("Find");
         private JButton quit = new JButton("Exit");
         // private JButton northavg = new JButton("North's Average");
         // private JButton eastavg = new JButton("East's Average");
         // private JButton largest = new JButton("Largest Percepitation");
         // private JButton totalPercepitation = new JButton("Total Percepitation");
         private ConflictCheckerGUI cC = new ConflictCheckerGUI();
         private JFrame jf = new JFrame();
         private JFrame jf1 = new JFrame();
         // Get the size of the default screen
         private static Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
         private int screensizex = (int) (dim.width * 0.8);
         private int screensizey = (int) (dim.height * 0.75);
         private static int gcsizex = (int) (dim.width * 0.625);
         private static int gcsizey = (int) (dim.height * 0.1953125);
         private static GUIConsole gc = new GUIConsole("Output", gcsizex, gcsizey);
         public ConflictCheckerGUIIntialization() {
              boolean RunOnce = false;
              while (RunOnce == false) {
                   if (cC.finished == true) {
                        System.out.println("he");
                        Container c1 = jf.getContentPane();
                        c1.setLayout(new FlowLayout());
                        Container c = this.getContentPane();
                        Container c2 = jf1.getContentPane();
                        JPanel jp = new JPanel();
                        jp.add(cC);
                        cConflict.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent ae) {
                                  datahome = cC.data;
                                  // System.out.print(datahome
                                  // [0][0].toString().compareTo(datahome
                                  // [1][0].toString()));
                                  // System.out.print(datahome
                                  // [0][0].toString().equals(datahome
                                  // [1][0].toString()));
                                  for (int conflictCounter2 = 1; conflictCounter2 < 3; conflictCounter2++) {
                                       int conflictCounter4 = 0;
                                       for (int conflictCounter1 = 0; conflictCounter1 <= cC.Classroomint; conflictCounter1++) {
                                            conflictCounter4++;
                                            for (int conflictCounter3 = 1; conflictCounter3 <= (cC.Classroomint - conflictCounter4); conflictCounter3++) {
                                                 if (datahome[conflictCounter2][conflictCounter1]
                                                           .toString()
                                                           .equals(
                                                                     datahome[conflictCounter2][conflictCounter1
                                                                               + conflictCounter3]
                                                                               .toString())) {
                                                      System.out.println("error at "
                                                                + conflictCounter2 + " "
                                                                + conflictCounter1);
                                   * for (int counter1 = 0; counter1 < pg.monthint;
                                   * counter1++) { for (int counter2 = 0; counter2 < 5;
                                   * counter2++) {
                                   * System.out.print(datahome[counter1][counter2] +
                                   * "\t"); } System.out.println(); }
                        quit.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent ae) {
                                  try {
                                       System.exit(0);
                                  } catch (SecurityException ea) {
                                       System.out.println("Cannot exit");
                        find.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent ae) {
                                  datahome = cC.data;
                                  Object value = null;
                                  cC.jtable.getCellRenderer(0, 0)
                                            .getTableCellRendererComponent(cC.jtable,
                                                      value, false, true, 0, 0).setFont(new Font(
                                                      "Serif", Font.BOLD, 14));
                                  System.out.println(cC.data[0][0].toString());
                                  // .setFont(new Font("serif", Font.BOLD, 12));
                        gc
                                  .println("There is a known bug with this program that if you enter any information in the table,");
                        gc
                                  .println("then not confirming it by not going to another cell, then the data you've entered it not valid and not considered to be input,");
                        gc
                                  .println("this will be fixed in future revisions if possible");
                        gc.show();
                        gc.setLocation(0, screensizey);
                                    *bold*
                                   *bold* c2.add(jp, "Center");
                        *bold*c2.add(new JScrollPane(jp,
                                  *bold*ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                                  *bold*ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED),
                                  *bold*"Center");
                        c1.setLayout(new GridLayout(2, 5));
                        c1.add(cConflict);
                        c1.add(find);
                        c1.add(quit);
                        c1.setVisible(true);
                        c2.setVisible(true);
                        c.add(c1, "South");
                        c.add(c2, "Center");
                        c.setVisible(true);
                        this.pack();
                        this.setTitle("Lancer's Class Conflict Checker");
                        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
                        this.setSize(screensizex, screensizey);
                        RunOnce = true;
                        // ! this.pack(); //this tries to set the size of the thing to a
                        // perferred size, and if used will not alow the dynamic sizing
                        // of
                        // the
                        // main JTable window based on the user's screensize
         public static void main(String[] args) {
              ConflictCheckerGUIIntialization x = new ConflictCheckerGUIIntialization();
              x.setVisible(true);
    }here, the JPanel with the jtable is added to c2 and c2 is added to c and c's parent is the JFrame of this whole class
    and the code for the jtable JPanel is:
    package packageSolo;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.FileNotFoundException;
    import javax.swing.*;
    import javax.swing.table.*;
    public class ConflictCheckerGUI extends JPanel {
         private void debug(int x) {
              // System.out.println(x);
         protected static boolean finished = false;
         protected static DefaultTableModel[][] data;
         protected static int Classroomint = 0;
         protected static JTable jtable;
         protected static String[] columnNames = { "Classroom", "Period One",
                   "Period Two", "Period Three", "Period Four" };
         protected static int GoAheadFlag = 0;
         SetCellColour renderer;
         public ConflictCheckerGUI() {
              // super(new GridLayout(1, 0));
              JFrame Choose = new JFrame();
              Choose.setDefaultCloseOperation(Choose.EXIT_ON_CLOSE);
              JButton ImportFromFile = new JButton("Impoort From File");
              JButton New = new JButton("New Planner");
              ImportFromFile.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        String[] North;
                        String[] East;
                        String[] South;
                        String[] West;
                        String[] Month;
                        // JFileChooser fc = new JFileChooser();
                        // fc.show();
                        // int returnVal = fc.showOpenDialog(fc);
                        // File file = null;
                        // if (returnVal == JFileChooser.APPROVE_OPTION) {
                        // file = fc.getSelectedFile();
                        java.util.Scanner parse = null;
                        File file = new File(
                                  "E://Documents and Settings//TheHolyLancer//My Documents//java - old//Eclipse workspace//Precipitation//packageSolo//datasave.txt");
                        try {
                             parse = new java.util.Scanner(file);
                        } catch (FileNotFoundException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        Classroomint = Integer.parseInt(parse.next());
                        North = new String[Classroomint];
                        East = new String[Classroomint];
                        South = new String[Classroomint];
                        West = new String[Classroomint];
                        Month = new String[Classroomint];
                        for (int counter1 = 0; counter1 < Classroomint; counter1++) {
                             Month[counter1] = "n/a";
                        for (int counter2 = 0; counter2 < Classroomint; counter2++) {
                             North[counter2] = "n/a";
                             East[counter2] = "n/a";
                             South[counter2] = "n/a";
                             West[counter2] = "n/a";
                        data = new DefaultTableModel[Classroomint][5];
                        jtable = new JTable(new DefaultTableModel(Classroomint,5));//columnnames
                        jtable.setPreferredScrollableViewportSize(new Dimension(800,
                                  600));
                        finished = true;
              New.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        String input;
                        String[] North;
                        String[] East;
                        String[] South;
                        String[] West;
                        String[] Month;
                        int flag2 = 0;
                        int flag4 = 0;
                        int flag5 = 0;
                        int flag8 = 0;
                        input = JOptionPane
                                  .showInputDialog("How many classromms are there?");
                         * see if the user wantes to quit at this point
                        if (input == null) {
                             debug(4);
                             int exitint = 0;
                             exitint = JOptionPane.showConfirmDialog(null,
                                       "Do you want to exit?", "Exit?",
                                       JOptionPane.OK_CANCEL_OPTION);
                             if (exitint == 0) {
                                  try {
                                       System.exit(1);
                                  } catch (SecurityException eb) {
                                       System.out.println("exit");
                        while (flag4 == 0) {
                              * this while loop with flag2 is for checking if the thing
                              * is of int class
                             while (flag2 == 0) {
                                   * try to get a integer, check for a bad input class
                                  try {
                                        * parse, and if success set flag2 to 1 and break
                                        * out this while loop
                                       Classroomint = Integer.parseInt(input);
                                       flag2 = 1;
                                       debug(2);
                                  } catch (NumberFormatException ec) {
                                       debug(3);
                                        * ops user input was not a integer class
                                       JOptionPane.showMessageDialog(null,
                                                 "Enter a positive integer only",
                                                 "Number Format is Wrong",
                                                 JOptionPane.ERROR_MESSAGE);
                                       input = JOptionPane
                                                 .showInputDialog("How many months are there?");
                                        * see if the user wantes to quit at this point
                                       if (input == null) {
                                            debug(4);
                                            int exitint = 0;
                                            exitint = JOptionPane.showConfirmDialog(null,
                                                      "Do you want to exit?", "Exit?",
                                                      JOptionPane.OK_CANCEL_OPTION);
                                            if (exitint == 0) {
                                                 try {
                                                      System.exit(1);
                                                 } catch (SecurityException eb) {
                                                      System.out.println("exit");
                              * this while loop sees if the integer is smaller than 0 so
                              * the array cannot be a real one
                             while (flag5 == 0) {
                                  // numamountint = Integer.parseInt(numamount);
                                  if (Classroomint < 0) {
                                       debug(5);
                                       JOptionPane.showMessageDialog(null,
                                                 "Enter a positive integer",
                                                 "Number Format/Size is Wrong",
                                                 JOptionPane.ERROR_MESSAGE);
                                       input = JOptionPane
                                                 .showInputDialog("How many months are there?");
                                       if (input == null) {
                                            int exitint = 0;
                                            exitint = JOptionPane.showConfirmDialog(null,
                                                      "Do you want to exit?", "Exit?",
                                                      JOptionPane.OK_CANCEL_OPTION);
                                            if (exitint == 0) {
                                                 try {
                                                      System.exit(1);
                                                 } catch (SecurityException eb) {
                                                      System.out.println("exit");
                                        * this while loop check for number format again
                                       while (flag8 == 0) {
                                            try {
                                                 debug(6);
                                                 Classroomint = Integer.parseInt(input);
                                                 flag8 = 1;
                                            } catch (NumberFormatException ec) {
                                                 debug(7);
                                                 JOptionPane.showMessageDialog(null,
                                                           "Enter a positive integer only",
                                                           "Number Format is Wrong",
                                                           JOptionPane.ERROR_MESSAGE);
                                                 input = JOptionPane
                                                           .showInputDialog("How many months are there?");
                                                 if (input == null) {
                                                      int exitint = 0;
                                                      exitint = JOptionPane
                                                                .showConfirmDialog(
                                                                          null,
                                                                          "Do you want to exit?",
                                                                          "Exit?",
                                                                          JOptionPane.OK_CANCEL_OPTION);
                                                      if (exitint == 0) {
                                                           try {
                                                                System.exit(1);
                                                           } catch (SecurityException eb) {
                                                                System.out.println("exit");
                                  } else {
                                        * here the input is greater than 0 so it sets flag5
                                        * and 4 then break out of the while loops
                                       debug(8);
                                       flag5 = 1;
                                       flag4 = 1;
                        North = new String[Classroomint];
                        East = new String[Classroomint];
                        South = new String[Classroomint];
                        West = new String[Classroomint];
                        Month = new String[Classroomint];
                        for (int counter1 = 0; counter1 < Classroomint; counter1++) {
                             Month[counter1] = "n/a";
                        for (int counter2 = 0; counter2 < Classroomint; counter2++) {
                             North[counter2] = "n/a";
                             East[counter2] = "n/a";
                             South[counter2] = "n/a";
                             West[counter2] = "n/a";
                        DefaultTableModel tableModel = new DefaultTableModel(Classroomint, 0);
                        tableModel.addColumn("Classroom");
                        tableModel.addColumn("Period One");
                        tableModel.addColumn("Period Two");
                        tableModel.addColumn("Period Three");
                        tableModel.addColumn("Period Four");
                        /*protected static String[] columnNames = { "Classroom", "Period One",
                             "Period Two", "Period Three", "Period Four" };*/
                        // /jtable = new JTable(data, columnNames);
                        jtable = new JTable(tableModel) {
                             private static final long serialVersionUID = 1L;
                             public TableCellRenderer getCellRenderer(int row, int col) {
                                  return renderer;
                        jtable.setRowSelectionAllowed(true);
                        jtable.setPreferredScrollableViewportSize(new Dimension(800,
                                  600));
                        finished = true;
              Container ButtonHolder = new Container();
              ButtonHolder.setLayout(new GridLayout(1, 2));
              ButtonHolder.add(New);
              ButtonHolder.add(ImportFromFile);
              Choose.add(ButtonHolder);
              Choose.setSize(200, 300);
              Choose.setVisible(true);
              boolean RunOnce = false;
              while (RunOnce == false) {
                   if (finished == true) {
                        //JScrollPane scrollPane = new JScrollPane(jtable);
                        this.add( jtable, BorderLayout.CENTER );
                        Choose.setEnabled(false);
                        RunOnce = true;
    }but upon start, and select start new table, the windows come up, but on where the large JFrame is and where the jtable is, nothing appears, and it acts like a screen cap and the thing just stucks like what is on the background of the computer... i think in all this linking i may have screwed something up, and the examples given were not designed for JPanels, but rather for JFrames... maybe i could implement all this into one class, since the buttons for choosing from load from file and all that can be in the first file as another JFrame, that is first visible, then when user chose one, something becomes visible, or something
    but anyone knows how to fix all this?

  • How to make crosstab cell value become hot link which can link to other?

    Dear Gurus:
    I am using Bi beans in a project, i create a crosstab in one .jsp file,the crosstable can display data correctly,but i want to make every cell value become hot link which point to a url,this url contains measure info and all dimension info,how can i do? Thanks a lot!

    Hi Tomsong,
    We will post a BI Beans Sample that does that to OTN next week.
    In the mean time, look at the following BI Beans Help topic (under Jdeveloper BI Beans Help)
    Handling Drill-Out Events in HTML-Client Applications
    Hope this helps
    Katia

  • How to make JTree cell renderer respect layout?

    Hi,
    In the JTree tutorial, the first example TreeDemo shows a simple tree.
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    If you grab the frame and make it really thin, you get a horizontal scroll bar in the top pane.
    How can I make it so that the tree cells just draw "..." at the end of the string if there is not enough space?
    I know the tree cell renderer uses JLabel, but they never seem to show "...", which is one of the best features of a JLabel. Any help is greatly appreciated!

    Hi,
    I got it working, but I also discovered a Java bug that ruins all this effort!
    Calculating the node's position & width:
    - When child nodes are indented, there is an "L" shaped line drawn... the space to the left of the line's vertical bar is the "leftChildIndent", and the space to the right is the "rightChildIndent". So you add both to get the whole indent.
    - I use label.getPreferredSize().width to figure out the node width, since that includes the icon width, the icon-text gap, and the font metrics.
    Example program:
    - This program models how I want it to look... Always expanded and automatic "..." when the scroll pane is not big enough.
    Bug found:
    - There is a runnable example below. Just run it and after a couple seconds, move the split pane to the right.
    - I use a timer to add a new node every 1 second. The new nodes get stuck being too small, and the original nodes don't have this problem.
    // =====================================================
    * Adaptation of TreeDemo to allow for tree nodes that show "..."
    * when there is not enough space to display the whole label.
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTree;
    import javax.swing.Timer;
    import javax.swing.UIManager;
    import javax.swing.event.TreeExpansionEvent;
    import javax.swing.event.TreeWillExpandListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.ExpandVetoException;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.tree.TreeSelectionModel;
    public class TreeDemo extends JPanel {
        private JTree tree;
        protected class EllipsesTreeCellRenderer implements TreeCellRenderer {
            Integer leftIndent = (Integer) UIManager.get("Tree.leftChildIndent");
            Integer rightIndent = (Integer) UIManager.get("Tree.rightChildIndent");
            int indent = leftIndent.intValue() + rightIndent.intValue();
            JLabel label = new JLabel();
            DefaultTreeCellRenderer r = new DefaultTreeCellRenderer();
            public Component getTreeCellRendererComponent(JTree tree, Object value,
                    boolean selected, boolean expanded, boolean leaf, int row,
                    boolean hasFocus) {
                label.setText("why hello there why hello there why hello there");
                if (selected) {
                    label.setForeground(r.getTextSelectionColor());
                    label.setBackground(r.getBackgroundSelectionColor());
                } else {
                    label.setForeground(r.getTextNonSelectionColor());
                    label.setBackground(r.getBackgroundNonSelectionColor());
                if (leaf) {
                    label.setIcon(r.getLeafIcon());
                } else if (expanded) {
                    label.setIcon(r.getOpenIcon());
                } else {
                    label.setIcon(r.getClosedIcon());
                label.setComponentOrientation(tree.getComponentOrientation());
                int labelWidth = label.getPreferredSize().width;
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                int level = node.getLevel();
                if (!tree.isRootVisible()) {
                    --level;
                int indentWidth = indent * level;
                int rendererWidth = labelWidth + indentWidth;
                // This is zero the first few times getTreeCellRenderer is called
                // because the tree is not yet visible.
                int maxWidth = (int) tree.getVisibleRect().getWidth();
                if (maxWidth > 0) {
                    if (rendererWidth > maxWidth) {
                        // figure out how much space "..." will consume.
                        label.setText(label.getText() + "...");
                        maxWidth = maxWidth
                                - (label.getPreferredSize().width - labelWidth);
                        label.setText(label.getText());
                        // chop off characters until "..." fits in the visible
                        // portion.
                        if (maxWidth > 0) {
                            while (rendererWidth > maxWidth
                                    && label.getText().length() > 1) {
                                label.setText(label.getText().substring(0,
                                        label.getText().length() - 2));
                                rendererWidth = indentWidth
                                        + label.getPreferredSize().width;
                            label.setText(label.getText() + "...");
                return label;
        public TreeDemo() {
            super(new GridLayout(1, 0));
            //Create the nodes.
            final DefaultMutableTreeNode top = new DefaultMutableTreeNode("");
            createNodes(top);
            //Create a tree that allows one selection at a time.
            tree = new JTree(top);
            tree.getSelectionModel().setSelectionMode(
                    TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setCellRenderer(new EllipsesTreeCellRenderer());
            tree.addTreeWillExpandListener(new TreeWillExpandListener() {
                public void treeWillExpand(TreeExpansionEvent event) {
                public void treeWillCollapse(TreeExpansionEvent event)
                        throws ExpandVetoException {
                    throw new ExpandVetoException(event);
            for (int i = tree.getRowCount(); i >= 0; i--) {
                tree.expandRow(i);
            //Create the scroll pane and add the tree to it.
            JScrollPane treeView = new JScrollPane(tree);
            //Add the scroll panes to a split pane.
            JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
            splitPane.setTopComponent(treeView);
            splitPane.setBottomComponent(new JLabel(""));
            Dimension minimumSize = new Dimension(0, 0);
            treeView.setMinimumSize(minimumSize);
            splitPane.setDividerLocation(200); //XXX: ignored in some releases
            //of Swing. bug 4101306
            //workaround for bug 4101306:
            //treeView.setPreferredSize(new Dimension(100, 100));
            // Makes tree nodes appear cut-off initially.
            splitPane.setPreferredSize(new Dimension(500, 300));
            //Add the split pane to this panel.
            add(splitPane);
            // Adds a new node every 1 second
            Timer timer = new Timer(1000, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode("");
                    model.insertNodeInto(child, top, 0);
                    for (int i = tree.getRowCount(); i >= 0; i--) {
                        tree.expandRow(i);
            timer.start();
        private void createNodes(DefaultMutableTreeNode top) {
            DefaultMutableTreeNode category = null;
            DefaultMutableTreeNode book = null;
            category = new DefaultMutableTreeNode("");
            top.add(category);
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
            category.add(new DefaultMutableTreeNode(""));
         * Create the GUI and show it. For thread safety, this method should be
         * invoked from the event-dispatching thread.
        private static void createAndShowGUI() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                System.err.println("Couldn't use system look and feel.");
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TreeDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TreeDemo newContentPane = new TreeDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

  • How to resize a cell in a JTAble

    Hi everyone,
    i have a question how can be done that a column of cells will have an specific size and that other column will be smaller or bigger than the other

    Hi,
    If you mean how to set the columns of your jtable to be of different widths, it can be done as follows:
          TableModel tm =table.getModel();
          int colcount = tm.getColumnCount();
          TableColumnModel tcm = table.getColumnModel();
          for(int s=0;s<colcount;s++) {
                tcm.getColumn(s).setPreferredWidth(150);
                tcm.getColumn(s).setMinWidth(150);
          }Just set the width you want based on the column no in the code above.
    cheers,
    vidyut
    http://www.bonanzasoft.com

  • How to make ALV cell editable

    Hi ,
    I am using cl_gui_alv_grid .
    please let me know how to make a particular cell is editable
    eg:  cell corresponding to first row second column should be editabel but remaining all are non editable

    Hi,
    Loop at your internal table.
    Eg: i have total 5 fields in my internal table itab_zqmeinz. in that 3 fields are editable as below.
    declare DATA: lt_celltab TYPE lvc_t_styl.
    internal table with celltab as one of the column
    DATA: BEGIN OF itab_zqmeinz OCCURS 0. "TYPE STANDARD TABLE OF zqmseqkopf
            INCLUDE STRUCTURE zqmseqeinz.
    DATA: celltab TYPE lvc_t_styl.
    DATA: END OF itab_zqmeinz.
    LOOP AT itab_zqmeinz INTO wa_zqmeinz.
          l_index = sy-tabix.
          REFRESH lt_celltab.
          CLEAR wa_zqmeinz-celltab.
          PERFORM fill_celltab1 USING 'RW'
                                  CHANGING lt_celltab.
          INSERT LINES OF lt_celltab INTO TABLE wa_zqmeinz-celltab.
          MODIFY  itab_zqmeinz FROM wa_zqmeinz INDEX l_index.
        ENDLOOP.
    FORM fill_celltab1 USING value(p_mode)
                      CHANGING pt_celltab TYPE lvc_t_styl.
    Refresh pt_celltab.
      clear ls_celltab.
      IF p_mode EQ 'RW'.
        l_mode = cl_gui_alv_grid=>mc_style_enabled.    "to enable the required fields
      ELSE.                                "p_mode eq 'RO'
        l_mode = cl_gui_alv_grid=>mc_style_disabled.
      ENDIF.
      ls_celltab-fieldname = 'NEBENSEQUEN'.   " field1
      ls_celltab-style = l_mode.
      INSERT ls_celltab INTO TABLE pt_celltab.
      ls_celltab-fieldname = 'BEZEICHNUNG'.     "field2
      ls_celltab-style = l_mode.
      INSERT ls_celltab INTO TABLE pt_celltab.
      ls_celltab-fieldname = 'SORTIERUNG'.         "field3
      ls_celltab-style = l_mode.
      INSERT ls_celltab INTO TABLE pt_celltab.
    Endform.
    It works. I have done it in my program.
    Thanks,

  • How to make a cell/column read only

    HI All,
    Is there any way to make a specific cell read only with in a specific data form?
    Similarly is there any way to make whole column read only inside a specific data form?
    I don't want to make changes in my dimension member (e.g Dynamic Calc), i want to make these changes at data form level because, these cell/column are read only at one form but on some other data form they are editable/enterable

    If you want to make a column read only then have a look at asymettric columns in the planning admin doc, if you use them then you can make one of the columns read only.
    If you want a make one cell read only then one method could be to use javascript, you could add an extra member which is dynamic calc and point to the original member with a formula but it doesn't sound like you want to do that.
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • How to do Multi Cell Selection in JTable

    Dear Friends,
    Any body know Multi cell selection in jtable......
    Thanks

    Try overriding the changeSelection(....) method of JTable.
    public void changeSelection(int row, int column, boolean toggle, boolean extend)
         if (d.after(currentDate)
              super.changeSelection(row, column, toggle, extend);
    }

  • How to make table cell drop down menu from an existing range in cell

    Is this possible?? Checked all over the web & coming up empty. Trying to avoid re-typing in contents from previously created tables in the cell format pop-up menu. Please help.

    I don't think there is an easy way to do this unless Yvan comes up with a script for you.
    One option is to select the range of cells and copy/paste to TextEdit (yes, surprisingly it'll take a range of cells) then from TextEdit you can copy/paste each cell's contents one at a time to the popup menu list. Still a pain but it might be easier than other methods. The workflow I found quickest was to position TextEdit near the Inspector pane (which is open to the Cell inspector with your popup in it) and have the top of the Numbers window nearby. Double click on one cell's contents in TextEdit then Cmd-C to copy, click on the Numbers window up in the toolbar to make Numbers active again without selecting a different cell, then put the contents in the inspector (hit + then paste with Cmd-V). Repeat.
    Message was edited by: Badunit

  • How to make editable cell in ALV TREE?

    Hi all,
    I have a problem to make the cell in item row (I mean not  the cell in hierarchy columns and not in the node row) in ALV tree editable.
    I know to make it in "normal" ALV, but my ALV is type class: cl_gui_alv_tree and the nodes are calculated in a sum.Can anyone help me to set the cell editable in ALV tree?
    Thank you a lot!
    Best regards,
    Danijela Zivanovic
    Message was edited by: Danijela Zivanovic

    HI,
    To make a column editable, it will be sufficient to set the field “<b>EDIT</b>” in the field catalog. The ALV Grid perceives if there are some editable fields and adds buttons for editing purposes. If you do not need these new buttons
    <u><i>if you want it in the Classes</i></u>
    For this procedure; add the name of the field to the field “FIELDNAME”, and pass “cl_gui_alv_grid=>mc_style_enabled” to make a field editable and “cl_gui_alv_grid=>mc_style_disabled” to make a field non-editable,
    <b>Example:</b>
    FORM adjust_editables USING pt_list LIKE gt_list[] .
    DATA ls_listrow LIKE LINE OF pt_list .
    DATA ls_stylerow TYPE lvc_s_styl .
    DATA lt_styletab TYPE lvc_t_styl .
    LOOP AT pt_list INTO ls_listrow .
    IF ls_listrow-carrid = 'XY' .
    ls_stylerow-fieldname = 'SEATSMAX' .
    ls_stylerow-style = cl_gui_alv_grid=>mc_style_disabled . APPEND ls_stylerow TO lt_styletab .
    ENDIF .
    IF ls_listrow-connid = '02' .
    ls_stylerow-fieldname = 'PLANETYPE' .
    ls_stylerow-style = cl_gui_alv_grid=>mc_style_enabled . APPEND ls_stylerow TO lt_styletab .
    ENDIF .
    INSERT LINES OF lt_styletab INTO ls_listrow-cellstyles . MODIFY pt_list FROM ls_listrow .
    ENDLOOP .
    ENDFORM
    Thanks
    Sudheer

  • How to make a cell populate the same as other cells mac numbers

    does anyone know if theres a command where I can make a cell be the same value as another cell? so i change one cell and it populates the same in others. Thanks!

    Hi appleryan,
    =A1
    in any cell will bring the value of A1 into that cell.
    quinn

  • HOW TO MAKE MATERIAL DESCRIPTION  FIELD IN SALES ORDER AS UNEDITABLE

    how to make the material description field as un editable in sales order , pls help me

    Through Transaction Variant <b>SHD0</b>
    Refer the thread
    /message/4083386#4083386 [original link is broken]
    Message was edited by:
            SHESAGIRI.G

Maybe you are looking for

  • Error in Process confirmation editing

    Hi, Experts, One of the users did a confirmation and got Error in Process status. I know that he can change this confirmation thru Display and Process Confirmations Centrally , but the client doesn't want me to add the user this role. Is there anothe

  • Problem with smartform pages

    Hi; I have an Invoice that reach de maximun of lines in the first page (21 lines, that is the size of the Main window), but it shows a second page with all titles but with no records.. any help to solve this. David Fúnez

  • Problem with a text tween

    I have a page I'm developing that has a greensock split text field that I use to animate text. http://jimslounge.com/segovia/ I'm using a timer to help control the tween it doesn't work real smoothly. import com.greensock.*; import com.greensock.easi

  • Part of my hotspot Wi-fi password is missing

    I am unable to connect WI-FI on my I-PHONE because part of my hotspot password is missing. I would like to know how it could be recovered.

  • HT1918 Can't sign in on new ipad

    New ipad 4 , signed in once, downloaded multi apps. signed out, now cannot sign.  went acct info, can't add new ipad, in fact no devices listed, not this comp, (non apple) not ipod, not ipad.