JTextField event output problem

Hello,
I am learning Java 2 and creating a swing program to handle mortgage amortization calcs. I have a main and event file.
In the main, I have JTextFields to display the output of the variable calculations that run in the event program.
Everything seems to be functioning properly, except that only the last run through the loop displays. I have experimented with "thread sleep" to slow the loop, but still the only output is the last run through the loop.
Is there anything simple concerning JTextField output and looping that Ive missed?
Here is my loop:
void startCalc() {
               gui.calc.setEnabled(true);
               gui.reset.setEnabled(true);
                    //get input values and convert from text to numbers
          double prin1 = Double.parseDouble(gui.principle.getText());
               double interest1 = Double.parseDouble(gui.iRate.getText());
               int term1 = Integer.parseInt(gui.years.getText());
                    // start monthly payment calc
               double moint1 = interest1/(12*100);
               double month1 = term1*12;
               double pay1 = (prin1 * (moint1/(1-(Math.pow(1 + moint1,-month1)))));
                              // output to mortgui1
          NumberFormat formatter = new DecimalFormat("0.00");
          gui.pay.setText("$"+ formatter.format(pay1));
          double begin1 = prin1;
                    for(int loan1=0;loan1 < month1;loan1++) {
                              double intpaid1 = (moint1) * begin1;
                              double prpaid1 = pay1 - intpaid1;
                              double end1 = begin1 - prpaid1;
                    begin1 = end1;
               try{
                    Thread.sleep(100);
                    }catch(InterruptedException e){ };
          gui.amortize.setText("Payment number"+(loan1+1));
                    gui.ipaid.setText("Interest paid is $" formatter.format(intpaid1) " Principal paid is $" +formatter.format(prpaid1));
                    gui.balance.setText("Ending balance is $" +formatter.format(end1));
                    }

Thanks, as you can see Im pretty new to Java... I will need to add gui.* to the methods you have shown me correct?
Here is my full code for the event. Mortgui2 is the main file where I have the guis set up.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.text.*;
import javax.swing.text.*;
public class Mort2JR implements ActionListener, ItemListener {
Mortgui2 gui;
public Mort2JR(Mortgui2 in){
gui = in;
// Array for 3 hardcode morts and one freeform
public void actionPerformed(ActionEvent event){
String command = event.getActionCommand();
if (command == "Clear")
clearAllFields();
if (command == "Calculate")
     startCalc();
public void itemStateChanged(ItemEvent event) {
     Object item = event.getItem();
     if (item == gui.sevenYear) {
          gui.iRate.setText("5.35");
          gui.years.setText("7");
          gui.iRate.setEnabled(false);
          gui.years.setEnabled(false);
     if (item == gui.fifteenYear) {
          gui.iRate.setText("5.5");
          gui.years.setText("15");
          gui.iRate.setEnabled(false);
          gui.years.setEnabled(false);
          gui.adhoc.setEnabled(true);
     if (item == gui.thirtyYear) {
          gui.iRate.setText("5.75");
          gui.years.setText("30");
          gui.iRate.setEnabled(false);
          gui.years.setEnabled(false);
          gui.adhoc.setEnabled(true);
     if (item == gui.adhoc) {
          gui.iRate.setEnabled(true);
          gui.years.setEnabled(true);
          void clearAllFields(){
gui.principle.setText(null);
gui.iRate.setText(null);
gui.years.setText(null);
gui.pay.setText(null);
void startCalc() {
               gui.calc.setEnabled(true);
               gui.reset.setEnabled(true);
                    //get input values and convert from text to numbers
          double prin1 = Double.parseDouble(gui.principle.getText());
               double interest1 = Double.parseDouble(gui.iRate.getText());
               int term1 = Integer.parseInt(gui.years.getText());
                    // start monthly payment calc
               double moint1 = interest1/(12*100);
               double month1 = term1*12;
               double pay1 = (prin1 * (moint1/(1-(Math.pow(1 + moint1,-month1)))));
                              // output to mortgui1
          NumberFormat formatter = new DecimalFormat("0.00");
          gui.pay.setText("$"+ formatter.format(pay1));
//// Delay between new Mortage amortization schedule
                    //               try{
                    //                         Thread.sleep(4000); // 4000 milliseconds
                    //                         }catch(InterruptedException e){ };
               // Amortization loop will calculate object attributes for outfile
               double begin1 = prin1;
                    for(int loan1=0;loan1 < month1;loan1++) {
                              double intpaid1 = (moint1) * begin1;
                              double prpaid1 = pay1 - intpaid1;
                              double end1 = begin1 - prpaid1;
                    begin1 = end1;
               try{
                    Thread.sleep(100);
                    }catch(InterruptedException e){ };
          gui.amortize.setText("Payment number"+(loan1+1));
                    gui.ipaid.setText("Interest paid is $" formatter.format(intpaid1) " Principal paid is $" +formatter.format(prpaid1));
                    gui.balance.setText("Ending balance is $" +formatter.format(end1));

Similar Messages

  • Labview slider event handling problems - revisited

    This topic asked a question that was very close to a problem I am having:
    Labview slider event handling problems
    That is, how do I, using an event structure and/or other means, only read out the value of a slider control after the value change is finalized?
    The extra constraint I'd like to place on this, which I believe will invalidate the answer given in the thread above, is that my slider control also has a digital display which can also be used to change the value without ever using the mouse. I cannot look for a value change followed by a mouse-up event if the mouse was not used to change the value.
    Any ideas how this might be accomplished? FWIW, I am using LabVIEW 7.0

    Each and every incremental value-change event generated by the movement of the slider is still detected and queued up for use by the event structure and the event structure loop wades through them all before it's done.
    I have come up the attached "fix" (LV v7.0) for this problem. While it is not as clean a solution as I had hoped it would be, it's the best I can manage given what LabVIEW offers me to work with and it does work in the situation where I need to use it.
    Now, within the Finalize Slider Events subVI, I'm keeping track of the most-recent values seen by the subVI, checking to see if they have changed, and reporting out that fact. That gives me a Changed/Not-Changed bit within the event case that I can use to control what code then gets executed. If the event case is just playing catch-up to the real value of the control, I can now see that fact and ignore it.
    In this version I've also dumped the variant output and limited the VI to using DBL values. I decided it added complication to something that was too complicated already and I wanted the output terminals for other purposes anyway (reporting of the correct "OldVal" of the control).Message Edited by Warren Massey on 04-28-2005 03:56 AM
    Attachments:
    slider_events[5].llb ‏77 KB

  • Macbook mini DVI to DVI output problems

    hi
    I've been using a samsung syncmaster 22" with my macbook for about a year now with no problems using the mini DVI to DVI connection
    then earlier this week i used a different DVI cable to plug my playstation 3 into the screen, when i plugged the computer DVI cable back into the screen lots of red/pink pixels have taken over the screen and when the desk is nudged red lines flash up
    i thought it might be either the DVI cable or the mini DVI to DVI adapter and replaced both to no avail, i have also tested all the cables on other screens/with other computers, and tested the screen with my playstation. Screen and cables all work fine so i think it must be some kind of output problem, but cant work out what it could be seeing as nothing would have happened to the port on the actual computer whilst changing connections on the samsung screen
    sorry for the long winded post, really wanna know what the problem is here

    Hi cbeth,
    welcome to macbook forum.
    For your friend macbook, try to press F7 back and forth to switch between mirror and expanded mode.
    Try to update your macbook hardware firmware and software using software updater and repair permission after that...application/utilities/disk utility/repair permission.
    Also reset your PRAM and PMU.
    Open your friend system preference / display and try to compare and set yours similar to hers, including resolution, color depth, refresh rate.
    Good Luck.

  • Mac mini audio output problems

    This is similar to a problem that appeared before, but with a different twist.
    On 4 July all was well. On 5 July I switched on and there was no "chord" from the Mac. When I collected my mail - no sound from my speakers (which are part of my screen). Logged on to a couple of sites - no sound.
    The System Profiler, under the "Audio (Built In)" category, says: "No Built-in Audio." I know that's wrong because it's always worked before and when I plug my headset in it works fine.
    When I go to the Sound preferences panel in System Preferences, it finds the headset but if I unplug that it finds nothing.
    I tried running the hardware test (by putting in the OS X install disc and holding D during startup.) It couldn't find a problem.
    So, as far as I can see, audio output is fine for the USB headset output but not for the others. Is there a simple fix? The nearest Apple store is about 200 miles away and I don't fancy the idea of posting the Mac off.
    (And I think it's still under warranty for a couple more weeks.)
    Mac mini   Mac OS X (10.4.10)  

    hello mini users with the "no audio output" problem
    it seems that there are faulty output jacks in the macbook and the mac mini
    there are two things you can try:
    i tried everything and began thinking about what new software i had installed. it was "macam" which enables you to use older webcams on OSX. i needed that to use my webcam on skype.
    macam installs a file called "macam.component"
    if you have the same, do this - take that file out of:
    (your hard drive)/library/quicktime - macam.component
    and just put it on your desktop
    restart, then in your sound pref's choose your audio output (if doesn't work restart again)
    the first time i took it out, i had my sound back instantly, another time i had to choose audio output in sound prefs. you kind of have to try different things. after you get your sound back, you can put back "macam.component" to use your webcam.
    it seems macam causes the problem, the two can not work at the same time.
    the second thing: if you dont have "maccam" try plugging and unplugging output jack a few times and restarting until you have sound.
    the problem still could be with the OSX 10.4.10 update / quicktime...or maybe even a hardware problem like others with macbooks were saying (with the red light), not sure.
    people with macbooks and who have the red light on, say to use a paperclip to turn off the switch inside.
    my mini does not have a red light on. i tried using a paperclip but it doesnt work.
    hope this helps, beleive me i feel your pain!!!!
    what good is a computer without sound?
    extremely annoying problem that i hope apple looks into and fixes
    -andrew

  • What is Event queue problem?

    HI,
    I have come across JSF document, they mentioned that Event queue
    Problem ins SUN's JSF implementation. what is that?

    You're going to have to be a little more specific.

  • GUI event handling problems appear in 1.4.1 vs. 1.3.1?

    Hi,
    Has anyone else experienced strange event handling problems when migrating from 1.3.1 to 1.4.1? My GUI applications that make use of Swing's AbstractTableModel suddenly don't track mouse and selection events quickly anymore. Formerly zippy tables are now very unresponsive to user interactions.
    I've run the code through JProbe under both 1.3 and 1.4 and see no differences in the profiles, yet the 1.4.1 version is virtually unusable. I had hoped that JProbe would show me that some low-level event-handling related or drawing method was getting wailed on in 1.4, but that was not the case.
    My only guess is that the existing installation of 1.3.1 is interfering with the 1.4.1 installation is some way. Any thoughts on that before I trash the 1.3.1 installation (which I'm slightly reluctant to do)?
    My platform is Windows XP Pro on a 2GHz P4 with 1GB RAM.
    Here's my test case:
    import javax.swing.table.AbstractTableModel;
    import javax.swing.*;
    import java.awt.*;
    public class VerySimpleTableModel extends AbstractTableModel
    private int d_rows = 0;
    private int d_cols = 0;
    private String[][] d_data = null;
    public VerySimpleTableModel(int rows,int cols)
    System.err.println("Creating table of size [" + rows + "," + cols +
    d_rows = rows;
    d_cols = cols;
    d_data = new String[d_rows][d_cols];
    int r = 0;
    while (r < d_rows){
    int c = 0;
    while (c < d_cols){
    d_data[r][c] = new String("[" + r + "," + c + "]");
    c++;
    r++;
    System.err.println("Done.");
    public int getRowCount()
    return d_rows;
    public int getColumnCount()
    return d_cols;
    public Object getValueAt(int rowIndex, int columnIndex)
    return d_data[rowIndex][columnIndex];
    public static void main(String[] args)
    System.err.println( "1.4..." );
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    Dimension size = new Dimension(500,500);
    panel.setMinimumSize(size);
    panel.setMaximumSize(size);
    JTable table = new JTable(new VerySimpleTableModel(40,5));
    panel.add(table);
    window.getContentPane().add(panel);
    window.setSize(new Dimension(600,800));
    window.validate();
    window.setVisible(true);
    Thanks in advance!!
    - Dean

    Hi,
    I've fixed the problem by upgrading to 1.4.1_02. I was on 1.4.1_01.
    I did further narrow down the symptoms more. It seemed the further the distance from the previous mouse click, the longer it would take for the table row to highlight. So, clicking on row 1, then 2, was much faster than clicking on row 1, then row 40.
    If no one else has seen this problem -- good! I wouldn't wish the tremendous waste of time I've had on anyone!
    - Dean

  • Delimited output problem at the time of writing in to text file

    Hi ,
    I am using matrix stayle design for my reports when i am generating reports in delimited format i am getting Delimited output problem(DR.Watson ERROR) at the time of writing in to textfile.

    Hi,
    Try with new desformat delimiteddata which is available with Report 6i patch 11.
    Thanks
    Oracle Reports Team

  • Can someone explain what (((JTextField) event.getSource()).getText()) does?

    I don't know what the casting(?) with JTextField is doing...
    Here is the code snippet:
    public void actionPerformed( ActionEvent event )
    int convertTemp, temp;
    temp = Integer.parseInt( ( ( JTextField ) event.getSource() ).getText() );

    Also, why doesn't event.getSource() return the specific source data type?Good question. In one sense it does return a JTextField. But it does so at runtime; long after the compiler has done its thing. The compiler deals with declarations only and doesn't try and predict the future runtime behaviour. (Consider the case of "skins" and things where the end user can replace your JTextField with some other GUI widget, presumably a subclass of JTextField. In that case event.getSource() will return a UserDefinedTextFieldWidget).
    As you say, the API says that the return type is declare as Object. Presumabley this is because they wanted to write a general purpose event notifying system where the "source" identifier could be anything at all. And its that declaration alone that counts for the Java compiler. Two things follow:
    (1) The programmer will be allowed to cast the returned thing to any type whatsoever - thereby allowing the API writers' intention to provide a general purpose notifying mechanism to be realised.
    (2) The programmer must cast since all the mechanism promises is a "bland Object" (though at runtime it will return some more specific type)
    It's a question of balance. Had event.getSource() returned a Component you would have been able to use at least the Component methods without casting. But, in that case the mechanism would not have been as general. (The source could not be identified as an id in some database, for instance.)

  • Premiere Elements 12 output problem

    I am having problems outputting my project. Different errors messages.  One says transcoding error.  Another time it says export error.  Other times it crashes. And then the program won't even open. 
    Any suggestions?
    bwatson9

    Steve,
    First, thank you for your prompt response.  This is the first time I have used Premiere Elements 12.  I don't seem to have a manual for the software.
    The product was bought with my new computer.  I am using windows 8.1 (64-bit) with Intel Core i7-4770 CPU @ 3.40GHz.  I have 12 GB of installed RAM.  I have 1TB hard drive of which this is the first project I done. 
    I have checked to make sure that I am getting all Windows and Microsoft Updates.  I even manually went to Windows Update and installed the optional updates.
    The project is a 20 min. video using mostly photos and 2 small video clips.  The project is saved in its own folder.
    When I go to the timeline in Expert view I do see an orange-yellow line above the timeline.  It runs the whole length of the project.
    I understand from reading the FAQ's that each photo cannot be larger than 1000 x 750 pixels.  I will check that and reduce their size.  Is there anything else that I need to do?
    Where can I find a manual?
    Thanks,
    bwatson9
    Date: Sun, 23 Mar 2014 06:31:03 -0700
    From: [email protected]
    To: [email protected]
    Subject: Premiere Elements 12 output problem
        Re: Premiere Elements 12 output problem
        created by Steve Grisetti in Premiere Elements - View the full discussion
    A lot depends on a lot.
    What operating system are you using? What processor do you have and how much RAM and how much free space is on your hard drive?
    How long is your project? What model of camcorder is your video coming from and what format and resolution is it?
    Have you ensured that your project file is saved to its own folder, with no other project files in this folder?
    When you add your video to your timeline in Expert view, do you see a yellow-orange line above the clips, along the top of the timeline? This indicates a mismatch between project settings and video specs.
    If you are on a Windows computer, have you set up your computer to get both Windows and Microsoft Updates -- and have you manually gone to Windows Update and ensured you have even the optional updates that don't install automatically?
    When did you last run Disk Cleanup and Disk Defragmenter?
         Please note that the Adobe Forums do not accept email attachments. If you want to embed a screen image in your message please visit the thread in the forum to embed the image at http://forums.adobe.com/message/6234402#6234402
         Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page: http://forums.adobe.com/message/6234402#6234402
         To unsubscribe from this thread, please visit the message page at http://forums.adobe.com/message/6234402#6234402. In the Actions box on the right, click the Stop Email Notifications link.
               Start a new discussion in Premiere Elements at Adobe Community
      For more information about maintaining your forum email notifications please go to http://forums.adobe.com/thread/416458?tstart=0.

  • Delicate ProgressMonitor/ event handling problem

    Hi,
    I have a delicate ProgressMonitor / event handling problem.
    There exists some solution on similiar problems here in the forums, but no solution to my special problem, hope anybody can help me out.
    I have a rather big project, an applet, that I've written a separate JarLoader class that will load specific jar's if the ClassLoader encounter a unloaded class, all ok so far.
    But, during loading, I would like to display a ProgressBar. And here is the problem. If my custom ClassLoader intercepts a findClass -request that needs to load the class from a jar from a normal thread, this is no problem, but if the ClassLoader intercepts a findClass that needs loading a jar when inside the EventQueue -thread, this is becomming tricky!
    The catch is that an event posted on the EventQueue finally needs a class that needs to be loaded, but I cannot dispatch a thread to do this and end that particular event before the class itself is loaded.
    So how do I hold the current EventQueue -event needing a jar -load, Pop up a ProgressBar, then process events in the EventQueue to display the ProgressBar and update repaints in it? then return from the event that now have loaded needed class-files.
    I've tried a tip described earlier in the forums by trying to handle events with this code when loading the Jar:
        /** process any waiting events - use during long operations
         * to update UI */
        static public void doEvents() {
            // need to derive from EventQueue otherwise
            // don't have access to protected method dispatchEvent()
            class EvtQueue extends java.awt.EventQueue {
                public void doEvents() {
                    Toolkit toolKit = Toolkit.getDefaultToolkit();
                    EventQueue evtQueue = toolKit.getSystemEventQueue();
                    // loop whilst there are events to process
                    while (evtQueue.peekEvent() != null) {
                        try {
                            // if there are then get the event
                            AWTEvent evt = evtQueue.getNextEvent();
                            // and dispatch it
                            super.dispatchEvent(evt);
                        catch (java.lang.InterruptedException e) {
                            // if we get an exception in getNextEvent()
                            // do nothing
            // create an instance of our new class
            EvtQueue evtQueue = new EvtQueue();
            // and call the doEvents method to process the events.
            evtQueue.doEvents();       
        }Then, the loader checks
    java.awt.EventQueue.isDispatchThread()to see if its' inside the eventqueue, and runs doEvents after updating the ProgressMonitor with new setProgress and setNote values.
    More precise;
    The loader is loading the jar like this:
    (this is pseudo code, not really usable, but outlines the vital parts)
    public void load() {
      monitor = new ProgressMonitor(null, "Loading " + jarName, ""+jarSize + " bytes", 0, jarSize);
      monitor.setMillisToDecideToPopup(0);
      monitor.setMillisToPopup(0);
      // reading jar info code here ...
      JarEntry zip = input.getNextJarEntry();
      for (;zip != null;) {
         // misc file handling here... total = current bytes read
         monitor.setProgress(total);
         monitor.setNote(note);
         if (java.awt.EventQueue.isDispatchThread()) {
            doEvents();
         zip = input.getNextJarEntry();
      monitor.close();
    }When debugging doEvents(), there is never any events pending in peekEvents(), even if I tries to put a invokeLater() to run the setProgress on the monitor, why? If it had worked, the doEvents() code would have saved my day...
    So, this is where I'm totally stuck...

    Just want to describe how I did this using spin from http://spin.sourceforge.net
    This example is not pretty, but it can probably help others understanding spin. Cancelling the ProgressMonitor is not implemented, but can easily be done by checking on ProgressMonitor.isCanceled() in
    the implementation code.
    First, I create a bean for displaying and run a ProgressMonitor:
    Spin requires an Interface and an Implementation, but that's just nice programming practice :-)
    import java.util.*;
    public interface ProgressMonitorBean {
        public void start(); // start spinning
        public void cancel(); // cancel
        public int getProgress(); // get the current progress value 
        public void setProgress(int progress); // set progress value
        public void addObserver(Observer observer); // observer on the progressValue
    }Then, I created the implementation:
    import java.util.*;
    import javax.swing.ProgressMonitor;
    import java.awt.*;
    public class ProgressMonitorBeanImpl extends Observable implements ProgressMonitorBean {
        private ProgressMonitor monitor;
        private boolean cancelled;
        private int  progress = 0;
        private int  currentprogress = 0;
        public ProgressMonitorBeanImpl(Component parent, Object message, String note, int min, int max) {
            monitor = new ProgressMonitor(parent, message, note, min, max);
            monitor.setMillisToDecideToPopup(0);
            monitor.setMillisToPopup(0);       
        public void cancel() {
            monitor.close();
        public void start() {
            cancelled = false;
            progress = 0;
            currentprogress = 0;
            while (progress < m_cMonitor.getMaximum()) {
                try {
                    synchronized (this) {
                        wait(50); // Spinning with 50 ms delay
                    if (progress != currentprogress) { // change only when different from previous value
                        setChanged();
                        notifyObservers(new Integer(progress));
                        monitor.setProgress(progress);
                        currentprogress = progress;
                } catch (InterruptedException ex) {
                    // ignore
                if (cancelled) {
                    break;
        public int getProgress() {
            return progress;
        public void setProgress(int progress) {
            this.progress = progress;
    }in my class/jarloader code, something like this is done:
    public void load() {
      ProgressMonitorBean monitor = (ProgressMonitorBean)Spin.off(new ProgressMonitorBeanImpl(null, "Loading " + url,"", 0, jarSize));
      Thread t = new Thread() {
        public void run() {
          JarEntry zip = input.getNextJarEntry();
          for (;zip != null;) {
            // misc file handling here... progress = current bytes read
         monitor.setProgress(progress);
      t.start(); // fire off loadin into own thread to do time consuming work
      monitor.start(); // this will spin events on monitor and block until progress = max
      monitor.cancel(); // Just make sure ProgressMonitor is closed
    }The beautiful thing here is that Spin is taking care of weither the load() is inside the dispatch thread or not, making the code much simpler and cleaner to understand.
    The ProgressMonitorBeanImplementation could been made much nicer and more complete, but I was in a hurry to check if it worked out. And it did! This will be applied on a lot of gui -components that blocks the event-queue in our project, making it much more responsive.
    Hope this will help others in similiar situations! Thanks again svenmeier for pointing me to the spin -project.

  • Graphic output problems in most programs - triangles ...

    - often at scrolling in the Finder
    - it appears spontaniously and dissappers/flicker if mouse is moving ...
    - in some programs it is permanent for example 3D Coat
    - different often and strong in different programs - in some there is no problem (5% - for example ZBrush)
    - Mountain Lion does not fix it - only some changes - for example Quicktime (not Fullscreen) a big triangle in the down left
    - little greeen/red pionts, like defect Pixels, in little groups are appearing too! - Photoshop, Final Cut Video Output...

    A screenshot give you a copy of what is actually sitting in the screen buffer.
    So this is not an "output" problem. That stuff has been messed up in the screen buffer.
    to draw the mouse cursor, the area around the pointer must be re-constructed. That is why moving the mouse cursor seems to "repair" it.

  • Print Output problem in ECC6

    Hi Friends,
    I am getting print output problem in ECC6.
    In VF03 I am giving issue output for invoice printing. Whenever I am presseing issue output one screen is coming for selecting output type. I have selected one output type and I pressed print preview then in print preview one item and corresponding amounts it is showing properly for the first time. But the problem is after the print preview if I come back and again if i press print preview button values are not getting refreshed and same item is repeated for twice and the amounts are also getting added. Again for the third time if i come back and again if i press print preview one more item is getting repeated and the amounts are also getting added which should not suppose to happen.
    What could be the problem and how to resolve it?
    Rewarded,
    Steve

    Hi,
    clear those variables in the program .
    Regards,
    Bharat.
    Reward points if helpful

  • J Option Pane Output Problem

    Hi guys,
    I am new to Java and I am having trouble compiling this program via which I can calculate the number of months to pay off a loan.
    I am not sure why it is not compiling and would really appreciate some solutions or suggestions
    Thanks a lot.
    import javax.swing.JOptionPane;
    public class Final
    public static void main(String[] args)
    String LoanAmount;
    String Months;
    String AnnualInterestRate;
    String MonthlyPayments;
    double balance;               
    double interest;
    double payment;
    int months=1;
    LoanAmount=JOptionPane.showInputDialog("Enter Loan Amount:");
    AnnualInterestRate=JOptionPane.showInputDialog("Enter Interest Rate:");
    MonthlyPayments=JOptionPane.showInputDialog("Monthly Payments:");
    balance=Double.parseDouble(LoanAmount);
    interest=Double.parseDouble(AnnualInterestRate);
    payment=Double.parseDouble(MonthlyPayments);
    months=Integer.parseInt(Months);
    while (balance>0)
    {balance=(balance+(interest/12)*(balance))-payment;
    months=months+1;
    JOptionPane.showMessageDialog(null, "Number of Months ", +months);
    Edited by: Java1001 on Sep 15, 2009 11:45 PM

A: J Option Pane Output Problem

Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
You are passing 3 parameters -- a null, a String and an int -- to the JOptionPane#showMessageDialog method. In the [_API_|http://java.sun.com/javase/6/docs/api/javax/swing/JOptionPane.html], do you find a variant of this method that accepts these three parameters?
db

Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
You are passing 3 parameters -- a null, a String and an int -- to the JOptionPane#showMessageDialog method. In the [_API_|http://java.sun.com/javase/6/docs/api/javax/swing/JOptionPane.html], do you find a variant of this method that accepts these three parameters?
db

  • Output problem urgent!!

    Okay so heres the problem i have a piece of code to convert a decimal value that a user enters into a binary value. My algorithm works its just when the binary value is displayed only the last element of the binary value to be outputed is displayed. But i want all the values of the binary number to be displayed. I dont know what to do plz help.
    the code i am using is:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import javax.swing.*;
    public class conversion extends JPanel implements ActionListener
         JPanel board;                // Panel for buttons
         JLabel canvas;               // Text Area for displaying answer
        JButton convert, reset;  // buttons
           JTextField input;       //input text box
             public conversion()
                 super(true); // Call constructor of parent
              // Standard layout (flow)
                 setLayout(new FlowLayout());
              // Set up two panels, control board and canvas
                 board = new JPanel(true);
              canvas = new JLabel();
                 board.setPreferredSize(new Dimension(100, 100));
                 canvas.setPreferredSize(new Dimension(300, 300));
              board.setBorder(BorderFactory.createLineBorder(Color.black));
              canvas.setBorder(BorderFactory.createLineBorder(Color.blue));
              // Create buttons and attach listeners
                 convert = new JButton("Convert");
                 convert.addActionListener(this);
                 reset = new JButton("Reset");
                 reset.addActionListener(this);
              input = new JTextField(8);
                 add(canvas); add(board);
              // Add button to board panel
            board.add(convert);
              board.add(input);
              board.add(reset);
         public void actionPerformed(ActionEvent e)
              String inputInfo;
              inputInfo = input.getText();
              if (e.getSource() == convert){           //action on convert button
               //algorithm for decimal to binary conversion
              int a = Integer.parseInt(inputInfo);    //Gets decimal number inputed
              if (a > 255){
                   canvas.setText("Please enter a number below 256");
              else {
              int b[] = new int[50];
              int i = 0;
              if (a / 2!=0 || a==1)               //Checks to see if decimal number is divisible by 2
              {                                             //Or exactly equal to 1
              while(a!= 1)                            //While loop for when the decimal inputted is not equal to 1
              b= a % 2;                              
              a = a / 2;                                   //Check to see if the remainder is divisible by 2
              i++;
              b[i]= 1;
              for(int x=i;x>=0;x--)
                                                      //Displays the binary answer
                   int answer = b[x];
                   String stringAns = Integer.toString(b[x]);     
                   System.out.println(stringAns);
                   canvas.setText ("The binary for your decimal is: " + stringAns); // this is the problem here, only the last element is displayed
              if (e.getSource() == reset){           //action on reset button
                   canvas.setText("");     
                   input.setText("");
              //Graphics g = canvas.getGraphics();}
         public static void main(String[] args)
         // Create a Blob entity
         conversion b = new conversion();
              // Set up outer frame, and its exit behaviour
         JFrame frame = new JFrame("Decimal to binary");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Set the main content frame to be the Blob,
              // size the frame (pack) and make it visible
         frame.setContentPane(b);
         frame.pack();
         frame.setVisible(true);

    pauze wrote:
              for(int x=i;x>=0;x--)
                                                      //Displays the binary answer
                   int answer = b[x];
                   String stringAns = Integer.toString(b[x]);     
                   System.out.println(stringAns);
                   canvas.setText ("The binary for your decimal is: " + stringAns);        // this is the problem here, only the last element is displayed
    Each element in the array b contains one digit of the binary representation. You need to convert each digit into a character and then concatenate all the characters into a String before displaying anything.

  • JOptionPane event blocking problem

    Hi,
    JOptionPane is causing me a problem.
    I have a simple frame that contains a text field and a button.
    Pressing the button should write something to the standard output.
    When the text field loses focus a JOptionPane in poped to the user.
    The following scenario is problematic:
    1. The text field owns the focus.
    2. The user presses the button.
    Expected result:
    The JOptionPane appears due to the lost focus event on the text field.
    After closing it some text is written to the standard output due to the action event on the button.
    The actual result:
    The JOptionPane does appears but after closing it nothing is written to the standard output. The button stays in a curious state (when the mouse hovers over the button the button looks pressed, and when the mouse doesn't hover over the button the button looks unpressed).
    Probable reason for this behaviour:
    The JOptionPane blocks all awt/swing events while it is opened. Some of the button code is perfomed due to the button press, but the ActionListener's actionPerformed method is not invoked.
    I need the actionPerfomed method to be invoked.
    Can anyone help me?
    Here is the source code:
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test {
    public Test() {
    public static void main(String[] args) {
    //Test test1 = new Test();
    final JFrame f = new JFrame("Test");
    JButton b = new JButton("Click Here");
    JTextField tField = new JTextField("Text", 10);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println("Button pressed!");
    tField.addFocusListener(new FocusAdapter() {
    public void focusLost(FocusEvent e) {
    if (e.isTemporary()) return;
    JOptionPane.showMessageDialog(f,
    "Focus lost",
    "Title",
    JOptionPane.INFORMATION_MESSAGE);
    JPanel content = (JPanel)f.getContentPane();
    content.setLayout(new BoxLayout(content, BoxLayout.X_AXIS));
    content.add(tField);
    content.add(Box.createHorizontalStrut(5));
    content.add(b);
    f.pack();
    f.show();
    Thanks,
    Shai

    Hello Shai.
    The JOptionPane seems to consume all events when its shown. (Check the stack after JOptionPane is shown.) I've solved a similar problem with the SwingUtilities.invokeLater() method. Maybe the following example will help:
    Runnable doDlgError = new Runnable() {
    public void run() {
    JOptionPane.showMessageDialog(this, "Error", "Error",
    JOptionPane.ERROR_MESSAGE);
    SwingUtilities.invokeLater(doDlgError);
    -Olaf

  • Maybe you are looking for

    • How do I archive iDVD project? Best/Smallest size?

      Hi, I need to know the best method to save a movie project that was made in imovie, then burned to DVD using iDVD. I want to save a copy of the finished product for archival purposes on an external drive. I want to be able to pull up this archive and

    • Download using GUI_download

      Hi all, i am trying to download the internal table which have 10 field, into the EXCEL file, at the same time i wanted into the downloaded file field name also appear....how can we do that,, while downloading its appearing in a one column, i want to

    • I can't open itunes after installation, says"itunes.exe-application error"

      first time, I installed ipod and itunes from the cd, it failed. then I downloaded from the website and reinstalled, it didn't work, either. afterward I have tried many times to delete,restart and reinstall, it just didn't work at all>_< every time i

    • Strange entries in lighttpd access log -- help!

      Hi, I run a lighttpd server at home. I just use it for working with some scripts, and sharing stuff with my friends. I have a dynamic IP address, so I use dyndns for getting a hostname. Today I noticed some strange entries in the lighttpd access log:

    • Extract Data from a Blob field

      I have a BLOB type field in a Table. Now I would like to have a Pl/Sql code or C code which could read the data in the BLOB field which is in XML format. Actually the data in the BLOB a record and I would like to take only required data from the BLOB