JTabbedPane modifying a JTable

Can a JTabbedPane change the internal layout of a component ?.
I have a pane with some labels and a JTable inside with a layout. It looks fine when setting it as the content pane of a frame, but when I add it to a JtabbedPane in a new tab the JTable looks wrong.
I am using a TableLayout, i don't know if it has something todo with the problem.
Any idea what i'm doing wrong ?

Any idea what i'm doing wrong ? Absolutely none.
How to create a [url http://www.physci.org/codes/sscce.jsp]Short, Self Contained, Correct (Compilable), Example

Similar Messages

  • Jdbc abstract Jtable model problem

    Hi,
    I am trying to write a program that displays the content of a database in a jtable.
    So far the displaying is working, but Im having trouble with adding, deleting and modifying the jtable.
    Im working on the add method first. Its supposed to add a blank row, but it just adds the last row instead.
    Heres the source:
    // new class. This is the table model
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.Vector;
    import javax.swing.JTable;
    public class MyTableModel extends AbstractTableModel {
    Connection con;
    Statement stat;
    ResultSet rs;
    int li_cols = 0;
    Vector allRows;
    Vector row;
    Vector newRow;
    Vector blankRow;
    Vector colNames;
    String dbColNames[];
    String pkValues[];
    String tableName;
    ResultSetMetaData myM;
    String pKeyCol;
    Vector deletedKeys;
    Vector newRows;
    boolean ibRowNew = false;
    boolean ibRowInserted = false;
    MyTableModel(){
    try{
    Class.forName("com.mysql.jdbc.Driver");
    catch (ClassNotFoundException e){
    System.out.println("Cannot Load Driver!");
    try{
    String url = "jdbc:mysql://localhost:3306/aubrey?";
    con = DriverManager.getConnection(url,"Dude1", "supersecret");
    stat = con.createStatement();
    rs = stat.executeQuery("SELECT * from COFFEES");
    deletedKeys = new Vector();
    newRows = new Vector();
    myM = rs.getMetaData();
    tableName = myM.getTableName(1);
    li_cols = myM.getColumnCount();
    dbColNames = new String[li_cols];
    for(int col = 0; col < li_cols; col ++){
    dbColNames[col] = myM.getColumnName(col + 1);
    allRows = new Vector();
    while(rs.next()){
    newRow = new Vector();
    for(int i = 1; i <= li_cols; i++){
    newRow.addElement(rs.getObject(i));
    } // for
    allRows.addElement(newRow);
    } // while
    catch(SQLException e){
    System.out.println(e.getMessage());
    public Class getColumnClass(int col){
    return getValueAt(0,col).getClass();
    public boolean isCellEditable(int row, int col){
    if (ibRowNew){
    return true;
    if (col == 0){
    return false;
    } else {
    return true;
    public String getColumnName(int col){
    return dbColNames[col];
    public int getRowCount(){
    return allRows.size();
    public int getColumnCount(){
    return li_cols;
    public Object getValueAt(int arow, int col){
    row = (Vector) allRows.elementAt(arow);
    return row.elementAt(col);
    public void setValueAt(Object aValue, int aRow, int aCol) {
    Vector dataRow = (Vector) allRows.elementAt(aRow);
    dataRow.setElementAt(aValue, aCol);
    fireTableCellUpdated(aRow, aCol);
    public void updateDB(){}
    public void addRow(){
         newRow.addElement(blankRow);
         int rowNumber = allRows.size();
         allRows.addElement(newRow);
         ibRowNew = true;
         this.isCellEditable(allRows.size(),0);
         System.out.println(allRows.size());
         fireTableRowsInserted(rowNumber,rowNumber);
    public void deleteRow(int i){}
    }And here is the code for the GUI:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class MyTableApp extends JFrame{
    JTable myTable;
    JButton update;
    JButton insert;
    JButton delete;
    JPanel p;
    MyTableModel tm;
    JScrollPane myPane;
    MyTableApp(){
    try{
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    catch(Exception e){
    System.out.println("Error on look and feel");
    update = new JButton("Update");
    insert = new JButton("Add");
    delete = new JButton("Delete");
    p = new JPanel();
    tm = new MyTableModel();
    myTable = new JTable(tm);
    myPane = new JScrollPane(myTable,
    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    myTable.setSelectionForeground(Color.white);
    myTable.setSelectionBackground(Color.red);
    myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    p.add(myPane);
    p.add(update);
    p.add(insert);
    p.add(delete);
    update.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    tm.updateDB();
    insert.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    tm.addRow();
    myTable.setEditingRow(tm.getRowCount());
    myTable.setRowSelectionInterval(tm.getRowCount()-1,tm.getRowCount()-1);
    delete.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    int rowToDelete = myTable.getSelectedRow();
    tm.deleteRow(rowToDelete);
    myTable.setEditingRow(rowToDelete -1);
    myTable.setRowSelectionInterval(rowToDelete -1,rowToDelete -1);
    this.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    }); // end windowlistener
    this.setContentPane(p);
    this.setVisible(true);
    this.pack();
    } // constructor
    public static void main (String args[]){
    new MyTableApp();
    } // main
    } //class

    When adding a row to a JTable, one should manipulate the table model. There are many examples of this on the web. Google is your friend.
    Good luck.
    Filestream

  • Get value from JTable

    I have created a 3-rows JTable and a JButton at a JFrame.
    The purpose of the JButton is to get all the value of the JTable and write to a text file.
    by the getValueAT method.
    User can press the save button any time after he/she modified the JTable.
    however, i discover a problem.
    problem:
    When user select a row, and modify it. and then press the save button.
    the getValueAt method still get the old value of the row and write to the text file unless user select another cell.
    in short, user has to select another cell after modified his/her target cell in order to let the modified to success.
    any experts can help?

    Hi,
    this is simply because the editing process is not finished at that time - if you want it to stop you should add a line of code to your ActionListener for your button:
    // assuming table is your JTable (subclass)
    if (table.isEditing()) { table.getCellEditor().stopCellEditing(); }
    this way the editing process is aborted and the particially edited contents of the cell are accepted.
    greetings Marsian

  • Display a text  with icon in a JTable cell and a textarea on click of icon

    Hello,
    I need to modify the JTable, so that in some cells I can display a text with a small icon or symbol, on click of the the icon or symbol a small JTextArea or a display should open exactly at the position of mouse click to display list of text values.
    I searched this forum, but could not find the right solution... a code example will be good....
    Eagerly waiting....
    Serj

    Are you using an annonymous inner class for your mouse listener? I think this coudl cause some problems in your case.
    Try creating your own listener class e.g.
    class myListener extends MouseListener(){....}
    in this class, add a field such as 'name' - set with the constructor. So when you create your "outer table" write something like..
    outerTable.addMouseListener(new myListener("outer"));
    And when you create the inner table, write something like
    innerTable.addMouseListener(new myListener("inner"));
    Then when you capture Mouse click events, you can work out whether the click came from an outer table or inner table:
    public void mouseClicked(MouseEvent e){
    if(this.name.equals("inner")).....
    else.....
    In this way you should avoid the problem of knowing which table was clicked on...and still us the same mouse listener.
    I hope this is what you mean!
    Chris.

  • Dragging multiple rows in JTable - MUST use CTRL, or not?

    Hello all!
    I'm writing an app that needs to be able to drag multiple rows from a JTable. I have seen that I can do this by selecting multiple rows with the LEFT mouse button, while holding down the CTRL key, and then dragging (again, with the left mouse button).
    The problem is, since I'm holding down the CTRL key, this comes across as a DnDConstants.ACTION_COPY.
    I find that if I do multiple selection, then drag with the RIGHT mouse button (no CTRL key held down), then I get a DnDConstants.ACTION_MOVE, as I want.
    My question: Is there any simple way to enable dragging multiple JTable rows, using the LEFT mouse button, but WITHOUT holding down the CTRL key?
    I have been tasked with "making it act like Windows", which doesn't undo a multiple-selection when one clicks on an existing selected row until one lets go of the left mouse button; whereas JTables appear to change the selection to the clicked-upon row immediately, even if it is part of the existing selection.
    Any ways around this anyone knows, short of modifying the JTable or BasicTableUI itself?
    - Tim

    By the way, I just tested this assumption of mine, and found I was wrong if you're using default JTable drag and drop.
    However, I'm using my own implementation. I notice in a simple program without any drag and drop, I get the behavior I mentioned above, so I'm guessing this IS default JTable behavior, which is then modified by the built-in drag and drop support.
    So the trick will be, how to do what built-in drag and drop is doing, without using built-in drag and drop. :-)
    - Tim

  • Regarding UI alignment

    Hi All,
    this is my first message in this Forum..
    In my project I created a UI with 10 Jtextfields two Tabs in JtabbedPane and a Jtable. Now my PL suddenly gave me a additional task to include 5 more Jtextfiled and another Tab.
    1. I have to modify the existiong view with rectangle postions.
    2. Simulataneously all other components has to be rearranged.
    3. Is there any easy method to do this instead of adjusting each time compiling and running. I am using JDeveloper but we are using our own Layout manager so i cant adjust with any IDE.
    So i need any simple solution for it

    It is really not complicated to add a Tab with textfields:
            JPanel jPanel3 = new JPanel();
            JTextField jTextField1 = new JTextField();
            jPanel3.add(jTextField1);
            jTabbedPane1.addTab("tab3", jPanel3);

  • Add button to unused space in JTableHeader

    I have modified my JTable so that I can have multiple rows of column headers. I did this by extending BasicTableHeaderUI. In my particular instance, the first column of the table will never have more than one row in the header (unlike other implementations of multi-row headers I have seen, my column headers don't automatically fill upwards to take up all usable space in the header). So, I have "unused" space in the header above the first column.
    I would like to put some buttons there that are relevant to the table, but so far every effort to do so has failed.
    In the SSCCE below I have created a very stripped down version of my TableHeaderUI. It doesn't contain any of the code to create multiple row headers, it just pushes down the standard column headers to create some space. I try adding a button to the rendererPane, but it doesn't show up. There is a commented out line that paints the button which does work in terms of showing the button, but that's probably not the right way to do this (and the button doesn't work anyway).
    So, why isn't the button showing up? Am I doing this the right way (i.e. adding the button within the UI)? Thanks in advance for you help.
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Enumeration;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.plaf.basic.BasicTableHeaderUI;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    public class HeaderButtonTable extends JPanel {
         public HeaderButtonTable() {
              String[] colNames = {"column 1", "column2", "column3"};
              Object[][] data = {{"a","b","c"},{"d","e","f"}};
              JTable table = new JTable(data, colNames);
              table.setPreferredScrollableViewportSize(new Dimension(400,100));
              table.setFillsViewportHeight(true);
              table.getTableHeader().setUI(new ButtonHeaderUI());
              JScrollPane scrollPane = new JScrollPane(table);
              add(scrollPane);
         public class ButtonHeaderUI extends BasicTableHeaderUI {
              public void paint(Graphics g, JComponent c) {
                   Rectangle clip = g.getClipBounds();
                   Point left = clip.getLocation();
                   Point right = new Point( clip.x + clip.width - 1, clip.y );
                   TableColumnModel cm = header.getColumnModel();
                   int cMin = header.columnAtPoint(left);
                   int cMax = header.columnAtPoint(right);
                   if (cMin == -1) cMin =  0;
                   if (cMax == -1) cMax = cm.getColumnCount()-1;
                   TableColumn draggedColumn = header.getDraggedColumn();
                   int columnWidth;
                   Rectangle cellRect = header.getHeaderRect(cMin);
                   TableColumn aColumn;
                   for(int column = cMin; column <= cMax ; column++) {
                        aColumn = cm.getColumn(column);
                        columnWidth = aColumn.getWidth();
                        cellRect.width = columnWidth;
                        if (aColumn != draggedColumn) {
                             paintCell(g, cellRect, column);
                        cellRect.x += columnWidth;
                  JButton test = new JButton("test");
                  test.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e) {
                             System.out.println("pressed");
                  test.setBounds(2, 2, 60, 15);
                  rendererPane.add(test);  //why isn't this showing up?
                  //this line will display the button, but button doesn't work
    //          rendererPane.paintComponent(g, test, header, 2, 2, 60, 15);
              private Component getHeaderRenderer(int columnIndex) {
                   TableColumn aColumn = header.getColumnModel().getColumn(columnIndex);
                   TableCellRenderer renderer = aColumn.getHeaderRenderer();
                   if (renderer == null) renderer = header.getDefaultRenderer();
                   return renderer.getTableCellRendererComponent(header.getTable(),
                        aColumn.getHeaderValue(), false, false, -1, columnIndex);
              private void paintCell(Graphics g, Rectangle cellRect, int columnIndex) {
                   Component component = getHeaderRenderer(columnIndex);
                   rendererPane.paintComponent(g, component, header,
                        cellRect.x, cellRect.y + 30, cellRect.width,
                        cellRect.height - 30, true);
              public Dimension getPreferredSize(JComponent c) {
                   long width = 0;
                   Enumeration enumeration = header.getColumnModel().getColumns();
                   while (enumeration.hasMoreElements()) {
                        TableColumn aColumn = (TableColumn)enumeration.nextElement();
                        width = width + aColumn.getPreferredWidth();
                   return new Dimension((int)width, 60);
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.add(new HeaderButtonTable());
              frame.pack();
              frame.setVisible(true);
    }

    Yes, I've seen similar links/posts about how to activate buttons in the header of a table, but those do it by adding listeners to the renderer. My buttons would be directly in the CellRendererPane that is the container for the table header. I would have thought that by putting the button directly in the Cell RendererPane that it would have nothing to do with the rest of the table header. CellRendererPane extends Container. Is it not possible to put a JButton in a Container? JFrame extends indirectly from Container and you can add buttons to that.
    Edited by: Bob.B on Oct 28, 2009 10:57 PM

  • Running a single program on several clients

    Hi,
    I'm making a program which is going to be put on a server. The users will have this server mapped as a network drive (say, P:). For the user to run the program, she/he will run a bat-file (which sets 'PATH' to include JRE (which is also on the server) and starts the program with javaw).
    The program takes input from the user (both by reading from user-specified file(s) and by getting data from a JTable edited by the user), generates information in a (temp) file, may save the file, and may send the file to another server.
    Storing of files is done on each user's own computer and not on the server (specifying "C:\TEMP" places the file on the computer running the program, not on the server).
    My question is this:
    When several users run the program at the same time, how will the program act?
    What happens if a couple (or more) users try to do the same thing at the same time, i.e. access the same methods at the same time? (For example generate XML from the table or send the generated file.)
    I've tried 'playing server' by sharing my program on the internal network and running it on other computers, and it all seems to be working well.
    Is there something I should be aware of?
    Should I use Threads and/or synchronization?
    -negal

    yes, i got that. as i said, in this case you need
    locks only on the resources that multiple threads
    modify (the JTable in your case, and whatever else you
    are using).What?!?
    There is nothing in the above discussion that suggests that a client server architecture is in use.
    There is a computer A which has application code. And a computer B where the code runs. The fact that there is two computers is irrelevant to the question. From the point of view of this architecture the code just a well live on computer B. It makes no difference.
    A JTable is a GUI component. Even in a client server architecture a JTable will ALWAYS be independent for every client.
    Now the resources that a JTable displays might not be independent but nothing in the above points out that any resources, at all, are shared.
    Now if there WAS a server component then that would mean there was an application RUNNING on the server. That is not the same as the application code being stored there.
    Now there might be a shared resource in the above when the OP says "send the file to another server." But that is the only possibility of a shared component (as server application.)
    Presumably if the OP has a server application (which is NOT what is being discussed here) then they need to provide more information about that. The client, as it is, does not do anything that involves shared resources.

  • Empty lines at the end of the payload generated in FTP server

    Hi All,
    I am facing an issue in one of the use cases that I am trying to implement.
    I am getting a purchase order from one of the trading partners through Oracle B2B.
    B2B forwards this B2BM (B2B message ) to AIAB2BInterface. From AIAB2BInterface my BPEL process gets invoked, which in turn invokes the AdapterComposite which has a FTP adapter that writes the purchase order to a FTP server. PFB the end to end flow.
    PurchaseOrder from ABC trading pertner--> Oracle B2B --> AIAB2BInterface --> TestInputProvABCS --> TestInputAdapter -> Host trading partner picks up the file from FTP location
    In the ProvABCS I retrieve the actual payload from the B2BM and convert it into a string using ora:getContentasString. I am then invoking the adapter composite and sending the string as the input to FTP adapter. At the adapter composite I use a simple native schema (for validation of the input string) which has only one element PO_Info of the type string. But when the file gets generated in the FTP server there are empty lines and junk characters at the end of the file.
    Need some advice on this. Why are the empty lines coming in the end of the file? Please help!
    Thanks

    OK, I cannot figure out a way to modify the JTable (in an extended class) directly.
    So, what I did was to add a wrapper around the TreeTableModel which shows an empty row at the end.
    For those of you who are in a similar situation, the methods that I had to modify are
    public boolean isCellEditable(Object node, int column);
    public int getIndexOfChild(Object parent, Object child);
    public int getChildCount(Object node);
    public Object getChild(Object node, int i);
    These other methods are required if you are using a TreeTable instead of just a table (see http://java.sun.com/products/jfc/tsc/articles/treetable2/index.html)
    public Object getValueAt(Object node, int row, int column);
    public Object getValueAt(Object node, int row, String columnName);
    public void setValueAt(Object node, int row, int column, Object newValue);
    public void setValueAt(Object node, int row, String columnName, Object newValue);
    The signature of above methods is slightly different than the ones at: http://java.sun.com/products/jfc/tsc/articles/treetable2/src/TreeTableModel.java
    This is due to the fact that, if you want to display the serial no. (as in row number), then getValue() can just return the row number. IndexedTreeTableModel is another wrapper around the TreeTableModel which can add an extra column to display the serial number.

  • Split TextArea

    Im wanting to create a TextArea that will show ASCII on the left, and the Hex values on the right.
    Im not sure where to start. Ive looked into the JTextArea source and noticed it doesnt have a paintComponent method. So obviosly text components render differently?
    I thought of modifying the JTable, but I wont be dealing with rows.
    I was then thinking of just implementing my own paintComponent for the text area, but I think I should learn how text components are drawn first.
    Or, to save time, has anyone seen an implementation of this already?
    Any ideas on where to start?

    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class ShowText extends JFrame{
        public ShowText(){
            setTitle("Show Text");
            setDefaultCloseOperation( EXIT_ON_CLOSE );
            try{
                readText();
            }catch(IOException ex){
                ex.printStackTrace();
            textPane = new JTextPane();
            textPane.setFont( new Font("monospaced", 0, 14) );
            JScrollPane scrollPane = new JScrollPane( textPane );
            getContentPane().add( scrollPane );
            showText(40);
            setScreenState(false);   //true = full screen
        private void showText(int textWidth){
            StringBuffer sb = new StringBuffer(1000);
            for ( int j=0; j<text.length(); j=j+textWidth ){
                int end = text.length();
                int end_2 = j+textWidth;
                if( end_2 > end ){
                    text.append( blanks.substring( 0, end_2 - end ) );
                String str = text.substring(j, end_2);
                sb.append(str);
                sb.append("\t");
                sb.append(asciiToHex(str));
                sb.append("\n");
            setTabs( textPane, textWidth+5 );
            textPane.setText( sb.toString() );
        public void setTabs( final JTextPane textPane, int textWidth){
            FontMetrics fm = textPane.getFontMetrics( textPane.getFont() );
            int charWidth = fm.charWidth( 'W' );
            TabStop[] tabs = new TabStop[1];
            tabs[0] = new TabStop( textWidth * charWidth );
            TabSet tabSet = new TabSet(tabs);
            SimpleAttributeSet attributes = new SimpleAttributeSet();
            StyleConstants.setTabSet(attributes, tabSet);
            int length = textPane.getDocument().getLength();
            textPane.getStyledDocument().setParagraphAttributes(0, length, attributes, false);
        private void readText()throws IOException{
            BufferedReader reader = new BufferedReader(new FileReader("MyText.txt"));
            text = new StringBuffer(1000);
            for( String str = reader.readLine(); str != null; str = reader.readLine() ){
                text.append(str);
        private String asciiToHex(String ascii){
            StringBuilder hex = new StringBuilder();
            for (int i=0; i < ascii.length(); i++) {
                hex.append(Integer.toHexString(ascii.charAt(i)));
            return hex.toString();
        private void setScreenState(boolean full){
            setExtendedState(JFrame.MAXIMIZED_BOTH);
            if(full){
                setResizable(false);
                setVisible(true);
            }else{
                setVisible(true);
                setResizable(false);
        public static void main(final String[] args){
            new ShowText();
        private JTextPane textPane;
        private StringBuffer text;
        private final String blanks = "                                                  ";
    }

  • Grabbing focus still needs 2 TABS to show focus border

    I have a JFrame that contains a JSplitPane (jsp1). The left side of jsp1 has a JScrollPane that contains a JTreeTable. The right side of jsp1 contains another JSplitPane (jsp2). The top of jsp2 has a JPanel that contains lots of JTextFields. The bottom of jsp2 has a JPanel that contains a JTabbedPane. Each tab of the JTabbedPane contains a JTable.
    TAB works to navigate through this entire mess. I want to create shortcut keys to jump from anywhere on the screen to the first cell of the JTreeTable. I would also like to be able to jump to the first cell of the JTable that is in the current selected JTabbedPane.
    I have a CTRL-TAB shortcut that moves the focus into the component of the JSplitPane that I want [via requestFocus()], but it takes 2 more presses of the TAB key for the focus border to show up and then when it shows up it is on the 2nd cell of the JTreeTable (or 2nd cell of the JTable inside the JTabbedPane.
    I would like to force the focus without the extra TABS. Any ideas ?
    WW

    Sorry, I don't understand what you are trying to accomplish. However one line did catch my eye.
    This is happening because the popup is not keyboard-focusable The code in the popupPopup() method in the following post might help:
    http://forum.java.sun.com/thread.jspa?threadID=636842

  • UI Components for folder tabs, trees and tables

    I hear quite a lot lately about how JSF is the Web equivalent of Swing, but I cannot find any references of support for some of the advanced Swing components, such as JTabbedPane, JTree and JTable. Are there such components in JSF, either from Sun, or from third parties?

    Good question. I have a thick swing client that began
    life as an applet and ended as as
    Java-Web-Start-launched application. It makes HEAVY
    use of JTable.
    I'm guessing JSF won't help us.Don't jump to conclusion.
    First check out this resources:
    http://www.cs.sjsu.edu/faculty/horstman/corejsf/geary-horstmann-corejsf-chapter9.pdf
    http://www.manning.com/mann (buy book or take a look on source code)
    http://thejspbook.com/aboutjsfbook.jsp;jsessionid=a974mvl_TiKf
    (buy book or take a look on source code)
    https://bpcatalog.dev.java.net/nonav/solutions.html
    http://www.ourfaces.net:8080/ourfaces/
    http://myfaces.org/
    Let me know if you need more functionality.
    I'm developing couple of related components so let me know if you need some extra functionality.
    Let's start compete with Swing :-)
    Vladimir

  • Problem in JTabel

    Dear sir,
    I am using Netbeans 6.1
    I know that I can get selected rows from JTable which is connected to database from " jTable1.getSelectedRow();
    but my problem is that once I have got the selected row then how to read the data from it.
    Means that my table consist of a coloumn "name" then how to display the " name "of the selected row into the textfield in the jFrame
    Please tell me the function for that.
    regards
    gaurav

    Dear sir,
    I am able to perform every operation the Jtable .
    But my another problem is that when I modify the Jtable or delete a row or add a new row.
    Then how to save that modified Jtable into the database i.e. the new rows added must be saved to database or rows deleted must be deleted from database.
    Please help me for that,It is very urgent?
    rgdrs
    gaurav

  • SwingML Beta 1.1 released

    The SwingML Beta 1.1 version is out.
    This new version is released under GNU General Lesser Public License and has many additions and improvements to the previous Beta 1.0 version.
    It is available at:
    http://swingml.sourceforge.net
    This version provides support for the following JFC Swing components and features:
    JMenuBar, JMenu, JMenu, JSeparator, ButtonGroup, JToolBar, JEditorPane, Customized Action Behavior support.
    Several improvements have been made to the Renderer's internal architecture to provide better scalability and its size has been reduced to 110 KB in comparison with the 119 KB that weighted before the new additions.
    For those who doesn't know what the SwingML project is
    SwingML is an open source project available under LGPL and its goal is to release the power of JFC/Swing in the creation of front ends for web based business applications by providing an alternative to replace completely the use of HTML dinamic generation at the server side components.
    With SwingML a developer can produce dinamically in the server side component a SwingML form (which is based on XML) and at the client side an applet translates it in to a JFC/Swing based graphical user interface. This applet is called "Renderer" and it manages the translation of the SwingML into a Swing based gui and the request and response calls to the server side component using HTTP.
    Currently we support the components mentioned above plus all the following
    JPanel, JTextField, JLabel, JButton, JTabbedPane, JInternalFrame, JTree, JTable, JList, JComboBox, JDialog, JCheckBox, JTextArea, JSplitPane, JOptionPane, JRadioButton, ActionListener, DocumentListener, FocusListener, ItemListener, ListSelectionListener, GridLayout, FlowLayout, BorderLayout, GridBagLayout, ToolTips, Icons, Debugging Messages, Multiple Look and Feels, POST and GET operations.
    SwingML has been built entirely around an object oriented architecture and provides a flexible framework that can be extended to support custom made JFC Swing components or any other necessary feature. The SwingML specification is very simple and easy to understand and doesn't require any learning curve for developers with basic JFC Swing knowledge

    Blech. A solution looking for a problem. The things programmers do when the are bored.

  • Resize JTable in JTabbedPane

    Given the FileTableDemo from the Java Foundation Class in a Nutshell book.(O'Reilly) Chapter 3 page 51 in my addition.
    I have modified the example to place the JTable in a JTabbedPane. Now when the window (JFrame) is resized by the user the JTable no longer resizes. How do I passing the "resizing" into the component (JTable) placed in the JTabbedPane?
    Here is the code: My deviation from the example is enclosed in "///////////KBS" and of course the line frame.getContentPane().add(myTP, "Center"); where "pane" has been replaced with "myTP"
    Thanks Brad
    import javax.swing.*;
    import javax.swing.table.*;
    import java.io.File;
    import java.util.Date;
    public class FileTableDemo
    public static void main(String[] args)
    // Figure out what directory to display
    File dir;
    if (args.length > 0)
    dir = new File(args[0]);
    else
    dir = new File(System.getProperty("user.home"));
    // Create a TableModel object to represent the contents of the directory
    FileTableModel model = new FileTableModel(dir);
    // Create a JTable and tell it to display our model
    JTable table = new JTable(model);
    JScrollPane pane = new JScrollPane(table);
    pane.setBorder(BorderFactory.createEmptyBorder(60,20,20,20));
    ////////KBS
    JTabbedPane myTP = new JTabbedPane();
    JPanel myOne = new JPanel();
    JPanel myTwo = new JPanel();
    myOne.add(pane);
    myTP.add("One", myOne);
    myTP.add("Two", myTwo);
    ////////KBS
    // Display it all in a scrolling window and make the window appear
    JFrame frame = new JFrame("FileTableDemo");
    frame.getContentPane().add(myTP, "Center");
    frame.setSize(600, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    // The methods in this class allow the JTable component to get
    // and display data about the files in a specified directory.
    // It represents a table with six columns: filename, size, modification date,
    // plus three columns for flags: direcotry, readable, writable
    class FileTableModel extends AbstractTableModel
    protected File dir;
    protected String[] filenames;
    protected String[] columnNames = new String[] {
    "name",
    "size",
    "last modified",
    "directory?",
    "readable?",
    "writable?"
    protected Class[] columnClasses = new Class[] {
    String.class,
    Long.class,
    Date.class,
    Boolean.class,
    Boolean.class,
    Boolean.class
    // This table model works for any one given directory
    public FileTableModel(File dir)
    this.dir = dir;
    this.filenames = dir.list();
    // These are easy methods
    public int getColumnCount()
    return 6;
    public int getRowCount()
    return filenames.length;
    // Information about each column
    public String getColumnName(int col)
    return columnNames[col];
    public Class getColumnClass(int col)
    return columnClasses[col];
    // The method that must actually return the value of each cell
    public Object getValueAt(int row, int col)
    File f = new File(dir, filenames[row]);
    switch(col)
    case 0: return filenames[row];
    case 1: return new Long(f.length());
    case 2: return new Date(f.lastModified());
    case 3: return f.isDirectory() ? Boolean.TRUE : Boolean.FALSE;
    case 4: return f.canRead() ? Boolean.TRUE : Boolean.FALSE;
    case 5: return f.canWrite() ? Boolean.TRUE : Boolean.FALSE;
    default: return null;
    }

    Well, I didn't find an answer but I did find a solution.
    The JPanel is the problem. I use it to help with layout which is not obvious in this example.
    As you can see in the code the JTable is placed in a JScrollPane which is place in a JPanel which is placed in a JTabbedPane.
    If I use Box instead of JPanel the JTable in the JScrollPane in the Box in the TabbedPane in the JFrame resizes correclty.
    So although JPanel is resizable with setSize it does not get resized when it's JFrame gets resized.
    I would still like to know why?
    ////////KBS
    JTabbedPane myTP = new JTabbedPane();
    Box myOne = Box.createHorizontalBox();
    Box myTwo = Box.createHorizontalBox();
    myOne.add(pane);
    myTP.add("One", myOne);
    myTP.add("Two", myTwo);
    ////////KBS

Maybe you are looking for