Setting column names in JTable

can n e one tell me how to set column names for JTable..
i don't wanna use the JTable constructor ... cuz
my column names change...

this is how i did it once...hope it helps
Vector columnNames = new Vector();
JTable previewTable = new JTable();
previewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
previewScrollPane.getViewport().add(previewTable, null);
int colNo = 2; // i am displaying 2 columns
columnNames.add("Col One");
columnNames.add("Col Two");
String[] tableColumnNames = {"Id Name","Type"};
DefaultTableModel aModel = (DefaultTableModel) previewTable.getModel();
aModel.setColumnIdentifiers(tableColumnNames);
//add data to the table
.//loop
aModel.addRow(objects);
previewTable.revalidate();
previewTable.setModel(aModel);

Similar Messages

  • How to set column names when not using object of row data in  constructer

    hello i am using JTable constructer as
    public JTable(int numRows,
    int numColumns)
    can i set column names for the columns .How?

    hi,
    sure you can: Create a subclass of DefaultTableModel and overwrite the method public String getColumnName(int) which returns the column name of a specific column. Then use this subclass as the data model for the table.
    best regards, Michael

  • Setting Column Names in Dynamic Pivot Query

    Hi all,
    I'm having trouble setting column names in a dynamic pivot query and was wondering if someone could please help me figure out what I need to do.
    To help you help me, I've setup an example scenario in my hosted account. Here's the login info for my hosted site at [http://apex.oracle.com]
    Workspace: MYHOSTACCT
    Username : DEVUSER1
    Password : MYDEVACCTAnd, here is my test application info:
    ID     : 42804
    Name   : dynamic query test
    Page   : 1
    Table 1: PROJECT_LIST         (Alias = PL...  Listing of Projects)
    Table 2: FISCAL_YEAR          (Alias = FY...  Lookup table for Fiscal Years)
    Table 3: PROJECT_FY           (Alias = PF...  Intersection table containing project fiscal years)
    Table 4: PROJECT_FY_HEADCOUNT (Alias = PFH... Intersection table containing headcount per project and fiscal year)Please forgive the excessive normalization for this example, as I wanted to keep the table structure similar to my real application, which has much more going on.
    In my sample, I have the "Select Criteria" region, where the user specifies the project and fiscal year range that he or she would like to report. Click the Search button, and the report returns the project headcount in a pivoted fashion for the fiscal year range specified.
    I've got it working using a hard-coded query, which is displayed in the "Hardcoded Query" region. In this query, I basically return all years, and set conditions on each column which determines whether that column should be displayed or not based on the range selected by the user. While this works, it is not ideal, as there could be many more fiscal years to account for, and this is not very dynamic at all. Anytime a fiscal year is added to the FISCAL_YEAR table, I'd have to update this page.
    So, after reading all of the OTN SQL pivot forums and "Ask Tom" pivot thread, I've been able to create a second region labeled "Dynamic Query" in which I've created a dynamic query to return the same results. This is a much more savvy solution and works great; however, the column names are generic in the report.
    I had to set the query to parse at runtime since the column selection list is dynamic, which violates SQL rules. Can anyone please help me figure out how I can specify my column names in the dynamic query region to get the same column values I'm getting in the hardcoded region?
    Please let me know if you need anymore information, and many thanks in advance!
    Mark

    Hi Tony,
    Thanks so much for your response. I've had to study up on the dbms_sql package to understand your function... first time I've used it. I've fed my dynamic query to your function and see that it returns a colon delimited list of the column names; however, I think I need a little more schooling on how and where exactly to apply the function to actually set the column names in APEX.
    From my test app, here is the code for my dynamic query. I've got it in a "PL/SQL function body returning sql query" region:
    DECLARE 
      v_query      VARCHAR2(4000);
      v_as         VARCHAR2(4);
      v_range_from NUMBER;
      v_range_to   NUMBER;         
    BEGIN
      v_range_from := :P1_FY_FROM;
      v_range_to   := :P1_FY_TO;
      v_query      := 'SELECT ';
      -- build the dynamic column selections by looping through the fiscal year range.
      -- v_as is meant to specify the column name as (FY10, FY11, etc.), but it's not working.
      FOR i IN v_range_from.. v_range_to  LOOP
        v_as    := 'FY' || SUBSTR(i, 3, 4);
        v_query := v_query || 'MAX(DECODE(FY_NB,' || i || ',PFH_HEADCOUNT,0)) '
          || v_as || ',';
      END LOOP;
      -- add the rest of the query to the dynamic column selection
      v_query := rtrim(v_query,',') || ' FROM ('
        || 'SELECT FY_NB, PFH_HEADCOUNT FROM ('
        || 'SELECT FY_ID, FY_NB FROM FISCAL_YEAR) A '
        || 'LEFT OUTER JOIN ('
        || 'SELECT FY_ID, PFH_HEADCOUNT '
        || 'FROM PROJECT_FY_HEADCOUNT '
        || 'JOIN PROJECT_FY USING (PF_ID) '
        || 'WHERE PL_ID = ' || :P1_PROJECT || ') B '
        || 'ON A.FY_ID = B.FY_ID)';
      RETURN v_query;
    END;I need to invoke GET_QUERY_COLS(v_query) somewhere to get the column names, but I'm not sure where I need to call it and how to actually set the column names after getting the returned colon-delimited list.
    Can you (or anyone else) please help me get a little further? Once again, feel free to login to my host account to see it first hand.
    Thanks again!
    Mark

  • How to dynamically set column name in Answers

    Hi.
    How to dynamically set column name in Answers, for example I want to put presentation variable in column header. Is this possible?
    Regards,
    Goran Ocko
    http://108obiee.blogspot.com/

    May be a rude way .. but it works.
    Add narrative view and use Java script to change the column headings based on the variables.
    <script language="javascript" type="text/javascript">
    var a = document.getElementById('idResultsTableParent');
    var rows= a.getElementsByTagName('tr');
    rows[1].cells[1].innerText ="@{Presentation Variable}";
    </script>
    Editing the same post to remove irrelevant information.
    - Girish

  • How can I set column width in JTable?

    How can I set column width in JTable?

    Also, read the JTable API before posting questions. You will find a link to the Swing tutorial on "How to Use Tables", which contains an example of doing exactly this.

  • How to set column names in OVS search help of ALV EDIT

    Hi All,
    I have a OVS search help for my ALV EDIT column.This OVS will have two columns,I need to give the names(name1 , name2)  to the columns.
    I am writing the below codo in phase 0.
          ls_text-name = 'Column1'.
          ls_text-value = 'name1'.
          INSERT ls_text INTO TABLE lt_column_texts.
          ls_text-name = 'Column2'.
          ls_text-value = 'name2'.
          INSERT ls_text INTO TABLE lt_column_texts.
          ovs_callback_object->set_configuration(
                    label_texts  = lt_label_texts
                    column_texts = lt_column_texts
                    group_header = lv_group_header
                    window_title =  lv_window_title
                    table_header = lv_table_header
                    col_count    = 2
                    row_count    = 20 ).
    Below code in Phase 3.
          Assign ovs_callback_object->selection->* to <ls_selection>.
          if <ls_selection> is assigned.
            ovs_callback_object->context_element->set_attribute(
            name = `ATR1`
            value = <ls_selection>-Column1 ).
          endif.
    But,the column names are not getting set.Please provide your inputs.
    Regards,
    Salma

    hi,
    About your requirement, i don't know why you need to code in "Phase 3" of OVS.
    "Phase 3" is used for transporting your selected value to Your ALV.
    I think, the reason why you loose the result table including your customized column title, is that you loose the "Phase 2".
    Generally, in the past i used OVS as the following code simply.Just one example:
    * declare data structures for the fields to be displayed and
    * for the table columns of the selection list, if necessary
      types:
        begin of lty_stru_input,
    *   add fields for the display of your search input here
          carrid type string,
          connid type string,
        end of lty_stru_input.
      types:
        begin of lty_stru_list,
    *   add fields for the selection list here
          carrid type string,
          connid type string,
          text   type string,
        end of lty_stru_list.
      data: ls_search_input  type lty_stru_input,
            lt_select_list   type standard table of lty_stru_list,
            ls_text          type wdr_name_value,
            lt_label_texts   type wdr_name_value_list,
            lt_column_texts  type wdr_name_value_list,
      case ovs_callback_object->phase_indicator.
        when if_wd_ovs=>co_phase_0.  "configuration phase, may be omitted
    *   in this phase you have the possibility to define the texts,
    *   if you do not want to use the defaults (DDIC-texts)
          ls_text-name = 'CARRID'.  "must match a field name of search
          ls_text-value = 'Search Field-Carrid'.
          insert ls_text into table lt_label_texts.
          ls_text-name = 'CONNID'.  "must match a field name of search
          ls_text-value = 'Search Field-Connid'.
          insert ls_text into table lt_label_texts.
          ls_text-name = 'CARRID'.  "must match a field in list structure
          ls_text-value = 'Result-Carrid'.
          insert ls_text into table lt_column_texts.
          ls_text-name = 'CONNID'.  "must match a field in list structure
          ls_text-value = 'Result-Connid'.
          insert ls_text into table lt_column_texts.
          ls_text-name = 'TEXT'.  "must match a field in list structure
          ls_text-value = 'Result-Text'.
          insert ls_text into table lt_column_texts.
          lv_group_header = 'Group Header'.
          lv_window_title = 'Window Title'.
          lv_table_header = 'Table Header'.
          ovs_callback_object->set_configuration(
                    label_texts  = lt_label_texts
                    column_texts = lt_column_texts
                    group_header = lv_group_header
                    window_title = lv_window_title
                    table_header = lv_table_header
                    col_count    = 3
                    row_count    = 8 ).
    when if_wd_ovs=>co_phase_2.
    *   If phase 1 is implemented, use the field input for the
    *   selection of the table.
    *   If phase 1 is omitted, use values from your own context.
          if ovs_callback_object->query_parameters is not bound.
    ******** TODO exception handling
          endif.
          assign ovs_callback_object->query_parameters->*
                                  to <ls_query_params>.
    SELECT * INTO CORRESPONDING FIELDS OF TABLE lt_select_list FROM ZTABLE_FLIGHT
                           WHERE CARRID LIKE lw_carrid
                                 AND CONNID LIKE lw_connid
    *ovs_callback_object->set_output_table( output = lt_select_list ).*
    Hope it can help.
    Best wishes.

  • Set column width in JTable

    I have two columns in a JTable and I am trying to set the column width for the first.
    I am trying to this by
    getDataTbl().getColumnModel().getColumn(0).setHeaderValue("Index");
    getDataTbl().getColumnModel().getColumn(1).setHeaderValue(" Data ");
    int width = ((String)getDataTbl().getColumnModel().getColumn(0).getHeaderValue()).length();
    getDataTbl().getColumnModel().getColumn(0).setPreferredWidth(width);
    but it doesn't reset the width. I want the first column width to be smaller than the second which should be much larger width.
    Any suggessions to this?
    Thanks.

    Hi there
    Use this JTable method
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);This should solve your resize problem
    ICE

  • How can I set column headers in JTable?

    I only want to set 3 column headers in JTable (without TabelModel). Can you help me?

    Hello dn77,
    Here's is a little sample I just rigged up, hope it helps.
    import java.awt.*;
    import javax.swing.*;
    public class TestOne{
         public static void main(String arg[]) {
              Object rows[][] = {
                   {"One", "1", "I"},
                   {"Two", "2", "II"},
                   {"Three", "3", "III"},
                   {"Four", "4", "IV"},
                   {"Five", "5", "V"},
                   {"Six", "6", "VI"},
                   {"Seven", "7", "VII"},
                   {"Eight", "8", "VIII"},
                   {"Nine", "9", "IX"},
                   {"Ten", "10", "X"},
                   {"Eleven", "11", "XI"},
                   {"Twelve", "12", "XII"},
                   {"Thirteen", "13", "XIII"},
                   {"Fourteen", "14", "XIV"},
                   {"Fifteen", "15", "XV"},
                   {"Sixteen", "16", "XVI"},
                   {"Seventeen", "17", "XVII"},
                   {"Eighteen", "18", "XVIII"},
                   {"Nineteen", "19", "XIX"},
                   {"Twenty", "20", "XX"}
              String headers[] = {"Notation", "Decimal", "Roman"};
              JFrame frame = new JFrame("3 Column header");
              JTable table = new JTable(rows, headers);
              JScrollPane scrollPane = new JScrollPane(table);
              frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
              frame.setSize(300,150);
              frame.setVisible(true);
    }-Merwyn,
    Developer Technical Support,
    http://www.sun.com/developers/support.

  • Setting column names in a sql statement

    hello everyone i hope someone can help me.
    i want a sql statement that gets the column names from a arraylist for example
    String sql = ("INSERT INTO Cust (and i want this part to get what is in the arraylist) values (?, ?, ?)");
    is there any way i can do this?
    thanks for your time
    loftty

    hello again
    well when i try to compile it i get an error saying [ODBC SQL server driver] COUNT field incorrect or syntax error.
    what is the problem here?
    and regarding my previous question my arraylist holds three names (firstname, lastname and postcode) now i want to be able to add 10 values to the column name firstname, then i want to add 8 values to the column name lastname and then 9 values to column name postcode.
    i hope this is a better understanding if not let me know and i will try and explain again.
    thanks for your time
    loftty
    StringBuffer sb = new StringBuffer("INSERT INTO Cust (");
                                                 Iterator it = arr.iterator();
                                                 while (it.hasNext())
                                                      String col = (String) it.next();
                                                      sb.append(col);
                                                      if (it.hasNext())
                                                           sb.append(',');
                                                      sb.append(") values (?, ?, ?)");
                                                      String sql = sb.toString();
                                                 PreparedStatement prepStmt = con.prepareStatement(sql);
                                                           prepStmt.setString(1, "hello");
                                                           prepStmt.setString(2, "hi");
                                                           prepStmt.setString(3, "bye");
                                                           prepStmt.executeUpdate();
                                                           prepStmt.close();

  • How to set column alignment in JTable

    I make a table with JTable(Vector a, Vector b).
    I don't know how to set the alignment to right while the column type is Integer or Long.
    Do i have to use JTable(Object[][] a, Object[] b) ?

    Well , you can configure the alignment when you are creating the column, like
    for (int i=0; i<7; i++){
    //Size of cell
    int colunaTam = 50;
    //Define Allingment
    int cellAlinhamento = 4; //Right Aligment
    //Column
    javax.swing.table.TableColumn coluna;
    BusinessObjects.CellColorRenderer renderer = new BusinessObjects.CellColorRenderer();
    //Define alingment in cell render
    renderer.setHorizontalAlignment(cellAlinhamento);
    coluna = new javax.swing.table.TableColumn(i, colunaTam, renderer, null);
    ivjJTableDespachos.addColumn(coluna);
    Hope i help you...
    Ice

  • Howto set Column name from InstanceProperty?

    I need to use one of InstanceProperties as some of ColumnDescriptor name.
    I try:
    <ColumnDescriptor NAME="%instanceproperty_1%" TYPE="NUMBER" >
    and
    <ColumnDescriptor NAME="name_1" TYPE="NUMBER">
    <Display>
    <Label NLSID="name_1">%instanceproperty_1%</Label>
    </Display>
    </ColumnDescriptor>
    In metric table displaying "%instanceproperty_1%"
    What wrong?

    Well, what you're describing is a bit contrary to the design of the agent and EM. A plug-in is a target type which represents a very specific entity, whether that entity be a piece of software or hardware. The target type metadata generalizes the information important to that piece of software or hardware, so that the system can easily support different instances and collect the same information for those different instances (off different nodes).
    The generalization doesn't come around the collection of the information. The information is very specific to the target type, allowing you to compare different instances of the same target type easily since the same pieces of information will be collected.
    I don't think I would try to do what you are doing, but if I did, I would structure it this way...
    Construct a single metric with a few columns called: OID, name, value
    Allow the user to create with instance properties as you specified and pass them as input parameters to the fetchlet. You'll probably have to use the OSFetchlet and write a script to do the snmp call (since the snmp fetchlet wouldn't work, I don't think). The return from your script would be multiple rows, echoing the OID first, and then the information specific to that OID (name and value or whatever else is important).
    The metric and its columns would be static, but you would be passing back a table of data which could be dynamic. So it doesn't matter to the metric how many OIDs are specified...

  • How to change column names in JTable?

    Hi!
    May be, my question is simple, but I still don't know the answer.
    Please help.

    JTableHeader th = table.getTableHeader();
    TableColumnModel tcm = th.getColumnModel();
    TableColumn tc = tcm.getColumn( int ); // the column to change
    tc.setHeaderValue( "New Value" );
    th.repaint();

  • Problem in updating first column header in JTable

    hi
    I am using JTable in my application. I want to change first column name of JTable every time when a JList is selected. I am using DefaultTableModel for JTable. I added first column in Constructor and another in a method. I have to edit only first column header. How can i do this???
    I used this code but it is not working.
    table.getColumnModel().getColumn(0).setHeaderValue("Name of column");
    table.getTableHeader().resizeAndRepaint();
    Your help will be appreciated.
    Thanks in advance
    Sonal

    table.getColumnModel().getColumn(0).setHeaderValue("Name of column");
    table.getTableHeader().repaint();Works for me so post a SSCCE ( http://www.sscce.org/ ) that shows the problem.

  • Easier way to set post-constructor JTable column names?

    I have a class that extends JTable. It also has a pair of inner classes that extend DefaultTableCellRenderer and AbstractTableModel so I can dynamicaly adjust the number of rows and their contents. That's not the problem - that part works fine. The problem is the column headers. My table doesn't currently have any but I want to add them.
    The column quantity is constant at 3 and should always be the same 3 Strings. It would be nice if I could use the JTable constructors that take a Vector or Object[] of column names from the start in my new class' constructor. But I don't think I can because at that point I don't know how many rows there will be or what they'll contain. Trying to set rowData to null just caused runtime exceptions.
    So the alternative seems to be to call setColumnModel() within the constructor, passing it a DefaultTableColumnModel. Which then requires I call addColumn() three times. Each time passing it a new TableColumn object. Each of which requires that I separately call setHeaderValue() after I construct it to set the header name. Am I right in that is the only way to do it? It just seems overly complex.

    I'll post a streamlined version of my class in case that will help...
    public class TotalsTable extends JTable
       private static int NUM_COLUMNS = 3;
       static final public String columnNames[] = {
             "Col Name 1", "Col Name 2", "Col Name 3"};
       protected Vector data = null;
       private TotalsModel tableModel;
       public TotalsTable()
          tableModel = new TotalsModel();
          setModel(tableModel);
          TableCellRenderer renderer = new TotalsCellRenderer();
          setDefaultRenderer(Object.class, renderer);
       public void updateTable(Vector pData)
          data = pData;
          tableModel.update();
       class TotalsCellRenderer extends DefaultTableCellRenderer
          public Component getTableCellRendererComponent
             (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
             super.getTableCellRendererComponent(table, value, isSelected,
                                                 hasFocus, row, column);
             if (column == 0) {
                setForeground(Color.blue);
             else {
                setForeground(Color.black);
             return this;
       class TotalsModel extends AbstractTableModel
          public TotalsModel()
             super();
          protected void update()
             fireTableStructureChanged();
           * Retrieves number of columns
           * (Necessary for AbstractTableModel implementation)
          public synchronized int getColumnCount()
             return NUM_COLUMNS;
          public synchronized int getRowCount()
             if (playerData == null)
                System.out.println("No rows found in table");
                return 0;
             else
                return playerData.size();
           * Returns cell information of a record at location row,column
           * (Necessary for AbstractTableModel implementation)
          public synchronized Object getValueAt(int row, int column)
             try
                MyObject p = (MyObject) data.elementAt(row);
                switch (column)
                   case 0:
                      return p.getName();
                   case 1:
                      return ("" + p.getDataItem2());
                   case 2:
                      return ("" + p.getDataItem3());
                   default:
                      System.out.println("getValueAt() Error: Invalid column");
             catch (Exception e)
                System.out.println("Exception in getValueAt(): " +
                                   e.getMessage());
             return "";
          public String getColumnName(int col)
             if (col < NUM_COLUMNS)
                return columnNames[col];
             else
                return "";
          public Class getColumnClass(int c)
             return getValueAt(0, c).getClass();
    }

  • 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.
    }

Maybe you are looking for