JDialog/JTable sizing

I have a JDialog with a JTable/scroll pane. The JTable has headers but no data initially.
I want to set the min size samller than the initial size.
When I try setSize/setPreferred size this is not working. It always inits to the min size.
    public TheDialog(Frame parent)
        super(parent);
        theModel = new TheTableModel();
        theTable      = new TheTable(thetableModel);
        Dimension size = new Dimension(100,400);
        setLayout(new BorderLayout());
        JScrollPane scrollPane = new JScrollPane(theTable,
                                                 JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                                 JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setPreferredSize(size);
        scrollPane.setSize(size);
        add(scrollPane, BorderLayout.CENTER);  
        setPreferredSize(size);
        setSize(size);
       setMinimumSize(new Dimension(100,20));

I am fairly new to the forum
Didn't know that people cared about any feedbackWhat does being new to a forum have to do with anything?
In other words you don't believe in saying "thank you" when someone gives you help, whether in a forum or in other apects of daily life?
Maybe the following will work:
table.setPreferredScrollableViewportSize(...);If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

Similar Messages

  • Model view presenter

    Hi,
    Does anyone have any examples of the use of the model view presenter design pattern within Swing. I am attempting to refactor a number of Swing classes based around JDialogs, JTables etc. Your help would be greatly appreciated.
    Many thanks,
    dude

    Thanks I have this example, I would like to see some other swing examples if anyone has them...

  • JTable can't display column names and scroll bar in JDialog !!

    Dear All ,
    My flow of program is JFrame call JDialog.
    dialogCopy = new dialogCopyBay(frame, "Bay Name Define", true, Integer.parseInt(txtSourceBay.getText()) ,proVsl ,300 ,300);
    dialogCopy.setBounds(0, 0, 300, 300);
    dialogCopy.setVisible(true);        Then,I set the datasource of JTable is from a TableModel.
    It's wild that JTable can diplay the data without column names and scroll bar.
    I have no idea what's going wrong.Cause I follow the Sun Tutorial to code.
    Here with the code of my JDialog.
    Thanks & Best Regards
    package com.whl.panel;
    import com.whl.vslEditor.vslDefine;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Frame;
    import javax.swing.JDialog;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class dialogCopyBay extends JDialog {
        vslDefine glbVslDefine;
        int lvCnt = -1;
        JTable tableCopyBay;
        int bgnX = 0;
        int bgnY = 30;
        int tableWidth = 100;
        int tableHeight = 100;
        public dialogCopyBay(Frame frame, String title, boolean modal, int sourceBay,
                vslDefine pVslDefine, int ttlWidth, int ttlHeight) {
            super(frame, title, true);
            Container contentPane = getContentPane();
            System.out.println("dialogCopyBay Constructor");
            glbVslDefine = null;
            glbVslDefine = pVslDefine;
            copyBayModel copyBay = new copyBayModel((glbVslDefine.getVslBayStructure().length - 1),sourceBay);
            tableCopyBay = new JTable(copyBay);
            tableCopyBay.setPreferredScrollableViewportSize(new Dimension(tableWidth, tableHeight));
            JScrollPane scrollPane = new JScrollPane(tableCopyBay);
            scrollPane.setViewportView(tableCopyBay) ;
            tableCopyBay.setFillsViewportHeight(true);
            tableCopyBay.setBounds(bgnX, bgnY, tableWidth, tableHeight);
            tableCopyBay.setBounds(10, 10, 100, 200) ;
            contentPane.setLayout(null);
            contentPane.add(scrollPane);
            contentPane.add(tableCopyBay);
        class copyBayModel extends AbstractTableModel {
            String[] columnNames;
            Object[][] dataTarget;
            public copyBayModel(int rowNum ,int pSourceBay) {
                columnNames = new String[]{"Choose", "Bay Name"};
                dataTarget = new Object[rowNum][2];
                for (int i = 0; i <= glbVslDefine.getVslBayStructure().length - 1; i++) {
                    if (pSourceBay != glbVslDefine.getVslBayStructure().getBayName() &&
    glbVslDefine.getVslBayStructure()[i].getIsSuperStructure() == 'N') {
    lvCnt = lvCnt + 1;
    dataTarget[lvCnt][0] = false;
    dataTarget[lvCnt][1] = glbVslDefine.getVslBayStructure()[i].getBayName();
    System.out.println("lvCnt=" + lvCnt + ",BayName=" + glbVslDefine.getVslBayStructure()[i].getBayName());
    public int getRowCount() {
    return dataTarget.length;
    public int getColumnCount() {
    return columnNames.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int rowIndex, int columnIndex) {
    return dataTarget[rowIndex][columnIndex];
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    public boolean isCellEditable(int row, int col) {
    if (col == 1) {
    // Bay Name Not Allow To modify
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    dataTarget[row][col] = value;
    fireTableCellUpdated(row, col);

    Dear DB ,
    I am not sure what you mean.
    Currently,I don't undestand which code is error.
    And I also saw some example is add JTable and JScrollPane in JDialog.
    Like Below examle in Sun tutorial
    public class ListDialog extends JDialog implements MouseListener, MouseMotionListener{
        private static ListDialog dialog;
        private static String value = "";
        private JList list;
        public static void initialize(Component comp,
                String[] possibleValues,
                String title,
                String labelText) {
            Frame frame = JOptionPane.getFrameForComponent(comp);
            dialog = new ListDialog(frame, possibleValues,
                    title, labelText);
         * Show the initialized dialog. The first argument should
         * be null if you want the dialog to come up in the center
         * of the screen. Otherwise, the argument should be the
         * component on top of which the dialog should appear.
        public static String showDialog(Component comp, String initialValue) {
            if (dialog != null) {
                dialog.setValue(initialValue);
                dialog.setLocationRelativeTo(comp);
                dialog.setVisible(true);
            } else {
                System.err.println("ListDialog requires you to call initialize " + "before calling showDialog.");
            return value;
        private void setValue(String newValue) {
            value = newValue;
            list.setSelectedValue(value, true);
        private ListDialog(Frame frame, Object[] data, String title,
                String labelText) {
            super(frame, title, true);
    //buttons
            JButton cancelButton = new JButton("Cancel");
            final JButton setButton = new JButton("Set");
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ListDialog.dialog.setVisible(false);
            setButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ListDialog.value = (String) (list.getSelectedValue());
                    ListDialog.dialog.setVisible(false);
            getRootPane().setDefaultButton(setButton);
    //main part of the dialog
            list = new JList(data);
            list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            list.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2) {
                        setButton.doClick();
            JScrollPane listScroller = new JScrollPane(list);
            listScroller.setPreferredSize(new Dimension(250, 80));
    //XXX: Must do the following, too, or else the scroller thinks
    //XXX: it's taller than it is:
            listScroller.setMinimumSize(new Dimension(250, 80));
            listScroller.setAlignmentX(LEFT_ALIGNMENT);
    //Create a container so that we can add a title around
    //the scroll pane. Can't add a title directly to the
    //scroll pane because its background would be white.
    //Lay out the label and scroll pane from top to button.
            JPanel listPane = new JPanel();
            listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
            JLabel label = new JLabel(labelText);
            label.setLabelFor(list);
            listPane.add(label);
            listPane.add(Box.createRigidArea(new Dimension(0, 5)));
            listPane.add(listScroller);
            listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    //Lay out the buttons from left to right.
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
            buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
            buttonPane.add(Box.createHorizontalGlue());
            buttonPane.add(cancelButton);
            buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
            buttonPane.add(setButton);
    //Put everything together, using the content pane's BorderLayout.
            Container contentPane = getContentPane();
            contentPane.add(listPane, BorderLayout.CENTER);
            contentPane.add(buttonPane, BorderLayout.SOUTH);
            pack();
        public void mouseClicked(MouseEvent e) {
            System.out.println("Mouse Click");
        public void mousePressed(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseReleased(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseEntered(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseExited(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseDragged(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseMoved(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
         * This is here so that you can view ListDialog even if you
         * haven't written the code to include it in a program.
    }

  • Issue with re-sizing JTable Headers, JTabbedPane and JSplit pane

    Ok, hopefully I'll explain this well enough.
    In my Swing application I have a split pane, on the left hand side is a JTable and on the right hand is a JTabbedPane. In the tabs of the JTabbedPane there are other JTables.
    In order to make the rows in the JTable on the left and the JTable(s) on the right line up, the Table Header of all the tables is set to the size of the tallest (deepest?) table header.
    Hopefully so far I'm making sense. Now to get to the issue. One of the tables has a number of columns equal to the value on a NumberSpinner (it represents a number of weeks). When this value is changed the table is modified so that it contains the correct number of columns. As the table is re-drawn the table header goes back to its default size so I call my header-resize method to ensure it lines up.
    The problem is this: if I change the number of weeks when selecting a tab other than the one containing my table then everything is fine, the table header is re-sized and everything lines up. If I change the number of weeks with the tab containing the table selected, the column headers stay at their standard size and nothing lines up.
    To make things more complicated, I also put System.out.println's in as every method called in the process to obtain the size of the table header. And every println returned the same height, the height the table header should be.. So I'm really confused.
    Could anyone shed any light on this?
    Thanks.

    Okay I managed to solve the problem by explicitly revalidating and repainting the table header.
    Not sure why it wasnt doing it properly for that table when all the others where fine.
    Oh well...

  • Modal JDialog editor in JTable

    I'm using a JDialog as an editor in a JTable. It instatiated from a class that extends TableCellEditor. When I select a value in the dialog, I call the fireEditingStopped method of the editor. The table then calls the editor's getCellEditorValue method, which returns the value I selected. So far, so good.
    However, if I make the dialog modal, the table doesn't call the getCellEditorValue method, unless I click in another cell. This is obviously fairly useless - any ideas folks?
    Thanks...

    Hello there
    I had a similar problem and I spent ages trying to figure it out. I take it the cell you are trying to edit is already empty. What it is, while you have a cell editor on the cell in question, you dont have a cell renderer which is responsible for actually drawing the selected item in the cell once the editing combobox has closed. The way I found around this problem was to fill the cells of the table with some default data when the table is initalised, this meant that a suitable renderer for the type of data I was trying to display was automatically assigned.
    Hope this helps

  • JTable column sizing

    Hi all. Getting frustrated. How can I size a column's width to fit the size its longest element?
    In the example below, "Test Column" gets sized to fit the width of the table instead of its data. So the first row's data is cut off. I want "Test Column" to auto resize itself to be as long as that String. Anyone know? Thanks.
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.table.DefaultTableModel;
    public class TableTest extends JPanel{
         GridBagConstraints gbc;
         public TableTest(){
              super(new GridLayout(1,0));
              createTable();
         public void createTable(){
              JPanel panel = new JPanel(new GridBagLayout());
              panel.setBorder(BorderFactory.createTitledBorder("Attributes"));
              DefaultTableModel model = new DefaultTableModel();
              model.addColumn("Test Column",new Object[]{"asdasdasdssssasdddddddddddddddddddddddddddssssssssssaSD"});
              JTable table = new JTable(model);
              table.setEnabled(false);    
         //     table.setPreferredSize(new Dimension(150,150));
              JScrollPane scroll = new JScrollPane(table);
              scroll.setPreferredSize(new Dimension(150,150));
              scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
              gbc = new GridBagConstraints();
              gbc.weightx = 1;
              gbc.weighty = 1;
              gbc.insets = new Insets(10,10,10,10);
              gbc.fill = GridBagConstraints.BOTH;
              panel.add(scroll, gbc);
              gbc = new GridBagConstraints();
              gbc.gridy = 1;
              gbc.weightx = 1;
              gbc.weighty = 1;     
              gbc.fill = GridBagConstraints.HORIZONTAL;
              gbc.anchor = GridBagConstraints.SOUTH;
              add(panel,gbc);
          private static void createAndShowGUI() {
                 //Create and set up the window.
                 JFrame frame = new JFrame("TableDemo");
                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 //Create and set up the content pane.
                 TableTest newContentPane = new TableTest();
                 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) {
              System.out.println("Start");
            //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();
    }

    I'm aware of the recent problems with the forum search. What I suggested was that you spend some time reading answered posts relating to problems that you have an interest in.
    That's the way I learned pretty much all I know, so I'm not spouting hot air here :)
    db

  • MouseEvent and KeyEvent for JTable in JDialog is not functioning

    What is working for a JFrame not working for a JDialog ???
    I created a JTable in JDialog and the mouse event is not working in JTable
    what I have to do ???
    Edited by: amnonm on Apr 25, 2009 3:07 AM

    This is what I could send I hope you will understand from this what is my problem.
    line 13 ????
    public TableRoughGroupDiamondDDetails(Vector Data)
             data = Data;
              addWindowListener(closeWindow);
    //                          SET HEADER AND DATABASE TO THE TABLE
              Container contentPane = getContentPane();
              contentPane.setLayout(null);
              tp      = this;
              sp = TableSimularSales(data);
              Enumeration enu = data.elements();
              arcivePanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
              getContentPane().add(arcivePanel);
              JLabel frm = new JLabel(The stone is from arcive, no details !");
              frm.setFont(new Font("Arial", Font.BOLD, 30));
              arcivePanel.add(frm);
              detailsPanel = PanelContainer();
              if(enu.hasMoreElements())
                   setChanges((Object[])data.elementAt(0));
                   sp.setBounds(0,0,759,245);
              else
                   sp.setBounds(0,0,759,436);
              getContentPane().add( sp );
              JPanel p = new JPanel();
            JLabel soldLabel = new JLabel("Sold:");
            JLabel arciveLabel = new JLabel(""Arcive:");
            JLabel stockLabel = new JLabel("In stock:");
            JButton sold = new JButton();
            JButton arcive = new JButton();
              JButton stock = new JButton();
              sold.setBackground(new Color(196,215,255));
              arcive.setBackground(new Color(210,235,221));
              stock.setBackground(new Color(250,178,178));
              sold.setEnabled(false);
              arcive.setEnabled(false);
              stock.setEnabled(false);
              p.setBorder(new BevelBorder(BevelBorder.LOWERED));
              getContentPane().add( p );
              p.setBounds(0,438,759,27);
             setVisible(true);
              tableView.addKeyListener(new KeyAdapter()
                   int row_int;
                   public void keyPressed(KeyEvent mouseEvent)
                        row_int =tableView.getSelectedRow();
                        if(row_int<0)
                             return;
                        setChanges((Object[])data.elementAt(row_int));
                   public void keyReleased(KeyEvent mouseEvent)
                        row_int =tableView.getSelectedRow();
                        if(row_int<0)
                             row_int=0;
                        setChanges((Object[])data.elementAt(row_int));
              tableView.addMouseListener(new MouseAdapter()
                   int row_int;
                   public void mousePressed(MouseEvent mouseEvent)
                        row_int =tableView.getSelectedRow();
                        if(row_int<0)
                             return;
                        setChanges((Object[])data.elementAt(row_int));
                   public void mouseReleased(MouseEvent mouseEvent)
                        row_int =tableView.getSelectedRow();
                        if(row_int<0)
                             row_int=0;
                        setChanges((Object[])data.elementAt(row_int));
         

  • How can I print a JTable with varying sized rows?

    How can I print a JTable with varying sized rows?
    I am using java 1.5, and have made a cell renderer to display multiple lines in rows and it works well, however when I use the new print method it doesn't separate the cells onto the next page, it cuts them and will print the rest of the row on the next page. Does anyone know how I might go about making this happen?
    cheers

    I finally found out the reason, The column heights were being set through my renderer. If I hadn't viewed them in the scrollpane the row heights were set to the default height of 16 therefore when the print method was called it clipped all the rows wrong, what is weird though is that the row height printed out correctly but the clipping area was set wrong because it was getting the default value of 16 from rowHeight(row).

  • Headache: Data Xchange from JDialog to JTable using JButton

    My head is spinning about how to get this to work. What is really confusing me is the data exchange from the JDialog.
    I have a JTable where one of the columns uses a JButton as the cell editor for each cell in that column. That part seems to be no problem. The JButton is labeled "Define Staff..."
    When the user clicks on the JButton, a JDialog containing a JList is to appear. If the user clicks cancel, the JDialog is disposed and nothing happens. If the user clicks OK, the selected items are to be returned to the cell in some way and the label of the JButton is to change to "Modify Staff..."
    How can I return the list from the JDialog to the "cell" so that when I access the cell using getValueAt() I get the list of values, and not the JButton object?

    Thanks.
    The actual JButton is inside a JTable cell though.
    Where would I add the event handler for the button? In the editor? In the renderer?
    Excerpt from the JTable file:
         PositionTable.getColumn("Staff").setCellRenderer(new ButtonRenderer());
         PositionTable.getColumn("Staff").setCellEditor(new ButtonEditor(new JCheckBox()));ButtonEditor.java
    public class ButtonEditor extends DefaultCellEditor {
      protected JButton button;
      private String    label;
      private boolean   isPushed;
      public ButtonEditor(JCheckBox checkBox) {
        super(checkBox);
        button = new JButton();
        button.setOpaque(true);
        button.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            fireEditingStopped();
      public Component getTableCellEditorComponent(JTable table, Object value,
                       boolean isSelected, int row, int column) {
        if (isSelected) {
        } else{
          button.setForeground(table.getForeground());
          button.setBackground(table.getBackground());
        label = (value ==null) ? "" : value.toString();
        isPushed = true;
        return button;
      public Vector<String> getCellEditorValue() {
        Vector<String> staff = new Vector<String>();
        if (isPushed)  {
          staffSelector temp = new staffSelector(null,true,"Building Supervisor");
          temp.setVisible(true);
          staff = temp.getSelectedStaff(true);
        isPushed = false;
       // return new String( label ) ;
       //Return vector people selected.
       return staff;
      public boolean stopCellEditing() {
        isPushed = false;
        return super.stopCellEditing();
      protected void fireEditingStopped() {
        super.fireEditingStopped();
    }ButtonRenderer.java
    public class ButtonRenderer extends JButton implements TableCellRenderer {
      public ButtonRenderer() {
        setOpaque(true);
      public Component getTableCellRendererComponent(JTable table, Object value,
                       boolean isSelected, boolean hasFocus, int row, int column) {
        if (isSelected) {
          setForeground(table.getForeground());
          setBackground(table.getBackground());
        } else{
          setForeground(table.getForeground());
          setBackground(UIManager.getColor("Button.background"));
        setText( (value ==null) ? "Define Staff..." : "Modify Staff..." );
        return this;
    }Message was edited by:
    AsymptoticCoder
    Made an error.

  • Including a JDialog or JFrame between two rows in a JTable

    Hello,
    Is it possible to include a JFrame or JDialog between two rows in a JTable?
    I would like two have a JFrame or JDialog which shift all the rows below the row that I want in order to include a JFrame between them.
    Thank in advance

    [http://forums.sun.com/thread.jspa?threadID=5331582]

  • Update JTable from a JDialog

    I'm wanting to update a JTable I have on a JFrame. This JFrame has a button on it which opens a JDialog box which populates a database. The main JFrame's JTable (ReceivedTable) holds this information. When a user inputs some more information and closes the dialog, I'd like to update the JTable in the main JFrame, but am not sure how to go about doing this. Can someone give me an idea to work from.
    Thanks.

    G'day mate,
    Make an extension of JDialog like so:
    //import appropriate classes here
    public class MyDialog extends JDialog implements ActionListener {
         //you would have some text fields or such here
         public MyDialog(Frame parent, String name) {
              super(parent, name, true);
              JPanel cp = (JPanel)getContentPane();
              //cp.add(fields here!);
              JButton submit = new JButton("Submit");
              submit.addActionListener(this);
              cp.add(submit);
         public void actionPerformed(ActionEvent ae) {
              Vector data = new Vector();
              //populate 2d data vector with data for the table
              Vector column_names = new Vector();
              //names for your table columns
              ((DefaultTableModel)((JFrame)getOwner()).getTable().getModel()).setDataVector(data, column_names);
              dispose();
    Note: In your JFrame you will need to define a method getTable().
    I think that should work for you... Obviously you'll have to add in a lot of code yourself, but that should be a reasonable skeleton.
    Good luck,
    Muel.

  • JTable  with headers extending JDialog

    I am creating a class file extending JDialog. I have populated the JTable on the form and want to include headers on the table. The dialog form opens and the table is visible and populated but with no headers. Has anyone had success with headers on JTables when creating a JDialog object?
    I have other tables created with headers so I wondered if the problem was with JDialog?

    inorder to make headers visible you need to add scroll pane to table,
    either by:
    JScrollPane scrollPane = JTable.createScrollPaneForTable(table);
    or:
    scrollPane = new JScrollPane(table);
    unless there's no scroller, you can't see headers.

  • JDialog sizing problems

    First of all, just let me say I have read everything there is available on layout managers and how pack() and validate() work.
    My problem is simply that my JDialog appears far longer than its components, and I can't see why.
    I've created screenshots of the desired appearance and the actual appearance:
    http://www.komododave.co.uk/gallery/main.php?g2_itemId=167
    The first 'undesired' screenshot shows what the JDialog looks like upon instantiation. The second shows what it looks like once you manually shrink it in the Y direction by more than about 10 pixels.
    I don't understand how the maximum size can exceed the Dimension I set with 'dialog.setMaximumSize(...', since I'm using BoxLayout for the JDialog and that respects a given maximum size.
    The constructor creating the JDialog is shown here:
              public AbstractSelectionDialog(Vector<String> argVector, String title,
                        String message) {
                   Vector<String> vector = argVector;
                   // create new modal JDialog
                   final JDialog dialog = new JDialog(Silk.getFrame(), title, true);
                   // set boxlayout for dialog frame
                   dialog.getContentPane().setLayout(new BoxLayout(dialog.getContentPane(),
                             BoxLayout.Y_AXIS));
                   // set default close operation
                   dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                   // create ButtonGroup to enforce exclusive collection choice
                   final ButtonGroup buttonGroup = new ButtonGroup();
                   // initialise other components
                   // use fake space for label rather than use another HorizontalGlue
                   JLabel label = new JLabel("   " + message);
                   // panel containing collection selection
                   JPanel selectionPanel = new JPanel();
                   // run initialiser methods
                   JPanel buttonPanel = (JPanel) createButtons(buttonGroup, dialog);
                   AbstractButton selection[] = createSelection(vector, buttonGroup,
                             selectionPanel);
                   // scrollPane containing collection panel
                   JScrollPane scrollPane = new JScrollPane(selectionPanel,
                             JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                             JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                   // panel containing scroll pane
                   JPanel scrollPanel = new JPanel();
                   scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.X_AXIS));
                   selectionPanel.setLayout(new GridLayout(vector.size(), 1));
                   // assemble component structure
                   scrollPanel.add(Box.createHorizontalGlue());
                   scrollPanel.add(scrollPane);
                   scrollPanel.add(Box.createHorizontalGlue());
                   dialog.add(label);
                   dialog.add(scrollPanel);
                   dialog.add(buttonPanel);
                   // set all components to be left-justified
                   label.setAlignmentX(0.0F);
                   scrollPanel.setAlignmentX(0.0F);
                   selectionPanel.setAlignmentX(0.0F);
                   buttonPanel.setAlignmentX(0.0F);
                   // set higher-level component sizes
                   Silk.setSizeAttributes(label, 300, 30, true);
                   selectionPanel.setMaximumSize(new Dimension(250, 400));
                   scrollPane.setMinimumSize(new Dimension(250, 50));
                   scrollPane.setMaximumSize(new Dimension(250, 400));
                   dialog.setMinimumSize(new Dimension(300, 200));
                   dialog.setMaximumSize(new Dimension(300, 500));
                   dialog.pack();
                   // set components to be opaque
                   label.setOpaque(true);
                   scrollPane.setOpaque(true);
                   selectionPanel.setOpaque(true);
                   // display dialog frame
                   //dialog.setResizable(false);
                   dialog.setVisible(true);
              }The 'createButtons' method it uses is here:
         public JPanel createButtons(ButtonGroup bg, JDialog jd) {
                   final ButtonGroup buttonGroup = bg;
                   final JDialog dialog = jd;
                   // confirmation buttons
                   JButton okBtn = new JButton();
                   JButton cancelBtn = new JButton();
                   JButton newBtn = new JButton();
                   // panel containing OK and CANCEL buttons
                   JPanel bothPanel = new JPanel();
                   // panel containing NEW COLLECTION button
                   JPanel newPanel = new JPanel();
                   // panel to contain all other button panels
                   JPanel confPanel = new JPanel();
                   confPanel.setLayout(new BoxLayout(confPanel, BoxLayout.X_AXIS));
                   newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.X_AXIS));
                   bothPanel.setLayout(new BoxLayout(bothPanel, BoxLayout.Y_AXIS));
                   // definition of button Actions
                   okBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                             Actions.addScript(buttonGroup.getSelection()
                                       .getActionCommand(), null);
                             dialog.dispose();
                   cancelBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                             dialog.dispose();
                   newBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                             dialog.dispose();
                             new Actions.NewCollectionAction().actionPerformed(ae);
                             new Actions.NewScriptAction().actionPerformed(ae);
                   // override action-set button text
                   okBtn.setText("Ok");
                   cancelBtn.setText("Cancel");
                   newBtn.setText("Add New Collection");
                   // set button sizes
                   Silk.setSizeAttributes(okBtn, 115, 30, true);
                   Silk.setSizeAttributes(cancelBtn, 115, 30, true);
                   Silk.setSizeAttributes(newBtn, 250, 35, true);
                   // set opaque buttons
                   confPanel.setOpaque(true);
                   okBtn.setOpaque(true);
                   cancelBtn.setOpaque(true);
                   // assemble components
                   confPanel.add(Box.createHorizontalGlue());
                   confPanel.add(okBtn);
                   confPanel.add(Box.createRigidArea(new Dimension(20, 0)));
                   confPanel.add(cancelBtn);
                   confPanel.add(Box.createHorizontalGlue());
                   newPanel.add(Box.createHorizontalGlue());
                   newPanel.add(newBtn);
                   newPanel.add(Box.createHorizontalGlue());
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 10)));
                   bothPanel.add(confPanel);
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                   bothPanel.add(newPanel);
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 10)));
                   bothPanel.setMaximumSize(new Dimension(300, 100));
                   return bothPanel;
              }And the createSelection() method it uses is defined here:
         public AbstractButton[] createSelection(Vector<String> argVector,
                        ButtonGroup buttonGroup, JPanel selectionPanel) {
                   Vector<String> vector = argVector;
                   JRadioButton selection[] = new JRadioButton[vector.size()];
                   for (int i = 0; i < vector.size(); i++)
                        selection[i] = new JRadioButton(vector.get(i));
                   AbstractButton current;
                   for (byte i = 0; i < selection.length; i++) {
                        current = selection;
                        // set action command string to later identify button that's
                        // selected
                        current.setActionCommand(vector.get(i));
                        // fix button's size
                        Silk.setSizeAttributes(current, 250, 30, true);
                        // set button's colour
                        current.setBackground(Color.WHITE);
                        // add button to buttongroup
                        buttonGroup.add(current);
                        // add button to appropriate JPanel
                        selectionPanel.add(current);
                   // ensure one button is selected to prevent pressing OK with no
                   // selection
                   selection[0].setSelected(true);
                   return selection;
    Please help if you can.
    Thank you.
    - Dave

    Yeah sorry camickr, I need to get into the habit of posting SSCCEs.
    Here it is in SSCCE form:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.AbstractButton;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import java.util.Vector;
    public class Testing {
         // prevent instantiation
         private Testing() {
         public interface SelectionDialog {
              // produces a component containing all dialog buttons
              public Component createButtons(ButtonGroup bg, JDialog jd);
              // produces an array of the selection buttons to be used
              public abstract AbstractButton[] createSelection(
                        Vector<String> selectionVector, ButtonGroup buttonGroup,
                        JPanel selectionPanel);
         abstract static class AbstractSelectionDialog implements SelectionDialog {
              public AbstractSelectionDialog() {
                   Vector<String> vector = new Vector<String>();
                   String title = "Broken dialog box";
                   String message = "Why is the maximum size exceedable, hmm?";
                   /* for sscce */
                   vector.add("choice 1");
                   vector.add("choice 2");
                   vector.add("choice 3");
                   vector.add("choice 4");
                   vector.add("choice 5");
                   vector.add("choice 6");
                   vector.add("choice 7");
                   vector.add("choice 8");
                   vector.add("choice 9");
                   vector.add("choice 10");
                   vector.add("choice 11");
                   vector.add("choice 12");
                   vector.add("choice 13");
                   vector.add("choice 14");
                   vector.add("choice 15");
                   vector.add("choice 16");
                   vector.add("choice 17");
                   vector.add("choice 18");
                   // create new modal JDialog
                   final JDialog dialog = new JDialog(Silk.getFrame(), title, true);
                   // set boxlayout for dialog frame
                   dialog.getContentPane().setLayout(new BoxLayout(dialog.getContentPane(),
                             BoxLayout.Y_AXIS));
                   // set default close operation
                   dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                   // create ButtonGroup to enforce exclusive collection choice
                   final ButtonGroup buttonGroup = new ButtonGroup();
                   // initialise other components
                   // use fake space for label rather than use another HorizontalGlue
                   JLabel label = new JLabel("   " + message);
                   // panel containing collection selection
                   JPanel selectionPanel = new JPanel();
                   // run initialiser methods
                   JPanel buttonPanel = (JPanel) createButtons(buttonGroup, dialog);
                   AbstractButton selection[] = createSelection(vector, buttonGroup,
                             selectionPanel);
                   // scrollPane containing collection panel
                   JScrollPane scrollPane = new JScrollPane(selectionPanel,
                             JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                             JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                   // panel containing scroll pane
                   JPanel scrollPanel = new JPanel();
                   scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.X_AXIS));
                   selectionPanel.setLayout(new GridLayout(vector.size(), 1));
                   // assemble component structure
                   scrollPanel.add(Box.createHorizontalGlue());
                   scrollPanel.add(scrollPane);
                   scrollPanel.add(Box.createHorizontalGlue());
                   dialog.add(label);
                   dialog.add(scrollPanel);
                   dialog.add(buttonPanel);
                   // set all components to be left-justified
                   label.setAlignmentX(0.0F);
                   scrollPanel.setAlignmentX(0.0F);
                   selectionPanel.setAlignmentX(0.0F);
                   buttonPanel.setAlignmentX(0.0F);
                   // set higher-level component sizes
                   Silk.setSizeAttributes(label, 300, 30, true);
                   selectionPanel.setMaximumSize(new Dimension(250, 400));
                   scrollPane.setMinimumSize(new Dimension(250, 50));
                   scrollPane.setMaximumSize(new Dimension(250, 400));
                   dialog.setMinimumSize(new Dimension(300, 200));
                   dialog.setMaximumSize(new Dimension(300, 500));
                   dialog.pack();
                   // set components to be opaque
                   label.setOpaque(true);
                   scrollPane.setOpaque(true);
                   selectionPanel.setOpaque(true);
                   // display dialog frame
                   // dialog.setResizable(false);
                   dialog.setVisible(true);
         protected static class ChooseCollectionDialog extends
                   AbstractSelectionDialog implements SelectionDialog {
              public ChooseCollectionDialog() {
                   super();
              public JPanel createButtons(ButtonGroup bg, JDialog jd) {
                   final ButtonGroup buttonGroup = bg;
                   final JDialog dialog = jd;
                   // confirmation buttons
                   JButton okBtn = new JButton();
                   JButton cancelBtn = new JButton();
                   JButton newBtn = new JButton();
                   // panel containing OK and CANCEL buttons
                   JPanel bothPanel = new JPanel();
                   // panel containing NEW COLLECTION button
                   JPanel newPanel = new JPanel();
                   // panel to contain all other button panels
                   JPanel confPanel = new JPanel();
                   confPanel.setLayout(new BoxLayout(confPanel, BoxLayout.X_AXIS));
                   newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.X_AXIS));
                   bothPanel.setLayout(new BoxLayout(bothPanel, BoxLayout.Y_AXIS));
                   // definition of button Actions
                   okBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                             dialog.dispose();
                   cancelBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                             dialog.dispose();
                   newBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                   // override action-set button text
                   okBtn.setText("Ok");
                   cancelBtn.setText("Cancel");
                   newBtn.setText("Add New Collection");
                   // set button sizes
                   Silk.setSizeAttributes(okBtn, 115, 30, true);
                   Silk.setSizeAttributes(cancelBtn, 115, 30, true);
                   Silk.setSizeAttributes(newBtn, 250, 30, true);
                   // set opaque buttons
                   confPanel.setOpaque(true);
                   okBtn.setOpaque(true);
                   cancelBtn.setOpaque(true);
                   // assemble components
                   confPanel.add(Box.createHorizontalGlue());
                   confPanel.add(okBtn);
                   confPanel.add(Box.createRigidArea(new Dimension(20, 0)));
                   confPanel.add(cancelBtn);
                   confPanel.add(Box.createHorizontalGlue());
                   newPanel.add(Box.createHorizontalGlue());
                   newPanel.add(newBtn);
                   newPanel.add(Box.createHorizontalGlue());
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 10)));
                   bothPanel.add(confPanel);
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                   bothPanel.add(newPanel);
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 10)));
                   bothPanel.setMaximumSize(new Dimension(300, 100));
                   return bothPanel;
              public AbstractButton[] createSelection(Vector<String> argVector,
                        ButtonGroup buttonGroup, JPanel selectionPanel) {
                   Vector<String> vector = argVector;
                   JRadioButton selection[] = new JRadioButton[vector.size()];
                   for (int i = 0; i < vector.size(); i++)
                        selection[i] = new JRadioButton(vector.get(i));
                   AbstractButton current;
                   for (byte i = 0; i < selection.length; i++) {
                        current = selection;
                        // set action command string to later identify button that's
                        // selected
                        current.setActionCommand(vector.get(i));
                        // fix button's size
                        Silk.setSizeAttributes(current, 250, 30, true);
                        // set button's colour
                        current.setBackground(Color.WHITE);
                        // add button to buttongroup
                        buttonGroup.add(current);
                        // add button to appropriate JPanel
                        selectionPanel.add(current);
                   // ensure one button is selected to prevent pressing OK with no
                   // selection
                   selection[0].setSelected(true);
                   return selection;
         public static void main(String args[]) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        new ChooseCollectionDialog();
    I considered that the GridLayout might be a problem, but surely the fact that it's ultimately contained in a BoxLayout (which [i]does respect maximum size) means the maximum size still shouldn't be exceedable?
    Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Sizing JTable columns

    Hello
    I have a couple of tables with two columns, and I want to make one column about 80% of the width, and the other the rest. I can currently do this through the UI, but I can't figure out a way to have it come up that way automaticaly. One thing I was thinking of was to get a TableColumn and then SetPreferedSize, but when I look at my table the identifier for both columns is set to null so I don't know what to feed the table's GetTableColumn. And I am not sure where I'm suposed to set the identifier. The Table is made from a TableModel. Any suggestions? Or am I going about it in the wrong way and maybe need to do something with layouts maybe? Thanks.

    do some like this
    datosPrecaptura.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    (datosPrecaptura.getColumnModel().getColumn(0)).setPreferredWidth( 60 );
    (datosPrecaptura.getColumnModel().getColumn(1)).setPreferredWidth( 485 );

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

Maybe you are looking for