Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2005

Tip: Looking for answers? Try searching our database.

IS THERE ANY EQUIVALENT TO DISPOSE()?

Thread view: 
abenm613@mail.ru - 11 Dec 2005 20:57 GMT
I'm trying to use dispose() method for closing a popup window.  But the
problem is that, after the window is closed and the action to open a
similar window (with another data) is performed, the new windows that
comes up is identical to the one that I have just disposed.  But I
don't want that.  What I want is the new data to come up in a new
window.  How do I achieve this?  Is there any other method similar to
dispose() but more effective, that completely removes the content of
the previous window.  Here is my code:

public class listByRequest extends JFrame implements ActionListener{
    private ScrollingPanel fields;
    private JTextField output, input, input1, input2, input3;
    private Connection connection;
    private String searchKey, searchStart, query, listQuery, whatIsInput,
social;
    private JList resultList;
    private JPanel listPanel, topPanel, mainPanel;
    ResultSet resultSet;
    JTable table[] = new JTable[100];
    JFrame frame;
    boolean flag[] = new boolean[20];
    int c = 0, contCount = 0;
    private JLabel lname, fname, gnumber, pcode;
    private JButton close;
    Container[] cont = new Container[100];

    public listByRequest(Connection c, ScrollingPanel f)
    {
        connection = c;
        fields = f;

    }

    public void actionPerformed(ActionEvent e)
       {
        lname = new JLabel();
        fname = new JLabel();
        gnumber = new JLabel();
        pcode = new JLabel();
        topPanel = new JPanel();
        mainPanel = new JPanel();
        //mainPanel.setLayout(new BorderLayout());
        close = new JButton("Close window");

        try{
            Statement statement = connection.createStatement();

            query = "SELECT ssec, lastname, firstname, streetadress, city,
state, zipcode, groupnumber FROM students WHERE";

            System.out.println("I'm about to start constructing query");

            if(!fields.lastName.getText().equals("")){
                query = query+" lastname = '"+fields.lastName.getText()+"'";
                flag[0] = true;
                if((!fields.firstName.getText().equals("")) ||
(!fields.groupNumber.getText().equals("")) ||
(!fields.programCode.getText().equals("")))
                    query = query+" AND";
                //System.out.println(query);
                lname.setText("Last name = "+fields.lastName.getText());
                topPanel.add(lname);

            }
            if(!fields.firstName.getText().equals("")){
                flag[1]=true;
                System.out.println("The first name appears as
"+fields.firstName.getText());
                query = query+" firstname = '"+fields.firstName.getText()+"'";;
                if((!fields.groupNumber.getText().equals("")) ||
(!fields.programCode.getText().equals("")))
                    query = query+" AND";
                fname.setText("First name = "+fields.firstName.getText());
                topPanel.add(fname);
            }
            if(!fields.groupNumber.getText().equals("")){
                flag[3]=true;
                System.out.println("The group number is
"+fields.groupNumber.getText());
                query = query+" groupnumber =
'"+fields.groupNumber.getText()+"'";
                if(!fields.programCode.getText().equals(""))
                    query = query+" AND";
                gnumber.setText("Group number =
"+fields.groupNumber.getText());
                topPanel.add(gnumber);
            }
            if(!fields.programCode.getText().equals("")){
                flag[4]=true;
                System.out.println("The program code is
"+fields.programCode.getText());
                query = query+" programcode = '"+fields.programCode.getText()+"'";
                pcode.setText("Program code = "+fields.programCode.getText());
                topPanel.add(pcode);
            }
            System.out.println(query);
            if(query == "SELECT * FROM students WHERE"){
                JOptionPane.showMessageDialog(null, "Invalid query", "Invalid
query", JOptionPane.ERROR_MESSAGE);
                System.exit(1);
            }
            System.out.println("\nSending query: "+query+"\n");

            //table = new JTable(12, 12);

            //Container cont = getContentPane();

            //cont.add(table);

            resultSet = statement.executeQuery(query);
            System.out.println("\nResults found...");

            showList(resultSet);

            System.out.println("\nQuery successful");
            statement.close();

            setSize(1050, 1050);

            System.out.println("Looks okay so far");

        }
        catch(SQLException sqlex){
            System.out.println("Something wrong with SQL finding the record");
            sqlex.printStackTrace();
            System.out.println(sqlex.toString());
        }
       }
public void showList(ResultSet rs){
        contCount++;
        cont[contCount] = getContentPane();
        listPanel = new JPanel();
        Vector columnHeads = new Vector();
        Vector rows = new Vector();
        cont[contCount].setLayout(new BorderLayout());
        frame = new JFrame();

        try{
            boolean moreRecords = rs.next();

            if(!moreRecords){
                JOptionPane.showMessageDialog(this, "ResultSet contained no
records");
                setTitle("No records to display");
                return;
            }
            boolean nextExists;
            ResultSetMetaData rsmd = rs.getMetaData();

            for(int i=1; i<=rsmd.getColumnCount(); ++i){
                columnHeads.addElement(rsmd.getColumnName(i));
                //columnHeads.elementAt(i).setWidth(5);
            }

            do{
                rows.addElement(getNextRow(rs, rsmd));
                nextExists = rs.next();
                //if(nextExists)
                //    System.out.println("Next exists");
                //else
                //    System.out.println("No next");

            }while(nextExists);
            table[contCount] = new JTable(rows, columnHeads);
            ExcelAdapter ea = new ExcelAdapter(table[contCount]);

            listPanel.add(table[contCount]);
            mainPanel.add(topPanel);
            mainPanel.add(listPanel);
            mainPanel.add(close);

            close.addActionListener(new ActionListener(){
                            public void actionPerformed(ActionEvent e){
                                dispose();
                            }
                        }
                        );

            cont[contCount].add(mainPanel);

            this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

            cont[contCount].setSize(40, 40);
            cont[contCount].validate();

            show();

        }
        catch(SQLException sqlex){
            System.out.println("SQL Exception");
            sqlex.printStackTrace();
        }

    }

    public Vector getNextRow(ResultSet rs, ResultSetMetaData rsmd) throws
SQLException{
            Vector currentRow = new Vector();
            for (int i=1; i<=rsmd.getColumnCount(); ++i){
                switch(rsmd.getColumnType(i)){
                    case Types.VARCHAR:
                    case Types.LONGVARCHAR:
                        currentRow.addElement(rs.getString(i));
                                  break;
                    case Types.INTEGER:
                        currentRow.addElement(new Long(rs.getLong(i)));
                        break;
                    default:
                        //System.out.println("Type was: "+rsmd.getColumnTypeName(i));
                }
            }
            return currentRow;
    }

}

---------------------------------
As I'm running a main program that activates this class, the popup
window is supposed to come up with the result of my query.  It comes up
correctly only for the first time.  Then the data "saves" somewhere and
keeps coming up even as I try to make different searches.  Can anyone
help me get out of this problem?
Thomas Hawtin - 11 Dec 2005 21:43 GMT
> I'm trying to use dispose() method for closing a popup window.  But the
> problem is that, after the window is closed and the action to open a
[quoted text clipped - 7 lines]
> public class listByRequest extends JFrame implements ActionListener{
> [...huge ammounts of code snipped...]

The usual way of creating a new JFrame is with new JFrame(). If you
resisted the temptation to extend JFrame (or use the same class to
implement ActionListener), then I don't suppose there would be a problem.

I can't help myself from suggesting you keep to the Java coding
conventions, in particular using initial caps for class names.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

zero - 12 Dec 2005 00:27 GMT
> I'm trying to use dispose() method for closing a popup window.  But
> the problem is that, after the window is closed and the action to open
[quoted text clipped - 4 lines]
> dispose() but more effective, that completely removes the content of
> the previous window.  Here is my code:

<code snipped>

Does this code work?  You're breaking a lot of coding conventions and
good programming practices here.

A few hints:

1. start class names with a capital letter.
2. use the principle of least privilege.  Unless you have good reason to
give a variable package access, use private.
3. constructors are used to make sure your class always has a consistant
state.  You should not initialize class scope arrays in the
actionPerformed method.
4. like Thomas pointed out, you don't seem to have a good reason to
extend JFrame.  Extending a class is done when you want to "extend" the
usage of that class.
5. doing database queries on the event dispatch thread is probably not
the best way to go.  Do your queries in the main thread, fill them out in
the frame, and then show it.

And also:

6. please don't use all CAPS in the subject line.

> As I'm running a main program that activates this class, the popup
> window is supposed to come up with the result of my query.  It comes
> up correctly only for the first time.  Then the data "saves" somewhere
> and keeps coming up even as I try to make different searches.  Can
> anyone help me get out of this problem?

Rethink the design.  Something like this:

class MainClass()
{
  public void showResult()
  {
     JFrame frame = new JFrame();
     JButton closeButton = new JButton("close");
     closeButton.addActionListener(
        {
           public void actionPerformed(ActionEvent e)
           {
              frame.dispose();
           }
        });
     
     frame.add(closeButton);

     // code to fill the frame and show it
  }
}

Signature

Beware the False Authority Syndrome

Thomas Hawtin - 12 Dec 2005 00:52 GMT
> 5. doing database queries on the event dispatch thread is probably not
> the best way to go.  Do your queries in the main thread, fill them out in
> the frame, and then show it.

Technically you should not perform queries on the EDT, as they may well
block for sometime.

However, in practice I'd prefer a program that works, is finished in
budget and on time, and is responsive, to one that has followed pedantic
rules. It all depends on the application.

I was quite happy when my first major Java application stayed
responsive, didn't die and kept live customer data despite the SQL
Server having to be rebooted (though I'm not sure if anyone noticed that
peculiarity - they'd have noticed if it didn't). On the other hand, for
code not used in such situations, it's much easier, faster and safer to
write code that assumes that Connections live for ever and always
respond well within the 100 ms limit.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

zero - 12 Dec 2005 02:56 GMT
>> 5. doing database queries on the event dispatch thread is probably
>> not the best way to go.  Do your queries in the main thread, fill
[quoted text clipped - 16 lines]
>
> Tom Hawtin

For small personal projects I agree it's fine to do queries on the EDT.  
But unless the project is really complex, I don't think it's that much
harder to do it on a different thread.  It's just creating a new Runnable.

Plus, doing this every time will make sure you remember to do it when it's
crucial, and it will even make it easier, since you've done it often
before.

Signature

Beware the False Authority Syndrome

Thomas Hawtin - 12 Dec 2005 04:55 GMT
> For small personal projects I agree it's fine to do queries on the EDT.  
> But unless the project is really complex, I don't think it's that much
> harder to do it on a different thread.  It's just creating a new Runnable.

Just creating a new Runnable???

I don't think the decision to go multi-threaded should be taken so
lightly. It's far too difficult to treat with such a cavalier attitude.

You need to consider what the UI is doing while the query is in progress.

One option is to block out UI interaction. You could disable all the
controls, but that looks bad. Put up a glass pane, and ignore key and
accessibility input, or perhaps do something funky with an invisible
dialog box. Or do funky control/model specific stuff.

Sometimes you want to do lazy loading. Perhaps give table model cells a
value representing unloaded, to be updated later. End up sending a
stream of requests for every displayed cell.

Then you need your own "EDT" for the database connectivity, with
invokeLater or queue processing of some form. In the EDT, you need to
feed the data back to the bit of the GUI that requested it. Perhaps when
you only have a partial result, but you don't want to have the GUI doing
updates for every single cell.

> Plus, doing this every time will make sure you remember to do it when it's
> crucial, and it will even make it easier, since you've done it often
> before.

I guess there is that. I have certainly messed it up, in my younger
years. IIRC, to start I had a key get the next customer details up. The
application being used by a bunch of menopausal women, some would press
down really hard on the key, keeping it down for a few repeats[1].
Unfortunately, that part of the GUI remained active until the database
responded and created the new screen (and presumably linked a few
classes and JITed some code). So a number of records would be fetched.
When the operator came to log off, up would come these records in
reverse order. Should a customer phone during this time (unlikely),
their record would be mysteriously locked.

Tom Hawtin

[1] I'm not blaming them for this. It's a poor programmer who blames his
(usually) users for being human. Just bit my lip and didn't mention the
records when they claimed this did not happen.
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Monique Y. Mudama - 12 Dec 2005 18:36 GMT
> The application being used by a bunch of menopausal women, some
> would press down really hard on the key, keeping it down for a few
> repeats[1].  

I am baffled by this sentence.  Please, Thomas, tell us how menopause
relates to the quality of one's keypresses.

Better yet, learn how to behave yourself in public.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Brandon McCombs - 13 Dec 2005 02:25 GMT
>> The application being used by a bunch of menopausal women, some
>> would press down really hard on the key, keeping it down for a few
[quoted text clipped - 4 lines]
>
> Better yet, learn how to behave yourself in public.

It puts a lot of undue stress on the keys.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.