Javax.swing.SwingUtilities.invokeLater make my program slow

i am writing a program in which i am implementing documentlistener
to communicating between two frames
if i write my code with javax.swing.SwingUtilities.invokeLater it makes my program slow
and if i write without this thread safe quality then this is fast but giving me runtime exception
what i do to make my program better
kindly suggest
public void insertUpdate(DocumentEvent e) {
            updateLog(e, "inserted into");
        public void removeUpdate(DocumentEvent e) {
            updateLog(e, "removed from");
        public void changedUpdate(DocumentEvent e) {
            //Plain text components don't fire these events.
        public void updateLog(DocumentEvent e, String action) {
            Document doc = (Document)e.getDocument();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
tf4.setText(lbl.getText());
}

If your program is becoming too slow or unresponsive, it means that the operation "tf4.setText(lbl.getText());" is taking too long to execute and is therefore blocking the Swing-thread.
There is little you can do to make that operation faster, but perhaps you can change how or how often you update the frames.
Setting the whole text via setText() everytime a change happens seems very wasteful. Imagine you have a text with a million characters, and every time the user adds or changes just one character, you are getting and seting over one million characters. That is not the right approach.
I'm not familiar with text-operations or class DocumentEvent, but I guess that there should be some kind of delta in DocumentEvent containing only the changes that were made. You could apply only these changes on tf4 instead of setting the whole text. Finding out how to do this would be the best solution. This will also make your program more scalable, as with setText() the performance of your application will continuously decrease as the text length increases.
Usually when working with documents you have a "viewer" and a "model". If your viewer was a JTextBox and your model was, say a StringBuilder, you could make quick changes to the contents of JTextBox using the StringBuilder.append() or delete() methods without having to modify the whole text. You need to find out how this is done with whatever UI system you're using.
If you can't find out how to do the above, a workaround would be to reduce how often you call "updateLog()". For example, is it truly necessary to call "updateLog" every time a new update happens? Perhaps it would be better to use a timer and only call "updateLog()" every few seconds.
But as I said, this should only be a temporary workaround. You really should find out how to perform more efficient updates without using setText(). I recommend you search for tutorials and guides on how to work with text and documents on the internet.

Similar Messages

  • Javax.swing.SwingUtilities.invokeAndWait limitation

    Hi all,
    I have the following method:
    private static void m() throws Throwable
    try {
          javax.swing.SwingUtilities.invokeAndWait ( new Runnable(){public void run(){
          try{
                invoke ( ... );                        // a Method.invoke() call
          } catch(Throwable t) {throw t;}
      } catch (Throwable th){}
    }If invoke() throws an exception, I need to pass the exception back to the caller of m(); however, I cannot do that since run() doesn't allow that
    Thank you

    Check the Javadoc, SwingUtilities.invokeAndWait(...) declares it can throw an InvocationtargetException that is just what you need.I knowYou didn't seem to, since you blamed an "invokeAndWait limitation" for a fact that is indeed with the Runnable interface.
    but the problem is with the invoke() call (inside the run()). I have to wrap it in a try - catch. What should I do with the caught exception ?Rethrow it wrapped in an unchecked exception?
    Note that if the exception thrown by Method.invoke() is already an InvocationTargetException, you may prefer to wrap this exception's cause instead, as the caller of invokeAndWait() will already have to unwrap it from an (+other+) InvocationTargetException.
    All that (cheating with checked/unchecked exceptions) is frowned upon in business code but is acceptable in framework code. If the caller of m() needs a strongly-typed exception handling interface, I suggest you wrap the nasty code so as to expose only the clean-cut interface.
    Note that Another practice that is questionable is a statement such as catch Throwable (except, again, in framework code). Regular business code shouldn't catch Errors.
    I suggest you read the Java tutorial's [chapter on exceptions|http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/essential/exceptions/index.html] as well.
    Best regards.

  • When jdialog now onwer the java get javax.swing.SwingUtilities$SharedOwnerF

    Hi!
    I have:
    JDialog myLogin
    JDialog myRegister
    The task is. When dialog myLogin have not owner, then myLogin must have one view (with 3 buttons). But when myLogin have owner, then myLogin must have another view (with 2 buttons). For this purpose I use methos getOwner() from class java.awt.Window. This work when myLogin have owner. But when myLogin have not owner it's not work.
    The question is, how I can understand that the dialog myLogin have not owner?

    duplicate post
    [http://forum.java.sun.com/thread.jspa?threadID=5287874&tstart=0]

  • Import javax.swing.JOptionPane

    hello
    i just installed j2sdk1.3.1 into my redhat linux7.3, during installation, everything's fine...
    but when i start to compile a program with some import classes...i face the problem :
    cannot find type "javax/swing/JOptionPane
    this is my program :
    import javax.swing.JOptionPane;
    public class Welcome{
    public static void main(String args[])
         JOptionPane.showMessageDialog(null,"Hello");
         System.exit(0);
    can anybody help me with this problem......?...thanks

    type
    java -versionto see which version of the JVM you are running
    you could also try
    which javato see the actuall executable that you are running.

  • [HELP! ] why my program thows a javax.swing.text.ChangedCharSetException?

    there's the source:
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.border.*;
    class HTMLMagician extends JFrame
         protected static final String APP_NAME="HTML Magician V1.0 Produced By V Studio";
         protected JTextPane hm_textPane;
         protected StyleSheet hm_styleSheet;
         protected HTMLEditorKit html_kit;
         protected HTMLDocument html_document;
         protected JMenuBar hm_menuBar;
         protected JToolBar hm_toolBar;
         protected JFileChooser hm_fileChooser;
         protected File current_file;
         protected boolean text_changed=false;
         public HTMLMagician()
              super(APP_NAME);
              setSize(800,600);
              getContentPane().setLayout(new BorderLayout());
              produceMenuBar();
              hm_textPane=new JTextPane();
              html_kit=new HTMLEditorKit();
              hm_textPane.setEditorKit(html_kit);
              JScrollPane textPane_scrollPane=new JScrollPane();
              textPane_scrollPane.getViewport().add(hm_textPane);
              getContentPane().add(textPane_scrollPane,BorderLayout.CENTER);
              hm_fileChooser=new JFileChooser();
              javax.swing.filechooser.FileFilter hm_filter=new javax.swing.filechooser.FileFilter()
                   public boolean accept(File pathname)
                        if(pathname.isDirectory())
                             return true;
                        String ext_name=pathname.getName().toLowerCase();
                        if(ext_name.endsWith(".htm"))
                             return true;
                        if(ext_name.endsWith(".html"))
                             return true;
                        if(ext_name.endsWith(".asp"))
                             return true;
                        if(ext_name.endsWith(".jsp"))
                             return true;
                        if(ext_name.endsWith(".css"))
                             return true;
                        if(ext_name.endsWith(".php"))
                             return true;
                        if(ext_name.endsWith(".aspx"))
                             return true;
                        if(ext_name.endsWith(".xml"))
                             return true;
                        if(ext_name.endsWith(".txt"))
                             return true;
                        return false;
                   public String getDescription()
                        return "HTML files(*.htm,*.html,*.asp,*.jsp,*.css,*.php,*.aspx,*.xml)";
              hm_fileChooser.setAcceptAllFileFilterUsed(false);
              hm_fileChooser.setFileFilter(hm_filter);
              try
                   File dir=(new File(".")).getCanonicalFile();
                   hm_fileChooser.setCurrentDirectory(dir);
              }catch(IOException ex)
                   showError(ex,"Error openning current directory");
              newDocument();
              WindowListener action_winClose=new WindowAdapter()
                   public void windowClosing(WindowEvent evt)
                        if(!promptToSave())
                             return;
                        System.exit(0);
              addWindowListener(action_winClose);
              setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              setVisible(true);
         protected void produceMenuBar()
              hm_menuBar=new JMenuBar();
              hm_toolBar=new JToolBar();
              JMenu menu_file=new JMenu("File");
              menu_file.setMnemonic('f');
              ImageIcon icon_new=new ImageIcon("imgs/file.gif");
              Action action_new=new AbstractAction("New",icon_new)
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        newDocument();
              JMenuItem item_new=new JMenuItem(action_new);
              item_new.setMnemonic('n');
              item_new.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK));
              menu_file.add(item_new);
              JButton button_new=hm_toolBar.add(action_new);
              ImageIcon icon_open=new ImageIcon("imgs/folder_open.gif");
              Action action_open=new AbstractAction("Open...",icon_open)
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        openDocument();
              JMenuItem item_open=new JMenuItem(action_open);
              item_open.setMnemonic('o');
              item_open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));
              menu_file.add(item_open);
              JButton button_open=hm_toolBar.add(action_open);
              ImageIcon icon_save=new ImageIcon("imgs/floppy.gif");
              Action action_save=new AbstractAction("Save",icon_save)
                   public void actionPerformed(ActionEvent evt)
                        saveAs(false);
              JMenuItem item_save=new JMenuItem(action_save);
              item_save.setMnemonic('s');
              item_save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
              menu_file.add(item_save);
              JButton button_save=hm_toolBar.add(action_save);
              Action action_saveAs=new AbstractAction("Save As...")
                   public void actionPerformed(ActionEvent evt)
                        saveAs(true);
              JMenuItem item_saveAs=new JMenuItem(action_saveAs);
              item_saveAs.setMnemonic('a');
              item_saveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_MASK));
              menu_file.add(item_saveAs);
              menu_file.addSeparator();
              Action action_close=new AbstractAction("Quit")
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        System.exit(0);
              JMenuItem item_exit=new JMenuItem(action_close);
              item_exit.setMnemonic('q');
              item_exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,InputEvent.CTRL_MASK));
              menu_file.add(item_exit);
              hm_menuBar.add(menu_file);
              setJMenuBar(hm_menuBar);
              getContentPane().add(hm_toolBar,BorderLayout.NORTH);
         protected String getDocumentName()
              return current_file==null ? "Untitled" : current_file.getName();
         protected void newDocument()
              html_document=(HTMLDocument)html_kit.createDefaultDocument();
              hm_styleSheet=html_document.getStyleSheet();
              hm_textPane.setDocument(html_document);
              current_file=null;
              setTitle(getDocumentName()+" - "+APP_NAME);
              Runnable runner=new Runnable()
                   public void run()
                        text_changed=false;
                        html_document.addDocumentListener(new action_textChanged());
              SwingUtilities.invokeLater(runner);
         protected void openDocument()
              if(hm_fileChooser.showOpenDialog(HTMLMagician.this)!=JFileChooser.APPROVE_OPTION)
                   return;
              File f=hm_fileChooser.getSelectedFile();
              if(f==null || !f.isFile())
                   return;
              current_file=f;
              setTitle(getDocumentName()+" - "+APP_NAME);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              try
                   InputStream in=new FileInputStream(current_file);
                   html_document=(HTMLDocument)html_kit.createDefaultDocument();
                   html_kit.read(in,html_document,0);
                   hm_styleSheet=html_document.getStyleSheet();
                   hm_textPane.setDocument(html_document);
                   in.close();
              }catch(Exception ex)
                   showError(ex,"Error openning file "+current_file);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
              Runnable runner=new Runnable()
                   public void run()
                        text_changed=false;
                        html_document.addDocumentListener(new action_textChanged());
              SwingUtilities.invokeLater(runner);
         protected boolean saveAs(boolean as)
              if(!as && !text_changed)
                   return true;
              if(as || current_file==null)
                   if(hm_fileChooser.showSaveDialog(HTMLMagician.this)!=JFileChooser.APPROVE_OPTION)
                        return false;
                   File f=hm_fileChooser.getSelectedFile();
                   if(f==null || !f.isFile())
                        return false;
                   current_file=f;
                   setTitle(getDocumentName()+" - "+APP_NAME);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              try
                   OutputStream out=new FileOutputStream(current_file);
                   html_kit.write(out,html_document,0,html_document.getLength());
                   out.close();
              }catch(Exception ex)
                   showError(ex,"Error saving file "+current_file);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
              return true;
         protected boolean promptToSave()
              if(!text_changed)
                   return true;
              int result=JOptionPane.showConfirmDialog(this,"Save change to "+getDocumentName(),APP_NAME,JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);
              switch(result)
                   case JOptionPane.YES_OPTION:
                        if(!saveAs(false))
                             return false;
                        return true;
                   case JOptionPane.NO_OPTION:
                        return true;
                   case JOptionPane.CANCEL_OPTION:
                        return false;
              return true;
         protected void showError(Exception ex,String message)
              ex.printStackTrace();
              JOptionPane.showMessageDialog(this,message,APP_NAME,JOptionPane.WARNING_MESSAGE);
         public static void main(String[] args)
              new HTMLMagician();
         class action_textChanged implements DocumentListener
              public void changedUpdate(DocumentEvent evt)
                   text_changed=true;
              public void insertUpdate(DocumentEvent evt)
                   text_changed=true;
              public void removeUpdate(DocumentEvent evt)
                   text_changed=true;
    when i open a .html file,the command output :
    javax.swing.text.ChangedCharSetException
         at javax.swing.text.html.parser.DocumentParser.handleEmptyTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.startTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.parseTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.parseContent(Unknown Source)
         at javax.swing.text.html.parser.Parser.parse(Unknown Source)
         at javax.swing.text.html.parser.DocumentParser.parse(Unknown Source)
         at javax.swing.text.html.parser.ParserDelegator.parse(Unknown Source)
         at javax.swing.text.html.HTMLEditorKit.read(Unknown Source)
         at javax.swing.text.DefaultEditorKit.read(Unknown Source)
         at HTMLMagician.openDocument(HTMLMagician.java:222)
         at HTMLMagician$4.actionPerformed(HTMLMagician.java:128)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    why? what's wrong? thanks

    The DocumentParser seems to throw a ChangedCharSetException if it finds a "http-equiv" meta tag for "content-type" or "charset" and if the parser's "ignoreCharSet" property is set to false on creation.

  • Good practice to update Swing i SwingUtilities.invokeLater() method?

    Is it a good practice to allways make the updates/changes of Swing components in the SwingUtilities.invokeLater() method in a multithreaded application. Or are there any situations when it´s not?

    There are a number of methods that are thread safe, but they generally say so in the API
    If they aren't then you shouldn't be updating them on the EDT.
    [http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html|http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html]

  • Swing Program Slow on Some Computers Second Instance Always Fast

    I am having a unusual and frustrating problem. I have a java swing application compiled and run with 1.5.06.
    On some computers the program runs very slowly and takes a long time to paint to the screen. If however, you run a second instance of the program the second instance runs very fast. If you close the first instance the second instance remains fast.
    Running the java console first will also make my program fast.
    On other PC's with the identical hardware it runs fine the first time. All the computers involved run windows 2000.
    Please help with this weird problem. Thanks.

    It seems that you need to fine tune ur JVM based you requirement.
    Try setting the max heap size.
    Also, You can tyr -XX jvm option. But the decision purely depends on you applications behaviour.
    Thanks
    Jobinesh

  • Question on SwingUtilities.invokeLater

    The program I have included is attempting to "simulate" opening and loading a file into memory.
    Run the program, select File and then select Open. You will notice that the File menu does not disappear for 3 seconds (i.e. until the file has been completely read).
    I was hoping it was possible to close the File menu while the file is being read. While reading through various documentation on the invokeLater() method I found the following:
    "Both invokeLater() and invokeAndWait() wait until all pending AWT events finish before they execute"
    Therefore by adding an invokeLater() method I was hoping to accomplish the following series of events:
    1) click on Open menuItem
    2) invoke OpenAction
    3) do the "repaint" (which would cause the file menu to disappear)
    4) finish the OpenAction
    5) do the long running task
    Hopefully you understand what I am trying to accomplish and can provide some guidance. Here is the sample program:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestInvokeLater extends JFrame
         JFrame frame;
         JMenuBar menuBar;
         JMenu menu;
         JMenuItem menuItem;
         public TestInvokeLater()
              frame = this;
              setDefaultCloseOperation( EXIT_ON_CLOSE );
              menuBar = new JMenuBar();
              menu = new JMenu("File");
              menuBar.add(menu);
              menuItem = new JMenuItem( new OpenAction() );
              menu.add(menuItem);
              setJMenuBar( menuBar );
              JPanel panel = new JPanel();
              panel.setPreferredSize( new Dimension( 100, 100 ) );
              setContentPane( panel );
         class OpenAction extends AbstractAction
              public OpenAction()
                   putValue( Action.NAME, "Open" );
              public void actionPerformed(ActionEvent e)
              repaint();
         SwingUtilities.invokeLater(new Runnable()
         public void run()
              try
                   Thread.sleep(3000); // simulate log running task
              catch (Exception e) {}
         public static void main(String[] args)
              JFrame frame = new TestInvokeLater();
              frame.pack();
              frame.show();
    }

    Thanks for the input, but I still have some confusion -
    "invokeLater() simply appends the thread to the end of the dispatch queue, this happens before the event code to hide the file menu gets queued"
    This is the part that confuses me. If I understand event driven programming correctly then the code for the MenuItemClicked must complete execution before the next event in the queue can be executed.
    If we assume the code for MenuItemClicked is something like:
    1) fireActionEvent
    2) fireCloseMenuEvent
    When MenuItemClicked is finished executing the next event in the queue is the ActionEvent which invokes my ActionPerformed code:
    1) I use the Swing invokeLater() method (which means it should be queued "after" the fireCloseMenuEvent
    Does this make any sense?

  • How do I make this program generate a new problem once the button is hit

    Here is the code... appreciate any help given
    How do I make this program generate a new set of problem when the "NEXT" button is clicked and continue until the END button is hit
    package javaapplication3;
    import java.awt.GridLayout;
    import java.awt.Window;
    import javax.swing.*;
    import java.awt.event.*;
    * @author Sylvester Saulabiu
    class Grid extends JFrame{
        final int score = 0;
        final int total = 0;
        Grid(){
            //Set Layout of Flashcard
            setLayout(new GridLayout(4, 4, 2 , 2));
            //Create Panels
            JPanel p2 = new JPanel();
            JPanel p3 = new JPanel();
            final JPanel p1 = new JPanel();
            //Create Radio buttons & group them
            ButtonGroup group = new ButtonGroup();
            final JRadioButton ADD = new JRadioButton("Addition");
            final JRadioButton SUB = new JRadioButton("Subtraction");
            final JRadioButton MUL = new JRadioButton("Multiplication");
            final JRadioButton DIV = new JRadioButton("Division");
            p2.add(ADD);
            p2.add(SUB);
            group.add(ADD);
            group.add(SUB);
            group.add(MUL);
            group.add(DIV);
            p2.add(ADD);
            p2.add(SUB);
            p2.add(DIV);
            p2.add(MUL);
            //Create buttons
            JButton NEXT = new JButton("NEXT");
            JButton END = new JButton("End");
            //Create Labels
            JLabel l1 = new JLabel("First num");
            JLabel l2 = new JLabel("Second num");
            JLabel l3 = new JLabel("Answer:");
            JLabel l4 = new JLabel("Score:");
            final JLabel l5 = new JLabel("");
            JLabel l6 = new JLabel("/");
            final JLabel l7 = new JLabel("");
            //Create Textfields
            final JTextField number = new JTextField(Generator1());
            final JTextField number2 = new JTextField(Generator1());
            final JTextField answer = new JTextField(5);
            //Add to panels
            p1.add(l1);
            p1.add(number);
            p1.add(l2);
            p1.add(number2);
            p1.add(l3);
            p1.add(answer);
            p1.add(l4);
            p1.add(l5);
            p1.add(l6);
            p1.add(l7);
            p3.add(NEXT);
            p3.add(END);
            //Add panels
            add(p2);
            add(p1);
            add(p3);
            //Create Listners
      NEXT.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
             int answer1 = 0;
             //Grab the numbers entered
             int numm1 = Integer.parseInt(number.getText());
             int numm2 = Integer.parseInt(number2.getText());
             int nummsanswer = Integer.parseInt(answer.getText());
             //Set the score and total into new variabls
             int nummscore = score;
             int nummtotal = total;
             //Check if the add radio button is selected if so add
             if (ADD.isSelected() == true){
                 answer1 = numm1 + numm2;
             //otherwise check if the subtract button is selected if so subtract
             else if (SUB.isSelected() == true){
                 answer1 = numm1 - numm2;
             //check if the multiplication button is selected if so multiply
             else if (MUL.isSelected() == true){
                 answer1 = numm1 * numm2;
             //check if the division button is selected if so divide
             else if (DIV.isSelected() == true){
                 answer1 = numm1 / numm2;
             //If the answer user entered is the same with th true answer
             if (nummsanswer == answer1){
                 //add to the total and score
                 nummtotal += 1;
                 nummscore += 1;
                 //Convert the input back to String
                 String newscore = String.valueOf(nummscore);
                 String newtotal = String.valueOf(nummtotal);
                 //Set the text
                 l5.setText(newscore);
                 l7.setText(newtotal);
             //Otherwise just increase the total counter
             else {
                 nummtotal += 1;
                 String newtotal = String.valueOf(nummtotal);
                 l7.setText(newtotal);
      //Create End listener
    END.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // get the root window and call dispose on it
            Window win = SwingUtilities.getWindowAncestor(p1);
            win.dispose();
    String Generator1(){
         int randomnum;
         randomnum = (1 + (int)(Math.random() * 20));
         String randomnumm = String.valueOf(randomnum);
         return randomnumm;
    public class Main {
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            JFrame frame = new Grid();
            frame.setTitle("Flashcard Testing");
            frame.setSize(500, 200);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    }Edited by: SirSaula on Dec 5, 2009 4:39 PM

    Extract code into methods, so that when an action is performed a method is called. That way you can reuse the method for purposes such as resetting textfields to their default values, scores to default values, etc.
    You can go one step further and seperate the GUI layer from the processing layer, by deriving classes that for example maintain and calculate a score.
    Mel

  • Make A Program Which Has Four Different Buttons, Which Do Different Things?

    So far here is what I have, I need program in which number starts at thirteen then one will take the current number and cut in half, other will multiply it by 3 and add 1, and other will make current number a random value from one to a hundred. The Quit one will just exit the program. Heres what i have so far:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Lab05 extends JFrame
    private Container content;          //fields
    private LayoutManager layout;
    private JLabel label;
    private JButton button1, button2, button3, quit;
    private ActionListener listener1, listener2, listener3, quitter;
    private int number,n;
    public Lab05()          //default-constructor
    formatWindow();
    label = createAndAddLabel("Current Number: 13");
    button1 = createAndAddButton("DIV 2",listener1);
    button2 = createAndAddButton("TIMES 3 PLUS 1",listener2);
    button3 = createAndAddButton("Random.",listener3);
    quit = createAndAddButton("Quit.",quitter);
    listener1 = new Handler1();
    listener2 = new Handler2();
    listener3 = new Handler3();
    quitter = new Quitter();
    public void formatWindow()
    content = getContentPane();
    layout = new FlowLayout();
    content.setLayout(layout);
    private JLabel createAndAddLabel(String s)
    JLabel temp = new JLabel();
    temp.setText(s);
    content.add(temp);
    return temp;
         //use this method for creating and adding various different buttons
    private JButton createAndAddButton(String s, ActionListener li)
    JButton temp = new JButton();
    temp.setText(s);
    temp.addActionListener(li);
    content.add(temp);
    return temp;
         //use this method for controlling the affect of pressing different buttons
    private void process(int x)
    number = x;
    private class Handler1 implements ActionListener
    public void actionPerformed(ActionEvent e)
    private class Handler2 implements ActionListener
    public void actionPerformed(ActionEvent e)
    private class Handler3 implements ActionListener
    public void actionPerformed(ActionEvent e)
    private class Quitter implements ActionListener
    public void actionPerformed(ActionEvent e)
    System.exit(0);
    public static void main(String[] args)
         //create graphics window
    Lab05 window = new Lab05();
         //configure graphics window
    window.setSize(175, 175);
    window.setLocation(300, 175);
    window.setTitle("Unit3, Lab05: Hailstone");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //display graphics window
    window.setVisible(true);
    }

    4. please don't use abbreviations such as "ur" for"your" :)
    Please don't say anything that offends smckee6452. He
    can get kinda grumpy when someone does that. ;-)
    Gotcha!:) actually, i'm not offended at all when people do stuff like that. there are multiple reasons i believe you shouldn't condense to "internet words":
    1. because some people on the forums know only broken english and when you throw unknown abbreviations at them they have no idea what you're ("u r") talking about. and some people use tools such as "babel fish" to translate to different languages (although, i'm not sure how accurate that would be).
    2. even though it is faster to type "ur" and "u" and "2" and "ne way" and etc., it is slower to read them because the human brain has been conditioned to look at "your" and "you" and "to" and "anyway" and skip over them quickly absorbing the meaning and syntax all in one fell swoop. you'll find yourself having to sound out things like "neway" for your brain to snag the meaning...
    but, alas, james is correct. i am easily annoyed.
    that is all. ;)

  • Using setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH); ...?

    using setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
    JFrame Window will cover windows toolbar.
    how to create JFrame,make it max size,don't cover windows toolbar.

    import javax.swing.*;
    import java.awt.*;
    class Testing
      public void buildGUI()
        JFrame f = new JFrame();
        f.setExtendedState(JFrame.MAXIMIZED_BOTH);
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        f.setMaximizedBounds(env.getMaximumWindowBounds());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Can anyone make my program short? tnx

    i'm new in java programming and have limited knowledge in OOP.. please help me make my code short please please... tnx guys...
    i want to split my program in 2 or more files/classes..
    and can you help me with my looping .. thank you so much...
    my program works fine.. all i want is to make ot shorter coz it almost reach 4k lines...
    here is my code..
    package TXNCNT;
    //imports
    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.enterprisedt.net.ftp.FTPClient;
    import com.enterprisedt.net.ftp.FTPException;
    import org.apache.log4j.*;
    public class TxnCntMain extends JFrame {
        private static final String DATASOURCECONFIG = "datasource.properties";
        private static String FTP_IPADDRESS = "";
        private static String FTP_USERNAME  = "";
        private static String FTP_PASSWORD  = "";
        private static String FTP_FOLDER    = "";
        private static String FTP_FILE      = "";
        private static String JDBC_DRIVER = "";
        private static String JDBC_URL    = "";
        private static String JDBC_USER   = "";
        private static String JDBC_PWD    = "";
        private static String BRANCHES    = "";
        protected static Category log = Category.getInstance(TxnCntMain.class);
        static {
            try {
                InputStream ins  = (TxnCntMain.class).getResourceAsStream(
                          DATASOURCECONFIG);
                Properties props = new Properties();
                props.load(ins);
                FTP_IPADDRESS = props.getProperty("FTP_IPADDRESS");
                FTP_USERNAME  = props.getProperty("FTP_USERNAME");
                FTP_PASSWORD  = props.getProperty("FTP_PASSWORD");
                FTP_FOLDER    = props.getProperty("FTP_FOLDER");
                FTP_FILE      = props.getProperty("FTP_FILE");
            } catch (IOException ex) {
                ex.printStackTrace();
                TxnCntMain.log.error("Unable to load: " + DATASOURCECONFIG);
        /* Load properties file for JDBC settings */
        static {
            InputStream ins = (TxnCntMain.class).getResourceAsStream(DATASOURCECONFIG);
            Properties props = new Properties();
            try {
                props.load(ins);
            } catch (IOException ex) {
                log.error("Unable to load: " + DATASOURCECONFIG);
                throw new RuntimeException("Unable to load: " + DATASOURCECONFIG);
            JDBC_DRIVER = props.getProperty("JDBC_DRIVER");
            JDBC_URL = props.getProperty("JDBC_URL");
            JDBC_USER = props.getProperty("JDBC_USER");
            JDBC_PWD = props.getProperty("JDBC_PWD");
            BRANCHES = props.getProperty("BRANCHES");
        private static BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) );
        private Connection connect;
        private ControlPanel cp;
        private JTextArea output;
        private JScrollPane textpane;
        private String fromDate = "";
        private String toDate = "";
        private String fDate = "";
        private String tDate = "";
        private Object fromD, fromM, fromY, toD, toM, toY;
        private int FD, TD;
    ////variable used in ControlPanel Class
        private JButton saveButton;
        DecimalFormat dateFormat = new DecimalFormat("00");
        DecimalFormat bCodeFormat = new DecimalFormat("000");
        private int iBCode;
        int rGDep = 0; int rGWith = 0; int rGBP = 0; int rGAO = 0;
        int rGCT = 0;int rGFX = 0;int rGTD = 0;int rTotal = 0;
        public TxnCntMain() {
            super( "MIS REPORT - Branch Transaction Count" );
            Container c = getContentPane();
            output = new JTextArea( 6, 30 );
            output.setEditable(false);
            c.setLayout( new BorderLayout() );
            textpane = new JScrollPane( output );
            c.add( textpane, BorderLayout.CENTER);
    //////// Set up database connection
            try {
                Class.forName(JDBC_DRIVER);
                connect = DriverManager.getConnection( JDBC_URL, JDBC_USER, JDBC_PWD );
                output.append("Connection successful\n"
                            + "Welcome to MIS Report - Branch Transaction Count\n");
                log.info("Connection successful: Welcome to MIS Report - Branch Transaction Count");
            catch ( ClassNotFoundException cnfex ) {
                // process ClassNotFoundExceptions here
                cnfex.printStackTrace();
                output.append("Connection unsuccessful\n" +
                              cnfex.toString() + "\n" );
                log.info("Connection unsuccessful: " + cnfex.toString());
            catch ( SQLException sqlex ) {
                // process SQLExceptions here
                sqlex.printStackTrace();
                output.append( "Connection unsuccessful\n" +
                               sqlex.toString() + "\n" );
                log.info("Connection unsuccessful: " + sqlex.toString());
            catch ( Exception ex ) {
                // process remaining Exceptions here
                ex.printStackTrace();
                output.append( ex.toString() + "\n" );
                log.info(ex.toString());
            // Complete screen layout
            cp = new ControlPanel( connect, output);
            c.add( cp, BorderLayout.NORTH );
            setSize( 650, 450 );
            show();
            try {
                jbInit();
            } catch (Exception ex) {
                ex.printStackTrace();
    ////Inner Class ControLPanel//////////////////////////////////////////////////
        class ControlPanel extends JPanel {
            private JLabel fromDateLabel, fromMonthLabel, fromYearLabel,
                           toDateLabel, toMonthLabel, toYearLabel, from, to;
            private JComboBox fromDateCombo, fromMonthCombo, fromYearCombo,
                              toDateCombo, toMonthCombo, toYearCombo;
            private String days[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9",
                "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
                "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" };
            private String monthNames[] = { "January", "February", "March",
                    "April", "May", "June", "July", "August", "September",
                    "October", "November", "December" };
            private String years[] = { "1990", "1991", "1992", "1993", "1994",
                      "1995", "1996", "1997", "1998", "1999", "2000", "2001",
                      "2002", "2003", "2004", "2005", "2006", "2007", "2008",
                      "2009", "2010", "2011", "2012", "2013", "2014", "2015",
                      "2016", "2017", "2018", "2019", "2020", "2021", "2022",
                      "2023", "2024", "2025", "2026", "2027", "2028", "2029",
                      "2030", "2031", "2032", "2033", "2034", "2035", "2036",
                      "2037", "2038", "2039", "2040", "2041", "2042", "2043",
                      "2044", "2045", "2046", "2047", "2048", "2049", "2050" };
            public ControlPanel( Connection c, JTextArea t) {
                output = t;
                setLayout( new GridLayout(3,7) );
    ////////////FROM (1st row) /////////////////////////////////////////////////////
                from = new JLabel("  FROM: ");
                add(from);
                fromMonthLabel = new JLabel("Choose Month ",SwingConstants.RIGHT);
                add(fromMonthLabel);
                fromMonthCombo =  new JComboBox(monthNames);
                fromMonthCombo.setMaximumRowCount(12);
                fromMonthCombo.setSelectedIndex(0); //january
                fromM = fromMonthCombo.getSelectedItem();
                fromMonthCombo.addItemListener(
                    new ItemListener() {
                        public void itemStateChanged(ItemEvent e) {
                            fromM = fromMonthCombo.getSelectedItem();
                add(fromMonthCombo);
                fromDateLabel = new JLabel("Choose Date ", SwingConstants.RIGHT);
                add(fromDateLabel);
                fromDateCombo = new JComboBox(days);
                fromDateCombo.setMaximumRowCount(10);
                fromD = fromDateCombo.getSelectedItem();
                fromDateCombo.addItemListener(
                    new ItemListener() {
                        public void itemStateChanged(ItemEvent e) {
                            fromD = fromDateCombo.getSelectedItem();
                add(fromDateCombo);
                fromYearLabel = new JLabel("Choose Year ", SwingConstants.RIGHT);
                add(fromYearLabel);
                fromYearCombo = new JComboBox(years);
                fromYearCombo.setMaximumRowCount(10);
                fromYearCombo.setSelectedIndex(17);     //default selected value is 2007
                fromY = fromYearCombo.getSelectedItem();
                fromYearCombo.addItemListener(
                    new ItemListener() {
                        public void itemStateChanged(ItemEvent e) {
                            fromY = fromYearCombo.getSelectedItem();
                add(fromYearCombo);
    ////////////TO (2nd row) ///////////////////////////////////////////////////////
                to = new JLabel("  TO: ");
                add(to);
                toMonthLabel = new JLabel("Choose Month ",SwingConstants.RIGHT);
                add(toMonthLabel);
                toMonthCombo =  new JComboBox(monthNames);
                toMonthCombo.setMaximumRowCount(12);
                toMonthCombo.setSelectedIndex(0); //january
                toM = toMonthCombo.getSelectedItem();
                toMonthCombo.addItemListener(
                    new ItemListener() {
                        public void itemStateChanged(ItemEvent e) {
                            toM = toMonthCombo.getSelectedItem();
                add(toMonthCombo);
                toDateLabel = new JLabel("Choose Date ", SwingConstants.RIGHT);
                add(toDateLabel);
                toDateCombo = new JComboBox(days);
                toDateCombo.setMaximumRowCount(10);
                toDateCombo.setSelectedIndex(31 - 1); //default selected day is 31
                toD = toDateCombo.getSelectedItem();
                toDateCombo.addItemListener(
                    new ItemListener() {
                        public void itemStateChanged(ItemEvent e) {
                            toD = toDateCombo.getSelectedItem();
                add(toDateCombo);
                toYearLabel = new JLabel("Choose Year ", SwingConstants.RIGHT);
                add(toYearLabel);
                toYearCombo = new JComboBox(years);
                toYearCombo.setMaximumRowCount(10);
                toYearCombo.setSelectedIndex(17);     //default selected year is 2007
                toY = toYearCombo.getSelectedItem();
                toYearCombo.addItemListener(
                    new ItemListener() {
                        public void itemStateChanged(ItemEvent e) {
                            toY = toYearCombo.getSelectedItem();
                add(toYearCombo);
    ////////////3rd row ////////////////////////////////////////////////////////////
                JLabel l1 = new JLabel("     ");
                add(l1);
                JLabel l2 = new JLabel("     ");
                add(l2);
                JLabel l3 = new JLabel("     ");
                add(l3);
                JLabel l4 = new JLabel("     ");
                add(l4);
                JLabel l5 = new JLabel("     ");
                add(l5);
                JLabel l6 = new JLabel("     ");
                add(l6);
    ////////////create an instance of inner class ButtonHandler
    /////////////to use for button event handling
                ButtonHandler handler = new ButtonHandler();
                saveButton = new JButton("Save File");
                saveButton.addActionListener(handler);
                saveButton.setToolTipText("Generate CSV File");
                add(saveButton);
    ////////inner class for button event handling
            private class ButtonHandler implements ActionListener {
                public void actionPerformed(ActionEvent e) {
                    fromDate = dateFormat.format((fromMonthCombo.getSelectedIndex() + 1))
                        + dateFormat.format((fromDateCombo.getSelectedIndex() + 1))
                        + fromY.toString();
                    toDate = dateFormat.format((toMonthCombo.getSelectedIndex() + 1))
                        + dateFormat.format((toDateCombo.getSelectedIndex() + 1))
                        + toY.toString();
                    fDate = fromY.toString()
                        + dateFormat.format((fromMonthCombo.getSelectedIndex() + 1))
                        + dateFormat.format((fromDateCombo.getSelectedIndex() + 1));
                    tDate = toY.toString()
                        + dateFormat.format((toMonthCombo.getSelectedIndex() + 1))
                        + dateFormat.format((toDateCombo.getSelectedIndex() + 1));
                    FD = Integer.parseInt(fDate);
                    TD = Integer.parseInt(tDate);
                    if (FD > TD)  { //check if from date is greater than to date
                        JOptionPane.showMessageDialog(null,
                            "Unable to process... Please check date.",
                            "Error on Date", JOptionPane.ERROR_MESSAGE);
                        output.append("\nUnable to process... Please check date.");
                        log.info("Unable to process... Please check date.");
                    } else {
                        writeToFile();
    ////write to file:
        public void writeToFile() {
            String FILENAME_SUMMARY = "C:/TXNCNT/TotalNoOfTransactionsProcessedPerBranch"
                                  + "_From" + fromD + fromM + fromY
                                  + "To" + toD + toM + toY + ".csv";
            int grandDeposit = 0;
            int grandWithdrawal = 0;
            int grandBP = 0;
            int grandAO = 0;
            int grandCT = 0;
            int grandFX = 0;
            int grandTD = 0;
            int regionalGrandTotal = 0;
            try {
                FileOutputStream outputFile_Summary = new FileOutputStream(FILENAME_SUMMARY, false);
                PrintStream r = null;
                r = new PrintStream(outputFile_Summary);
                r.println("MIS REPORT - Branch Transaction Count");
                r.println(" ");
                r.println("TOTAL # OF TRANSACTIONS PROCESSED PER BRANCH");
                r.println("From: " + fromD + fromM + fromY + " To: " + toD + toM + toY);
                r.println("                                        "
                        + "                                        "
                        + "            TOTAL NUMBER OF TRANSACTIONS");
                r.println("#,BRANCH NAME,DEPOSIT,WITHDRAWALS,BILLS PAYMENT,ACCOUNT OPENING,"
                          + "CASH TURNOVER,FX SALE,TD OPENING,TOTAL");
                r.println("Region 1 GMA 1");
                String FILENAME_REGION = "C:/TXNCNT/" + "Region1_GMA1"
                                          + "_NoOfprocessedTransactionPerBranchPerTeller"
                                          + "_From" + fromD + fromM + fromY
                                          + "To" + toD + toM + toY + ".csv";
                FileOutputStream outputFile_Region = new FileOutputStream(FILENAME_REGION, false);
                PrintStream p = null;
                p = new PrintStream(outputFile_Region);
                p.println("MIS REPORT - Branch Transaction Count");
                p.println("# OF PROCESSED TRANSACTION PER BRANCH PER TELLER");
                p.println("From: " + fromD + fromM + fromY
                          + " To: " + toD + toM + toY);
                p.println("Region 1 GMA 1");
                String sBCode = BRANCHES.substring(0,BRANCHES.indexOf(","));
                int i = BRANCHES.indexOf(",");
                String sTemp = BRANCHES;
                final Vector branches = new Vector(325, 1);
                while (i != sTemp.length()) {
                    branches.addElement(sBCode);
                    sTemp = sTemp.substring(i+1);
                    i = sTemp.indexOf(",");
                    if(i==-1){
                        sBCode = sTemp;
                        branches.addElement(sBCode);
                        i = sTemp.length();
                    }else{
                       sBCode = sTemp.substring(0,sTemp.indexOf(","));
                int iDeposit, iWithdrawals, iBP, iAO, iCT, iFX, iTD, grandTotal;
                for (int b = 0; b < branches.size(); b++) {
                    iBCode = Integer.parseInt(branches.get(b).toString());
                    String code = bCodeFormat.format(iBCode);
                    int gDeposit, gWithdrawal, gBP, gAO, gCT, gFX, gTD;
                    String sTxn = "";
                    grandTotal = 0;
                    final Vector Teller = new Vector(25, 1);
                    gDeposit = 0; gWithdrawal = 0; gBP = 0; gAO = 0; gCT = 0; gFX = 0; gTD = 0;
                    String sBranchName = "";
                    //select branchname from um_branch
                    String sSQL = "SELECT branchname FROM um_branch WHERE "
                                  + "branchcode = " + "'" + code + "'";
                    Statement stmt = connect.createStatement();
                    ResultSet rsQuery = null;
                    rsQuery = stmt.executeQuery(sSQL);
                    if (rsQuery.next()) {
                        sBranchName = rsQuery.getString(1);
                    rsQuery.close();
                    stmt.close();
                    p.println();
                    p.println("Branch Code: " + code + ",Branch Name: " + sBranchName);
                    //retrieve userid's
                    sSQL = "SELECT distinct(userid) FROM bdsarchive.txnjournal WHERE "
                        + "branchno = '" + code + "' AND "
                        + "txndate >= '" + fromDate
                        + "' AND txndate <= '" + toDate + "'";
                    ResultSet rsQuery1 = null;
                    Statement stmt1 = connect.createStatement();
                    rsQuery1 = stmt1.executeQuery(sSQL);
                    int u = 0;
                    String tel = "";
                    String teller = "";
                    String space = "";
                    while (rsQuery1.next()) {
                        tel = rsQuery1.getString(1);
                        teller += "," + tel;
                        Teller.addElement(tel);
                        space += ",";
                        u++;
                    rsQuery1.close();
                    stmt1.close();
                    p.println("Transaction Type,Transaction ID" + teller + ",Total");
                    int tellerTotal[];
                    tellerTotal = new int[u];
                    //DEPOSITS
                    //txnid 1101//
                    int t = 0;
                    sTxn = "";
                    iDeposit = 0;
                    while (t < u) {
                        sSQL = "SELECT count(txnid) FROM bdsarchive.txnjournal WHERE "
                             + "txnid = '1101' AND userid = '" + Teller.get(t) + "' "
                             + "AND branchno = '" + code + "' "
                             + "AND txndate >= '" + fromDate + "' "
                             + "AND txndate <= '" + toDate + "'";
                        ResultSet rsQuery2 = null;
                        Statement stmt2 = connect.createStatement();
                        rsQuery2 = stmt2.executeQuery(sSQL);
                        while (rsQuery2.next()) {
                            sTxn = sTxn + rsQuery2.getString(1) + ",";
                            iDeposit = iDeposit + Integer.parseInt(rsQuery2.getString(1));
                            tellerTotal[t] += Integer.parseInt(rsQuery2.getString(1));
                        rsQuery2.close();
                        stmt2.close();
                        t++;
                    p.println("DEPOSIT,1101 - Peso (SV) Cash with Book," + sTxn + iDeposit);
                    gDeposit += iDeposit;
                    rGDep += iDeposit;
                    //txnid 1102//
                    t = 0;
                    sTxn = "";
                    iDeposit = 0;
                    while (t < u) {
                        sSQL = "SELECT count(txnid) FROM bdsarchive.txnjournal WHERE "
                             + "txnid = '1102' AND userid = '" + Teller.get(t) + "' "
                             + "AND branchno = '" + code + "' "
                             + "AND txndate >= '" + fromDate + "' "
                             + "AND txndate <= '" + toDate + "'";
                        ResultSet rsQuery2 = null;
                        Statement stmt2 = connect.createStatement();
                        rsQuery2 = stmt2.executeQuery(sSQL);
                        while (rsQuery2.next()) {
                            sTxn = sTxn + rsQuery2.getString(1) + ",";
                            iDeposit = iDeposit + Integer.parseInt(rsQuery2.getString(1));
                            tellerTotal[t] += Integer.parseInt(rsQuery2.getString(1));
                        rsQuery2.close();
                        stmt2.close();
                        t++;
                    p.println(",1102 - Peso (SV) OBCK with Book," + sTxn + iDeposit);
                    gDeposit += iDeposit;
                    rGDep += iDeposit;
                    //txnid 1103//
                    t = 0;
                    sTxn = "";
                    iDeposit = 0;
                    while (t < u) {
                        sSQL = "SELECT count(txnid) FROM bdsarchive.txnjournal WHERE "
                             + "txnid = '1103' AND userid = '" + Teller.get(t) + "' "
                             + "AND branchno = '" + code + "' "
                             + "AND txndate >= '" + fromDate + "' "
                             + "AND txndate <= '" + toDate + "'";
                        ResultSet rsQuery2 = null;
                        Statement stmt2 = connect.createStatement();
                        rsQuery2 = stmt2.executeQuery(sSQL);
                        while (rsQuery2.next()) {
                            sTxn = sTxn + rsQuery2.getString(1) + ",";
                            iDeposit = iDeposit + Integer.parseInt(rsQuery2.getString(1));
                            tellerTotal[t] += Integer.parseInt(rsQuery2.getString(1));
                        rsQuery2.close();
                        stmt2.close();
                        t++;
                    p.println(",1103 - Peso (SV) DDMC with Book," + sTxn + iDeposit);
                    gDeposit += iDeposit;
                    rGDep += iDeposit;
                    //txnid 1104//
                    t = 0;
                    sTxn = "";
                    iDeposit = 0;
                    while (t < u) {
                        sSQL = "SELECT count(txnid) FROM bdsarchive.txnjournal WHERE "
                             + "txnid = '1104' AND userid = '" + Teller.get(t) + "' "
                             + "AND branchno = '" + code + "' "
                             + "AND txndate >= '" + fromDate + "' "
                             + "AND txndate <= '" + toDate + "'";
                        ResultSet rsQuery2 = null;
                        Statement stmt2 = connect.createStatement();
                        rsQuery2 = stmt2.executeQuery(sSQL);
                        while (rsQuery2.next()) {
                            sTxn = sTxn + rsQuery2.getString(1) + ",";
                            iDeposit = iDeposit + Integer.parseInt(rsQuery2.getString(1));
                            tellerTotal[t] += Integer.parseInt(rsQuery2.getString(1));
                        rsQuery2.close();
                        stmt2.close();
                        t++;
                    p.println(",1104 - Peso (SV) PNBC with Book," + sTxn + iDeposit);
                    gDeposit += iDeposit;
                    rGDep += iDeposit;
                    //txnid 1105//
                    t = 0;
                    sTxn = "";
                    iDeposit = 0;
                    while (t < u) {
                        sSQL = "SELECT count(txnid) FROM bdsarchive.txnjournal WHERE "
                             + "txnid = '1105' AND userid = '" + Teller.get(t) + "' "
                             + "AND branchno = '" + code + "' "
                             + "AND txndate >= '" + fromDate + "' "
                             + "AND txndate <= '" + toDate + "'";
                        ResultSet rsQuery2 = null;
                        Statement stmt2 = connect.createStatement();
                        rsQuery2 = stmt2.executeQuery(sSQL);
                        while (rsQuery2.next()) {
                            sTxn = sTxn + rsQuery2.getString(1) + ",";
                            iDeposit = iDeposit + Integer.parseInt(rsQuery2.getString(1));
                            tellerTotal[t] += Integer.parseInt(rsQuery2.getString(1));
                        rsQuery2.close();
                        stmt2.close();
                        t++;
                    p.println(",1105 - Peso (SV) FDR with Book," + sTxn + iDeposit);
                    gDeposit += iDeposit;
                    rGDep += iDeposit;
                    //txnid 1106//
                    t = 0;
                    sTxn = "";
                    iDeposit = 0;
                    while (t < u) {
                        sSQL = "SELECT count(txnid) FROM bdsarchive.txnjournal WHERE "
                             + "txnid = '1106' AND userid = '" + Teller.get(t) + "' "
                             + "AND branchno = '" + code + "' "
                             + "AND txndate >= '" + fromDate + "' "
                             + "AND txndate <= '" + toDate + "'";
                        ResultSet rsQuery2 = null;
                        Statement stmt2 = connect.createStatement();
                        rsQuery2 = stmt2.executeQuery(sSQL);
                        while (rsQuery2.next()) {
                            sTxn = sTxn + rsQuery2.getString(1) + ",";
                            iDeposit = iDeposit + Integer.parseInt(rsQuery2.getString(1));
                            tellerTotal[t] += Integer.parseInt(rsQuery2.getString(1));
                        rsQuery2.close();
                        stmt2.close();
                        t++;
                    p.println(",1106 - Peso (SV) PNBC Cross Check with Book," + sTxn + iDeposit);
                    gDeposit += iDeposit;
                    rGDep += iDeposit;
                     //txnid 1107//
                    t = 0;
                    sTxn = "";
                    iDeposit = 0;
                    while (t < u) {
                        sSQL = "SELECT count(txnid) FROM bdsarchive.txnjournal WHERE "
                             + "txnid = '1107' AND userid = '" + Teller.get(t) + "' "
                             + "AND branchno = '" + code + "' "
                             + "AND txndate >= '" + fromDate + "' "
                             + "AND txndate <= '" + toDate + "'";
                        ResultSet rsQuery2 = null;
                        Statement stmt2 = connect.createStatement();
                        rsQuery2 = stmt2.executeQuery(sSQL);
                        while (rsQuery2.next()) {
                            sTxn = sTxn + rsQuery2.getString(1) + ",";
                            iDeposit = iDeposit + Integer.parseInt(rsQuery2.getString(1));
                            tellerTotal[t] += Integer.parseInt(rsQuery2.getString(1));
                        rsQuery2.close();
                        stmt2.close();
                        t++;
                    p.println(",1107 - Peso (SV) Credit Memo with Book," + sTxn + iDeposit);
                    gDeposit += iDeposit;
                    rGDep += iDeposit;
                     //txnid 1110//
                    t = 0;
                    sTxn = "";
                    iDeposit = 0;
                    while (t < u) {
                        sSQL = "SELECT count(txnid) FROM bdsarchive.txnjournal WHERE "
                             + "txnid = '1110' AND userid = '" + Teller.get(t) + "' "
                             + "AND branchno = '" + code + "' "
                             + "AND txndate >= '" + fromDate + "' "
                             + "AND txndate <= '" + toDate + "'";
                        ResultSet rsQuery2 = null;
                        Statement stmt2 = connect.createStatement();
                        rsQuery2 = stmt2.executeQuery(sSQL);
                        while (rsQuery2.next()) {
                            sTxn = sTxn + rsQuery2.getString(1) + ",";
                            iDeposit = iDeposit + Integer.parseInt(rsQuery2.getString(1));
                            tellerTotal[t] += Integer.parseInt(rsQuery2.getString(1));
                        rsQuery2.close();
                        stmt2.close();
                        t++;
                    p.println(",1110 - Peso (SV) Cash no Book," + sTxn + iDeposit);
                    gDeposit += iDeposit;
                    rGDep += iDeposit;
                    //txnid 1111//
                    t = 0;
                    sTxn = "";
                    iDeposit = 0;
                    while (t < u) {
                        sSQL = "SELECT count(txnid) FROM bdsarchive.txnjournal WHERE "
                             + "txnid = '1111' AND userid = '" + Teller.get(t) + "' "
                             + "AND branchno = '" + code + "' "
                             + "AND txndate >= '" + fromDate + "' "
                             + "AND txndate <= '" + toDate + "'";
                        ResultSet rsQuery2 = null;
                        Statement stmt2 = connect.createStatement();
                        rsQuery2 = stmt2.executeQuery(sSQL);
                        while (rsQuery2.next()) {
                            sTxn = sTxn + rsQuery2.getString(1) + ",";
                            iDeposit = iDeposit + Integer.parseInt(rsQuery2.getString(1));
                            tellerTotal[t] += Integer.parseInt(rsQuery2.getString(1));
                        rsQuery2.close();
                        stmt2.close();
                        t++;
                    p.println(",1111 - Peso (SV) OBCK no Book," + sTxn + iDeposit);
                    gDeposit += iDeposit;
                    rGDep += iDeposit;
                    //txnid 1112//
                    t = 0;
                    sTxn = "";
                    iDeposit = 0;
                    while (t < u) {
                        sSQL = "SELECT count(txnid) FROM bdsarchive.txnjournal WHERE "
                             + "txnid = '1112' AND userid = '" + Teller.get(t)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Well expanding on before.
    All this can be ripped out and put in a different method
    t = 0;
                    sTxn = "";
                    iDeposit = 0;
                    while (t < u) {
                        sSQL = "SELECT count(txnid) FROM bdsarchive.txnjournal WHERE "
                             + "txnid = '1104' AND userid = '" + Teller.get(t) + "' "
                             + "AND branchno = '" + code + "' "
                             + "AND txndate >= '" + fromDate + "' "
                             + "AND txndate <= '" + toDate + "'";
                        ResultSet rsQuery2 = null;
                        Statement stmt2 = connect.createStatement();
                        rsQuery2 = stmt2.executeQuery(sSQL);
                        while (rsQuery2.next()) {
                            sTxn = sTxn + rsQuery2.getString(1) + ",";
                            iDeposit = iDeposit + Integer.parseInt(rsQuery2.getString(1));
                            tellerTotal[t] += Integer.parseInt(rsQuery2.getString(1));
                        rsQuery2.close();
                        stmt2.close();
                        t++;
                    p.println(",1104 - Peso (SV) PNBC with Book," + sTxn + iDeposit);
                    gDeposit += iDeposit;
                    rGDep += iDeposit;Then just call the method with the txnid value. So perhaps a List ( ArrayList) of txnid values and a for loop.
    Boom. There's a great chunk of repetitive code gone.
    Then the next step in refactoring to different classes is to seperate out all the pieces.
    Put the FTP bits in to one class.
    Put the database and processing stuff into another class.
    Put the report writing into another class.
    That would be a good start.

  • Should I use a SwingWorker or SwingUtilities.invokeLater() to update my UI?

    Are there specific situations where you want to use method above the other? This whole swing concurrency is very new to me, and I don't really know where to begin.

    When executing long running code you don't want the GUI to freeze. Therefore you have two things to be concerned about. First, you want the long running task to execute in a separate Thread. Secondly, when you need to update the GUI from this code you need to make sure the code executes on the Event Dispatch Thread (EDT).
    You can code this manually by creating a separate Thread and then use SwingUtilities.invokeLater() when necessary.
    A SwingWorker tries to simplify this process by having a simple API where you can add code that executes on a separate Thread or where you can add code that executes on the EDT.
    So in the case of managing long running tasks, the end result should be the same.
    Hwever, there are times when I know code is already executing on the EDT, but I sometimes use invokeLater(..) to force my code to the end of the EDT. This is used in special situations when code doesn't execute in the order you want.
    For example, I've tried to add a FocusListener to a JFormattedTextField to "select the text" when it gains focus. The problem is the the UI also adds a FocusListener. Because of the way listeners are handled the last listener added to the component executes first. Therefore, using the invokeLater() forces my listener code to execute last.
    You can try this code to see what I mean:
    KeyboardFocusManager.getCurrentKeyboardFocusManager()
         .addPropertyChangeListener("permanentFocusOwner", new PropertyChangeListener()
         public void propertyChange(final PropertyChangeEvent e)
              if (e.getNewValue() instanceof JTextField)
                   //  invokeLater needed for JFormattedTextField
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             JTextField textField = (JTextField)e.getNewValue();
                             textField.selectAll();
    });Edited by: camickr on Mar 5, 2011 2:36 PM

  • How to make my program work using 2 files separately?

    My main file is ExpenseTracker.java. When u
    compile the ExpenseTracker.java , there is a column of buttons on the left
    and a right box. I would like to make the output of the RecordMenu.java
    appear(not pop out) in the right box of my ExoenseTracker when i click one
    of the button 'Record Expenses'. I wonder you can help me in this? I am
    facing that problem right now.=======================================================================
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class ExpenseTracker extends JFrame {
    public ExpenseTracker() {
    super("Expense Tracker");
    // FirstPanel
    JPanel FirstPanel = new JPanel();
    FirstPanel.setLayout(null);
    JLabel labeltracker = new JLabel("Expense Tracker");
    JButton recordExpenses = new JButton("Record Expenses");
    JButton viewExpenses = new JButton("View Expenses");
    JButton calendar = new JButton("Calendar" );
    JButton exit = new JButton("Exit");
    labeltracker.setBounds(40,120,135,30);
    recordExpenses.setBounds(25,160,135,30);
    viewExpenses.setBounds(25,210,135,30);
    calendar.setBounds(25,260,135,30);
    exit.setBounds(25,310,135,30);
    FirstPanel.setBounds(5,5,200,500);
    FirstPanel.add(labeltracker);
    FirstPanel.add(recordExpenses);
    FirstPanel.add(viewExpenses);
    FirstPanel.add(calendar);
    FirstPanel.add(exit);
    //SecondPanel
    JPanel SecondPanel = new JPanel();
    SecondPanel.setLayout(new BorderLayout(1,2));
    // SecondPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
    SecondPanel.setBorder(new LineBorder(Color.black));
    SecondPanel.setBounds(210,120,530,270);
    getContentPane().setLayout(null);
    getContentPane().add(FirstPanel);
    getContentPane().add(SecondPanel);
    setSize(800,500);
    setVisible(true);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    public static void main(String [] args) {
    new ExpenseTracker();
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class RecordMenu extends JFrame implements ItemListener,ActionListener {
    >>
    JCheckBox weekly;
    JCheckBox monthly;
    public RecordMenu() {
    super("Choose");
    Container c = getContentPane();
    JPanel checkPanel = new JPanel();
    checkPanel.setLayout(new GridLayout(4,2));
    checkPanel.setBorder(new TitledBorder("Record Expenses"));
    JLabel label2 = new JLabel("Amount to track:");
    JTextField amtField = new JTextField(5);
    //Create the check boxes.
    weekly = new JCheckBox("Weekly");
    weekly.setSelected(false);
    monthly = new JCheckBox("Monthly");
    monthly.setSelected(false);
    //Register a listener for the check boxes.
    weekly.addItemListener(this);
    monthly.addItemListener(this);
    amtField.addActionListener(this);
    //Put the check boxes in a column in a panel
    checkPanel.add(weekly,BorderLayout.NORTH);
    checkPanel.add(monthly,BorderLayout.SOUTH);
    checkPanel.add(label2);
    checkPanel.add(amtField);
    JPanel buttonPanel = new JPanel();
    JButton buttonOk = new JButton("OK");
    JButton buttonCancel = new JButton("Cancel");
    buttonPanel.add(buttonOk);
    buttonPanel.add(buttonCancel);
    c.add(checkPanel,BorderLayout.NORTH);
    c.add(buttonPanel);
    setSize(370,200);
    setVisible(true);
    /** Listens to the check boxes. */
    public void itemStateChanged(ItemEvent event) {
    public static void main(String[] args) {
    new RecordMenu();

    but i wan e program to work wit 2 file, not all e 2 file codes put together in a file. I wonder if can call e code from the recordmenu file when i execute the expenseTracker file. I not sure i explain this way u will understand?
    When the record menu 'ok' is clicked there will b a JOptionpane tat will pop out saying
    'Total amt to b tracked on a weekly basis is (amt entered in textfield)"
    if e checkbox is selected weekly, the output will be like e above
    otherwise it will display 'Total amt to b tracked on a monthly basis is (amt entered in textfield)".
    ya e textfield input must be numbers.

  • Is it safe to use SwingUtilities.invokeLater(), while updating GUI?

    Hi,
    I am updating GUI components in synchronized block which is runinng on main() thread my application hangs, but if I use SwingUtilities.invokeLater(...) then it runs fine.
    My question is:
    Is it safe to use SwingUtilities.invokeLater(...) in synchronized block.
    Edited by: Amol_Parekh on Nov 1, 2007 1:28 AM

    Paul Hyde in his "Java Thread Programming" (great book!!!) says it is.
    With invokeLater() you say to the Thread Scheduler you want that code to run on the Swing thread. In fact, if that is the only thing you do in the synchronized block I think it is unnecessary.
    Greetings,
    astrognom

Maybe you are looking for