Need help with threading in Swing GUI !!!

I've written an app that parses and writes
files. I'm using a Swing GUI. The app
could potenially be used to parse hundreds or even
thousands of files. I've included a JProgressBar
to monitor progress. The problem is when I parse
a large number of files the GUI freezes and only
updates the values of the progress bar when the
parsing and writing process is finished.
I assume I need to start the process in a seperate thread. But, I'm new to threads and I'm not sure
whether to start the Progressbar code in a seperate
thread or the parsing code. As a matter of fact I really
don't have any idea how to go about this.
I read that Swing requires repaints be done in the
event dispatch thread. If I start the parsing in a seperate
thread how do I update the progressbar from the other
thread? I'm a thread neophyte.
I need a cigarette.

In other words do this:
Inside event Thread:
handle button action
start thread
return from action listener
Inside worker Thread:
lock interface
loop
perform action
update progress bar
unlock interface
return from worker ThreadDoesn't updating the progress bar (and locking/unlocking the interface components) from within the worker thread violate the rule that you shouldn't mess with Swing components outside the event thread? (Do I have that rule right?)
In any case, is there any way to just post some kind of event to the progress bar to update it from within the worker thread, thereby insuring that the GUI progress bar update is being invoked from the event thread? This would also obviate the need to use a timer to poll for an update, which I think is a waste especially when the monitored progress is at a variable rate, (or for number crunching, is executing on different speed machines).
Also, doesn't using invokeLater() or invokeAndWait() still block the event dispatching thread? I don't understand how having a chunk of code started in the event thread doesn't block the event thread unless the code's executed in a "sub-thread", which would then make it not in the event thread.
I'm also looking to have a progress bar updated to monitor a worker thread, but also want to include a "Stop" button, etc. and need the event queue not to be blocked.
The last thing I can think of is to implement some kind of original event-listener class that listens to events that I define, then register it with the system event queue somehow, then have the worker thread post events to this listener which then calls setValue() in the progress bar to insure that the bar is updated from the event queue and when I want it to be updated. I don't know yet if it's possible to create and register these kinds of classes (I'm guessing it is).
Thanks,
Derek

Similar Messages

  • Need help with threads?.. please check my approach!!

    Hello frnds,
    I am trying to write a program.. who monitors my external tool.. please check my way of doing it.. as whenever i write programs having thread.. i end up goosy.. :(
    first let me tell.. what I want from program.. I have to start an external tool.. on separate thread.. (as it takes some time).. then it takes some arguments(3 arguments).. from file.. so i read the file.. and have to run tool.. continously.. until there are arguments left.. in file.. or.. user has stopped it by pressing STOP button..
    I have to put a marker in file too.. so that.. if program started again.. file is read from marker postion.. !!
    Hope I make clear.. what am trying to do!!
    My approach is like..
    1. Have two buttons.. START and STOP on Frame..
    START--> pressed
    2. check marker("$" sign.. placed in beginning of file during start).. on file..
         read File from marker.. got 3 arg.. pass it to tool.. and run it.. (on separate thread).. put marker.. (for next reading)
         Step 2.. continously..
    3. STOP--> pressed
         until last thread.. stops.. keep running the tool.. and when last thread stops.. stop reading any more arguments..
    Question is:
    1. Should i read file again and again.. ?.. or read it once after "$" sign.. store data in array.. and once stopped pressed.. read file again.. and put marker ("$" sign) at last read line..
    2. how should i know when my thread has stopped.. so I start tool again??.. am totally confused.. !!
    please modify my approach.. if u find anything odd..
    Thanks a lot in advance
    gervini

    Hello,
    I have no experience with threads or with having more than run "program" in a single java file. All my java files have the same structure. This master.java looks something like this:
    ---master.java---------------------------------------------------
    import java.sql.*;
    import...
    public class Master {
    public static void main(String args []) throws SQLException, IOException {
    //create connection pool here
    while (true) { // start loop here (each loop takes about five minutes)
    // set values of variables
    // select a slave process to run (from a list of slave programs)
    execute selected slave program
    // check for loop exit value
    } // end while loop
    System.out.println("Program Complete");
    } catch (Exception e) {
    System.out.println("Error: " + e);
    } finally {
    if (rSet1 != null)
    try { rSet1.close(); } catch( SQLException ignore ) { /* ignored */ }
    connection.close();
    -------end master.java--------------------------------------------------------
    This master.java program will run continuously for days or weeks, each time through the loop starting another slave process which runs for five minutes to up to an hour, which means there may be ten to twenty of these slave processes running simultaneously.
    I believe threads is the best way to do this, but I don't know where to locate these slave programs: either inside the master.java program or separate slave.java files? I will need help with either method.
    Your help is greatly appreciated. Thank you.
    Logan

  • Need help with Threading GUI progress bar

    Anyone able to help? I'm sure you've seen this a million times. I've google'd around and tried examples but still can't get a progress bar to work properly under the following situation:
    1. Created a panel with several components to select directory, display directory in tree etc.
    2. When a specific button (Search) is clicked, I want a secondary window to popup and report progress of searching down the directory.
    As you'll probably guess, the progress window isn't being updated until the end. I'm using Threads and using InvokeLater but nothing happens. Is there any good example that does the above? I can't seem to find one to figure this out.
    Thanks
    Speedy.
    Sample code:
    main.java:
    ========
    public class Main {
    public static void main(String[] args) {
    MainPanel mainPanel = new MainPanel();
    mainPanel.show();
    MainPanel.java:
    ============
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class MainPanel extends JFrame implements ActionListener {
    public MainPanel() {
    this.setSize(100,100);
    JButton startButton = new JButton("Start");
    this.getContentPane().add(startButton);
    startButton.addActionListener(this);
    public void actionPerformed(ActionEvent event) {
    ProgressPanel pp = new ProgressPanel();
    pp.show();
    SimpleTask st = new SimpleTask(pp);
    st.start();
    while (st.isAlive()) {
    System.err.println("waiting..");
    try {
    Thread.sleep(100);
    } catch (Exception e) {};
    System.err.println("finished!");
    SimpleTask.java:
    =============
    import javax.swing.SwingUtilities;
    public class SimpleTask extends Thread {
    ProgressPanel pp = null;
    public SimpleTask(ProgressPanel _pp) {
    pp = _pp;
    this.setDaemon(true);
    int i = 0;
    String position = "";
    public void run() {
    Runnable updateGUI = new Runnable() {
    public void run() {
    pp.setText(position);
    try {
    for (i=0; i<50; i++) {
    position = "Now on = " + new Integer(i).toString();
    System.err.println(position);
    SwingUtilities.invokeLater(updateGUI);
    sleep(100);
    } catch (Exception e) {}
    ProgressPanel.java:
    ===============
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class ProgressPanel extends JFrame {
    private JLabel label = new JLabel();
    public ProgressPanel() {
    this.setSize(200,200);
    this.setLocation(100,100);
    this.getContentPane().add(label);
    setText("Start");
    public void setText(String text) {
    label.setText(text);
    }

    Ok, I'll look down that road. I should have said the Thread is being used because the current while loop will be changed to perform real work. Just an example at the moment to show what I'm trying to do. Does this make a difference? The real task will be to drill down directories, counting file types/dirs etc...

  • Need help with integrating chat into Gui

    Hello Guys,
    I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class Client
    extends JPanel {
    public static void main(String[] args) throws IOException {
    String name = args[0];
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    final Socket s = new Socket(host, port);
    final Client c = new Client(name, s);
    JFrame f = new JFrame("Client : " + name);
    f.addWindowListener(new WindowAdapter() { 
    public void windowClosing(WindowEvent we) { 
    c.shutDown();
    System.exit(0);
    f.setSize(300, 300);
    f.setLocation(100, 100);
    f.setContentPane(c);
    f.setVisible(true);
    private String mName;
    private JTextArea mOutputArea;
    private JTextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new JTextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new JTextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");

    I think the easiest way to do it would be to cut an paste most of that code into your program. Then all you have to do is change some names so that it uses your textfield and textarea.

  • Creating breakout game. Need help with thread starting.

    Howdy. As the title says, I've got an assignment to make a breakout game. So far it's going alright, but I've run into a rather large snag...I can't get it to animate :P I've got my main applet, then I created a class heirarchy for the paddle, ball, and brick objects. For this question, lets just focus on the ball object.
    This is my applet code so far (it is not even close to being done, so don't laugh :P )
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    * Class BreakoutApplet - Plays a simple game of Breakout.
    * @author Kris Nelson
    * @version November 10, 2004
    public class BreakoutApplet extends JApplet implements Runnable
        protected Brick brick; // creates an object of class brick
        protected Ball ball; // creates an object of class ball
        protected Paddle paddle; // creates an object of class paddle
        protected boolean running; // tells the program whether or not the thread is running
        protected ArrayList brickArray = new ArrayList(); // stores all the bricks in the game
        protected Thread timer; // the thread which controls the animation for the applet
        * Called by the browser or applet viewer to inform this JApplet that it
        * has been loaded into the system. It is always called before the first
        * time that the start method is called.
        public void init()
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
            createBricks(); // creates the games array of bricks
            ball = new Ball(400, 400, 2, 2); // sets the values for the ball
            paddle = new Paddle(300, 660, 2); // sets the values for the paddle
            // !!!!!!! have tried placing ball.start() here
        * Paint method for applet.
        * @param  g   the Graphics object for this applet
        public void paint(Graphics g)
            // draws the background, border, and all the games objects
            g.setColor(Color.lightGray); // sets the drawing color to light gray
            g.fillRect(0, 0, 600, 700); // displays the game screens background
            displayBorder(g); // displays the game screens border
            displayBricks(g); // displays the array of bricks
            ball.display(g); // displays the ball
            paddle.display(g); // displays the paddle
        * Creates the games array of bricks
        public void createBricks()
            int colorNumber = 1; // starts the color of the bricks at orange
            double yPosition = 100; // starts the bricks y screen position at 100
            for(int i = 0; i < 4; i++)
                double xPosition = 12; // starts the bricks x screen position at 12
                for(int j = 0; j < 8; j++)
                    if(colorNumber == 0)
                        colorNumber = 1; // sets the color of the bricks to orange
                    else
                        colorNumber = 0; // sets the color of the bricks to green
                    brickArray.add(brick = new Brick(xPosition, yPosition, colorNumber)); // adds a brick to the current container in the brick array
                    xPosition = xPosition + brick.getWidth(); // move the bricks x screen position to the next column
                yPosition = yPosition + brick.getHeight(); // moves the bricks y screen position to the next row
                if(colorNumber == 0)
                    colorNumber = 1; // sets the color of the bricks to orange
                else
                    colorNumber = 0; // sets the color of the bricks to green
        * Displays the game screens border
        * @param  g   the Graphics object for this applet
        public void displayBorder(Graphics g)
            g.setColor(Color.black); // sets the drawing color to black
            g.fillRect(0, 0, 600, 24); // draws a border on the top of the screen
            g.fillRect(0, 0, 12, 700); // draws a border on the left of the screen
            g.fillRect(588, 0, 12, 700); // draws a border on the right of the screen
        * Displays the array of bricks on the screen
        * @param  g   the Graphics object for this applet
        public void displayBricks(Graphics g)
            Brick currentBrick; // holds the brick data from the current ArrayList container
            for(int i = 0; i < 32; i++)
                currentBrick = (Brick)(brickArray.get(i)); // grabs the brick data from the current ArrayList container
                currentBrick.display(g); // displays the current brick
        * Called by the browser or applet viewer to inform this JApplet that it
        * should start its execution. It is called after the init method and
        * each time the JApplet is revisited in a Web page.
         public void start()
             if(timer == null)
                 timer = new Thread(this); // creates a new object of type Thread
                 timer.start(); // starts the new thread
                 running = true; // tells the program that the new thread is running
        * Runs the code that controls the animation
        public void run()
            do{
                repaint(); // redraws the screen
                try{
                    timer.sleep(100); // puts the thread to sleep for 100 milliseconds
                } catch(InterruptedException e) {running = false;}
                // !!!!!!! have tried placing ball.start() here
            } while(running);
            timer = null; // destroys the timer thread
        * Called by the browser or applet viewer to inform this JApplet that
        * it should stop its execution. It is called when the Web page that
        * contains this JApplet has been replaced by another page, and also
        * just before the JApplet is to be destroyed.
        public void stop()
            running = false; // tells the program that the thread is now done
    }These are the bits of code for my class heirarchy, just to (hopefully) make it easier to follow.
    import java.awt.*;
    * The parent class of all the games objects.
    * @author Kris Nelson
    * @version November 9, 2004
    public class Sprite
        protected double screenX, screenY; // stores the x and y location of the object
        * Constructor for objects of class Sprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        public Sprite(double xPosition, double yPosition)
            screenX = xPosition; // sets the initial x screen position
            screenY = yPosition; // sets the initial y screen position
        * Sets new x and y screen locations for an object
        * @param  newX   the new x screen location
        * @param  newY   the new y screen location
        public void setScreenXY(double newX, double newY)
            screenX = newX; // sets the new x screen location
            screenY = newY; // sets the new y screen location
        * Sends back the current x screen location
        * @return     the current x screen location
        public double getScreenX()
            return screenX; // returns the current x screen location
        * Sends back the current y screen location
        * @return     the current y screen location
        public double getScreenY()
            return screenY; // returns the current y screen location
    import java.awt.*;
    * Parent class of any game object that moves.
    * @author Kris Nelson
    * @version November 9, 2004
    public class MovingSprite extends Sprite implements Runnable
         protected double speedX, speedY; // stores the speed of an object in the x and y directions
         protected Thread timer; // the thread which controls animation for all moving objects
         protected boolean running; // tells the program whether or not the thread is running
         * Constructor for objects of class MovingSprite
         * @param  xPosition   the initial x screen position
         * @param  yPosition   the initial y screen position
         * @param  xSpeedValue   the speed in the x direction
         * @param  ySpeedValue   the speed in the y direction
         public MovingSprite(double xPosition, double yPosition, double xSpeedValue, double ySpeedValue)
              super(xPosition, yPosition); // passes the initial screen positions to Sprite
              speedX = xSpeedValue; // sets the speed in the x direction
              speedY = ySpeedValue; // sets the speed in the y direction
         * Sends back the speed in the x direction
         * @return     the speed in the x direction
         public double getSpeedX()
             return speedX; // returns the speed in the x direction
         * Sends back the speed in the y direction
         * @return     the speed in the y direction
         public double getSpeedY()
             return speedY; // returns the speed in the y direction
         * Starts the thread in order to start animation
         public void start()
             if(timer == null)
                 timer = new Thread(this); // creates a new object of type Thread
                 timer.start(); // starts the new thread
                 running = true; // tells the program that the new thread is running
         * Empty since the child objects have their own run methods
         public void run()
         * Stops the thread from running
         public void stop()
             running = false; // tells the program that the thread is now done
    import java.awt.*;
    * Creates a single ball who's purpose is to bounce around and destroy the bricks.
    * @author Kris Nelson
    * @version November 10, 2004
    public class Ball extends MovingSprite
        protected static final double BALL_WIDTH = 15; // sets the width of the ball
        protected static final double BALL_HEIGHT = 15; // sets the height of the ball
        * Constructor for objects of class Ball
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public Ball(double xPosition, double yPosition, double xSpeedValue, double ySpeedValue)
            super(xPosition, yPosition, xSpeedValue, ySpeedValue); // passes the initial screen positions and ball speeds to MovingSprite
            // !!!!!!!! have tried placing timer.start() here
        * Displays a ball onto the screen
        * @param  g   the Graphics object for this applet
        public void display(Graphics g)
            g.setColor(Color.blue); // sets the balls color
            g.fillOval((int)(screenX), (int)(screenY), (int)(BALL_WIDTH), (int)(BALL_HEIGHT)); // displays the ball
        * Runs the code that controls the balls animation
        public void run()
            do{
                try{
                    timer.sleep(100); // puts the thread to sleep for 100 milliseconds
                } catch(InterruptedException e) {running = false;}
                screenX = screenX + speedX;
                screenY = screenY + speedY;  // this is VERY SIMPLE BALL MOVEMENT FOR TESTING PURPOSES, WILL BE CHANGED LATER
            } while(running);
    }Sorry if that was too much code. I'm just trying to make this easier to follow.
    I placed a // !!!!!!!!!!!!! comment in the places where I have tried starting the ball thread.
    So basically, everything is running fine, except that I'm not at all sure of where to start the ball Thread, and thus can't start anything moving. If someone could tell me where I should be starting the thread, I would REALLY appriciate it. Thank you :D
    - Kris

    Some advice.
    1. the start method on the ball should be called from the start method on the applet and should in turn call the start method on the sprite's thread.
    2. the run method of the Moveable sprite should have been declare abstract
    3. don't implement borders manually. There's a java.awt.Border class for that.
    4. probably, you don't want to have the game invoke each sprite by name; just make a big list of all the sprites and invoke all of them every time
    5. do you really need provision for a non-circular ball? this isn't rugby.
    6. I don't think you ever had a threading problem, just a display problem.
    7. Don't write comments like this:     ball.display(g); // displays the ballHere's my (even more simplified version):import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    * Class BreakoutApplet - Plays a simple game of Breakout.
    * @author Kris Nelson, modified by Michael Lorton
    * @version November 10, 2004
    public class BreakoutApplet extends JApplet implements Runnable {  
        protected Ball ball;
        protected Paddle paddle;
        public boolean running; // tells the program whether or not the thread is running
        protected Thread timer; // the thread which controls the animation for the applet
        public void init() {
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            getRootPane().putClientProperty("defeatSystemEventQueueCheck",
                                            Boolean.TRUE);
             ball = new Ball(this, GAMEWIDTH / 2, GAMEHEIGHT / 2, 5, 5);
        public final static int GAMEWIDTH = 600;
        public final static int GAMEHEIGHT = 400;
        public void paint(Graphics g) {
            g.setColor(Color.lightGray);
            g.fillRect(0, 0,
                       GAMEWIDTH, GAMEHEIGHT);
            ball.display(g); // displays the ball
        * Called by the browser or applet viewer to inform this JApplet that it
        * should start its execution. It is called after the init method and
        * each time the JApplet is revisited in a Web page.
        public void start() {
            if(timer == null) {
                timer = new Thread(this); // creates a new object of type Thread
                timer.start(); // starts the new thread
                running = true; // tells the program that the new thread is running
            ball.start();
        * Runs the code that controls the animation
        public void run() {
            do{
                repaint(); // redraws the screen
                try{
                    Thread.sleep(100);
                } catch(InterruptedException e) {running = false;}
            } while(running);
        public void stop() {
            running = false;
    abstract class Sprite {
        protected double screenX, screenY; // stores the x and y location of the object
        protected final BreakoutApplet parent;
        * Constructor for objects of class Sprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        public Sprite(BreakoutApplet parent, double xPosition, double yPosition) {
            this.parent = parent;
            screenX = xPosition; // sets the initial x screen position
            screenY = yPosition; // sets the initial y screen position
        * Sets new x and y screen locations for an object
        * @param  newX   the new x screen location
        * @param  newY   the new y screen location
        public void setScreenXY(double newX, double newY) {
            screenX = newX; // sets the new x screen location
            screenY = newY; // sets the new y screen location
        * Sends back the current x screen location
        * @return     the current x screen location
        public double getScreenX() {
            return screenX; // returns the current x screen location
        * Sends back the current y screen location
        * @return     the current y screen location
        public double getScreenY() {
            return screenY; // returns the current y screen location
        abstract public void display(Graphics g);
    * Parent class of any game object that moves.
    * @author Kris Nelson
    * @version November 9, 2004
    abstract class MovingSprite extends Sprite implements Runnable {
        protected double speedX, speedY; // stores the speed of an object in the x and y directions
        protected Thread timer; // the thread which controls animation for all moving objects
        protected boolean running; // tells the program whether or not the thread is running
        * Constructor for objects of class MovingSprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public MovingSprite(BreakoutApplet parent,
                            double xPosition, double yPosition,
                            double xSpeedValue, double ySpeedValue) {
            super(parent, xPosition, yPosition);
            speedX = xSpeedValue; // sets the speed in the x direction
            speedY = ySpeedValue; // sets the speed in the y direction
        * Starts the thread in order to start animation
        public void start() {
            if(timer == null) {
                timer = new Thread(this); // creates a new object of type Thread
                timer.start(); // starts the new thread
                running = true; // tells the program that the new thread is running
        * Runs the code that controls the balls animation
        public void run() {
            while (parent.running) {
                try{
                    Thread.sleep(100);
                } catch(InterruptedException e) {
                    System.err.println(e);
                step();
        abstract protected void step();
    * Creates a single ball whose purpose is to bounce around and destroy the bricks.
    * @author Kris Nelson
    * @version November 10, 2004
    class Ball extends MovingSprite {
        protected static final int BALL_DIAMETER = 15;
        * Constructor for objects of class Ball
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public Ball(BreakoutApplet parent,
                    double xPosition, double yPosition,
                    double xSpeedValue, double ySpeedValue) {
            super(parent, xPosition, yPosition, xSpeedValue, ySpeedValue);
        * Displays a ball onto the screen
        * @param  g   the Graphics object for this applet
        public void display(Graphics g) {
            g.setColor(Color.blue);
            g.fillOval((int)(screenX),
                       (int)(screenY),
                       BALL_DIAMETER, BALL_DIAMETER);
        protected void step() {
                screenX = screenX + speedX;
                if (screenX < 0) {
                    screenX = -screenX;
                    speedX = -speedX;
                else if ((screenX + BALL_DIAMETER)> BreakoutApplet.GAMEWIDTH) {
                    screenX = 2*(BreakoutApplet.GAMEWIDTH  - BALL_DIAMETER) - screenX;
                    speedX = -speedX;
                screenY = screenY + speedY;
                if (screenY < 0) {
                    screenY = -screenY;
                    speedY = -speedY;
                else if ((screenY  + BALL_DIAMETER) > BreakoutApplet.GAMEHEIGHT) {
                    screenY = 2*(BreakoutApplet.GAMEHEIGHT - BALL_DIAMETER) - screenY;
                    speedY = -speedY;
    }

  • Need help with  HTML and Swing Components

    Dear All,
    I am using HTML text for Jbutton and Jlabel and MenuItem.
    But when i am trying to disable any of these, its foreground color is not being grayed out.
    For that, I have overrided the setEnable() method as mentioned below:
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.*;
    import javax.swing.plaf.FontUIResource;
    * HtmlLabelEx.java
    public class HtmlLabelEx extends javax.swing.JDialog implements MouseListener{
         * Creates new form HtmlLabelEx
        public HtmlLabelEx(java.awt.Frame parent, boolean modal) {
            super(parent, modal);
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            initComponents();
            setLayout(null);
            this.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent event)
                    System.exit(0);
            JLabel jLabel1 = new JLabel()
                public void setEnabled(boolean b)
                  super.setEnabled(b);
                  setForeground(b ? (Color) UIManager.get("Label.foreground") : (Color) UIManager.get("Label.disabledForeground"));
            JButton jButton1 = new JButton()
                public void setEnabled(boolean b)
                  super.setEnabled(b);
                  setForeground(b ? (Color) UIManager.get("Label.foreground") : (Color) UIManager.get("Label.disabledForeground"));
            add(jButton1);
            String str = "<html><body><b>Label</b></body></html>";
            System.out.println("str = "+str);
        jLabel1.setText(str);
        add(jLabel1);
        jLabel1.setBounds(10,10,100,20);
        jLabel1.setEnabled(false);
        jButton1.setText("<html><body><b>Button</b></body></html>");
        jButton1.setEnabled(true);
        jButton1.setBounds(10,50,100,20);
        System.out.println("getText = "+jLabel1.getText());
        setSize(400,400);
        addMouseListener(this);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            getContentPane().setLayout(null);
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new HtmlLabelEx(new javax.swing.JFrame(), true).setVisible(true);
        // Variables declaration - do not modify                    
        // End of variables declaration                  
        public void mouseClicked(MouseEvent e)
            if(e.getButton() == e.BUTTON3)
                JMenuItem mit = new JMenuItem("<html><body><b>Menu Item</b></body></html>");
                JPopupMenu pop = new JPopupMenu();
                pop.add(mit);
                mit.setEnabled(false);
                pop.show(this,e.getX(),e.getY());
        public void mousePressed(MouseEvent e) {
        public void mouseReleased(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
    But, I think it is difficult to write like this for each component.
    I am looking for an optimized solution so that the change will be only in one place.
    so that, It wont leads to change so many pages or so many places.
    And i have the following assumptions to do this. please let me know the possibility.
    1.Implementing custom UI class, extending the JButton/JMenuItem (As the BasicButton/MenuItemUI class does not have setEnabled() method to override) and putting this in UIManager.put("ButtonUI/MenuItemUI","CustomClass).
    2.If there is any possibility to achieve this, by just overriting any key in the UIManager
    3.By setting any client property globally.
    My requirement is to do this only at one place for entire the application.So, that we need not change all the buttoins, sya some 30 buttions are there in a dialog, then we need to override each button class.
    Please suggest me the possibilties..
    Thank you

    Hi camickr ,
    I know that to set the font we have to use component.setfont().
    But, as per my requirement,i am not setting any font to any component in my application.
    i am just passing HTML text along with FONT tags to all the components in my Application.SO, in this case we will get bold letters and that problem fixed when we set swing.boldMetal = false in UI Manager.
    But actual problem irrespective of font settings is when ever we use HTML rendered text, when the button or menuitem is disabled,then that one will not be changed to gray color. i.e., it still looks like normal controls, even it is disabled.(It is also reported as bug)
    But, as per my knowledge we can fix by overrding setEnabled or paint() methods for each and every component.
    But, if we do like that, for an application that has 200 buttons or MenuItems, it is difficult to follow that approach.
    So, We should find a way to achieve that only in one place like using UIManager or other one as i mentioned in previous posts if possible.
    I hope you understood what my problem is exactly.
    Thank You
    Edited by: sindhumourya on Mar 4, 2010 7:26 AM

  • I need help with random number in GUI

    hello
    i have home work about the random number with gui. and i hope that you can help me doin this application. and thank you very much
    Q1)
    Write an application that generates random numbers. The application consists of one JFrame,
    with two text fields (see the figures) and a button. When the user clicks on the button, the
    program should generate a random number between the minimum and the maximum numbers
    entered in the text fields. The font of the number should be in red, size 100, bold and italic.
    Moreover, if the user clicks on the generated number (or around it), the color of the background
    should be changed to another random color. The possible colors are red, green blue , black ,cyan
    and gray.
    Notes:
    �&#61472;The JFrame size is 40 by 200
    �&#61472;The text fields size is 10
    this is a sample how should the programe look like.
    http://img235.imageshack.us/img235/9680/outputgo3.jpg
    Message was edited by:
    jave_cool

    see java.util.Random

  • Help with Threads

    I need help with threads. How can I break this code into teo threads without chaning the data objects at all? Producer will produce string line by line and consumer will take the line and search for the word. Help me please.
    Thank you
    public class WordFinder
    * Main program opens the file given by the user as an argument and
    * searches for the word given by the user. If the word is found,
    * the line number on which the word occurs is displayed.
    * @param args[0] Word to search for
    * @param args[1] Name of file to search
    public static void main(String[] args) throws IOException
    // To keep track of how long the program runs we'll set the startTime
    // variable to the current time in milliseconds and use that at
    // the end of the program to find out how long we ran.
    long startTime = System.currentTimeMillis();
    String wordToFind;
    String currentLine;
    int lineCount = 0; // Keep track of line numbers
    BufferedReader inputFile = null; // Needed to get compiler to quit
    // complaining about uninitialized
    // variables.
    // Make sure we have 2 arguments passed to us
    if (args.length < 2)
    // Nope. Show user how to run and then exit with an error (1)
    System.out.println("usage: java WordFinder <word> <file pathname>");
    System.exit(1);
    // So far, so good. Now try to open the file the user gave us as
    // a parameter. We'll use a BufferedReader object to read the file
    // so we can read one line at a time from the input. If opening the
    // file fails, print an error message and exit with an error (1).
    try
    inputFile = new BufferedReader(new FileReader(args[1]));
    catch (FileNotFoundException e)
    System.out.println(args[1] + ": File not found or is not readable");
    System.exit(1);
    // Set the wordToFind variable to refer to args[0]. We don't
    // really need to do this, but it makes our code more readable
    wordToFind = args[0];
    // We're going to read the file one line at a time. For each
    // line, we'll create a StringTokenizer object to break the line
    // into distinct words, checking each word to see if it's the same
    // as the given search word.
    // Read first line from the file
    currentLine = inputFile.readLine();
    while (currentLine != null) // Repeat until we reach EOF
    // Have a valid input line, increment the counter
    lineCount++;
    // Create a StringTokenizer object over the current line
    StringTokenizer tokens = new StringTokenizer(currentLine);
    // Check each word in the string by accessing each token
    while (tokens.hasMoreTokens())
    // See if the next word is the one we're looking for and
    // advance the token iterator to the next token
    if (wordToFind.equals(tokens.nextToken()))
    // Yes, display the current line number
    System.out.println(wordToFind + " found on line " + lineCount);
    // Read next line from the file
    currentLine = inputFile.readLine();
    } // while
    // Done with the input file
    inputFile.close();
    // Display the running time of this program in milliseconds by
    // subtracting the start time from the current time
    System.out.println((System.currentTimeMillis() - startTime) + " milliseconds");
    } // main
    } // WordFinder

    You may create Queue object. (I guess that you're already know QUEUE)
    Then ... use producer thread to load input file into queue. (Enqueue)
    Consumer ... dequeue
    Queue can be empty because of
    - Input file was read to EOF and Consumer had produced all queue.
    or
    - Cunsumer works too fast... So the queue is empty.
    So, you may have to use ... wait() in Consumer in case of the queue is empty.
    And use notify() in Producer to wake up consumer ...
    Is this right ?

  • I need Help with loop

    Hello everyone this is my first time posting here, i have always find java easy(up to this point), this is my first class in programming java i am just needing help with the "for loops" i cant seem to get the program generate 10 random math questions. if you guys can please help i will appreciate it, i have been working on it for a couple of hours. I am not finished with it yet but thats the only thing i need help with.
    import javax.swing.JOptionPane;
    public class Lab5
    public static void main(String[] args)
    int num1 = (int) (Math.random() * 100 + 1);
    int num2 = (int) (Math.random() * 100 + 1);
    int sum = num1 + num2;
    int product = num1 * num2;
    int quotient = num1 / num2;
    int difference = num1 - num2;
    for (int i = 0; i > 11; i++);
    int number = (int)(Math.random()*4);
    if (number == 0 )
    String s1 = JOptionPane.showInputDialog(null, num1 + " + " + num2 + "=" );
    if(number == 1)
    String s3 = JOptionPane.showInputDialog(null, num1 + " - " + num2 + "=" );
    if(number == 2)
    String s3 = JOptionPane.showInputDialog(null, num1 + " x " + num2 + "=" );
    if(number == 3)
    String s4 = JOptionPane.showInputDialog(null, num1 + " &divide; " + num2 + "=" );

    for (int i = 0; i > 11; i++);Two problems with this line:
    1) The second part of a For loop is the constraint. You have said that for the loop to be entered, i must be greater than 11. Well since you've also told i to begin at 0, this will never happen. Thus, the loop will never enter. You may have meant less than?
    2) You put a semicolon in the line. Semicolons are used to end statements. The For loop, when used as a block with curly braces, is not a single statement and does not require a semicolon. Here's the two structures of a basic For loop:
    for(int i = 0; i <= 100; i++) {
        //this is a block. you can put multiple statements in here and they are all part of the loop
        int a = 1;
        int b = i;
    //if your loop only needs to use a single statement, no braces are required
    for(int i = 0; i <= 100; i++)
        int a = i;

  • Need help!!!! GUI problems with netbeans

    i have a problem with the interface i created using netbeans.
    i created a JFrame, inside it a JDesktopPane, and inside that 3 JInternalFrames. the problem is in one of the JinternalFrames, i have 4 radio buttons which i forgot to add to a buttongroup and whenever i try to do that, the GUI doesn't work anymore. The bigger problem is that if i undo the changes, the thing still doesn't work and i have to copy my backup project folder over the one i work on to get an output.
    i tried to edit the source code to add the 4 buttons to a button group but netbeans won't let me since i created the buttons thru it not by writing it myself
    please i really need help with this and i hope its a stupid thing i'm just overlooking.
    If u need the code, i will gladly post it.
    thanks in advance

    if you're not using a netbeans-specific layout manager, copy the working code
    into notepad, make the changes, then compile and run from the command prompt.
    if all works OK, dump netbeans

  • Help with a very basic GUI

    Hi guys, i have a project to do and Ive chosen hangman. Ive already made the main program , but i need help with the GUI. I havent been taught about GUI in school, so all i know is what i could understand from a book and what ive read on the internet..
    First , heres the code of my basic Hangman class:
    import java.io.*;
    import java.util.Random;
    public class Hangman
        public void maingame()throws IOException
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            String movies[]={"THE BOURNE ULTIMATUM","TRANSFORMERS","RUSH HOUR 3","THE INSIDE MAN","THE SIMPSONS MOVIE","THE LORD OF THE RINGS","DIE HARD 4.0"};
            Random rand = new Random();
            char current[]=(movies[rand.nextInt(movies.length)]).toCharArray();  //Convert a random string from movies array into a char array
            char actual[]=new char[current.length]; //Store current state of guessed movie
            for (int i=0;i<actual.length;i++)
                if (isVowel(Character.toUpperCase(current))==true)
    actual[i]=current[i];
    else if (isSpecialChar(Character.toUpperCase(current[i]))==true)
    actual[i]=current[i];
    else if (current[i]==' ')
    actual[i]='/';
    else
    actual[i]='_';
    String hangman = "HANGMAN";
    int turnsleft=7;
    StringBuffer guessed=new StringBuffer();
    while (turnsleft!=0)
    System.out.println("\n\t\t\t\t"+hangman.substring(0,turnsleft)+"\n");
    print(actual);
    System.out.println("\nEnter your guess");
    String inp = br.readLine();
    if (inp.length()>1)
    System.out.println("You may only enter one character");
    else
    char guess = inp.charAt(0); //Convert the entered string to char
    if ( (hasBeenGuessed(guess,guessed)) == true )
    System.out.println("You have already guessed that\nYou have "+turnsleft+" turns left");
    else if (guess >= '0' && guess <= '9')
    System.out.println("You cannot guess digits.All digits in a movie will will be filled in automatically");
    else
    guessed.append(guess);
    if (isVowel(guess)!=true)
    if (isCorrect(guess,turnsleft,current,actual)==true)
    if (hasWon(actual,current)==true)
    System.out.println();
    print(actual);
    System.out.println("\nCongratulations!You won!");
    System.exit(0);
    else
    System.out.println("\nCorrect Guess!\nYou have "+turnsleft+" turns left\n");
    else
    turnsleft--;
    System.out.println("Wrong Guess!\nYou have "+turnsleft+" turns left\n");
    else if (isVowel(guess)==true)
    System.out.println("You cannot guess vowels\nYou have "+turnsleft+" turns left\n");
    else
    System.out.println("You have already guessed that\nYou have "+turnsleft+" turns left\n");
    print(actual);
    if (turnsleft==0)
    System.out.println("\nYou lose!\nThe movie was: ");
    print(current);
    System.exit(0);
    private boolean isCorrect(char guess,int turnsleft,char current[],char actual[])
    int flag=0;
    for (int i=0;i<current.length;i++)
    if ( Character.toUpperCase(current[i])==Character.toUpperCase(guess) && actual[i]!=guess ) //Check if guess is correct, and make sure it has not already been entered
    actual[i]=guess;
    flag=1;
    else if (Character.toUpperCase(current[i])!=Character.toUpperCase(guess) && i==current.length-1 && flag==0)
    return false;
    if (flag!=0)
    return true;
    else
    return false;
    private boolean hasWon(char actual[],char current[])
    char actualspc[]=new char[actual.length];
    for (int i=0;i<actual.length;i++)
    if (actual[i]=='/')
    actualspc[i]=' ';
    else
    actualspc[i]=actual[i];
    for (int i=0;i<actual.length;i++)
    if ((Character.toUpperCase(current[i]))==(Character.toUpperCase(actualspc[i])) && i==actual.length-1)
    return true;
    else if ((Character.toUpperCase(current[i]))==(Character.toUpperCase(actualspc[i])) && i!=actual.length-1)
    continue;
    else
    return false;
    return false;
    private void print(char arr[])
    for (int i=0;i<arr.length;i++)
    System.out.print(Character.toUpperCase(arr[i])+" ");
    private boolean isVowel(char a)
    if (a=='a' || a=='A' || a=='e' || a=='E' || a=='i' || a=='I' || a=='o' || a=='O' || a=='u' || a=='U')
    return true;
    else
    return false;
    private boolean isSpecialChar(char a)
    //if (a>='a' && a<='z')
    //return false;
    //else if (a>='A' && a<='z')
    //return false;
    //else if (a==' ')
    //return false;
    //else if (a>='0' && a<='9')
    //return true;
    if (isLetter(a)==true)
    return false;
    else if (isWhiteSpace(a)==true)
    return false;
    else if (isDigit(a)==true)
    return true;
    else
    return true;
    private boolean hasBeenGuessed(char a,StringBuffer guessed)
    for (int i=0;i<guessed.length();i++)
    if ( Character.toUpperCase(guessed.charAt(i)) == Character.toUpperCase(a))
    return true;
    return false;
    My first 2 questions are here:
    a - Why does isLetter not work, it says cannot resolve symbol - method isLetter(char)... Im guessing even isDigit and isWhiteSpace wont work, so why? If i cant use them ill have to use the commented code, its kind of unprofessional..
    b- Isnt there any way i can compare chars ignoring cases besides converting both to one case, like im doing now?
    Heres the new HangmanGUI class i made, it doesnt necessarily have to be a different class in the final outcome, but i would prefer it if it can.. Ive made what i can figure out.. Ive commented about what i need to do.
    Keep in mind i cant use Applets, only Frame/JFrame
    import java.awt.*;
    import javax.swing.*;
    public class HangmanGUI extends JFrame implements ActionListener
        Button newGame = new Button("New Game");
        Button entGuess = new Button("Submit Guess");
        Button giveUp = new Button("Give Up");
        TextField input = new TextField("",1);
        Label hangman = new Label("HANGMAN");
        JPanel play = new JPanel();
        JPanel hang = new Jpanel();
        GridLayout playLayout = new GridLayout(2,4);
        public HangmanGUI()
            play.setLayout(playLayout);
            play.add(hangman+"\n");
            play.add(newGame);
            play.add(giveUp);
            play.add(input);
            play.add(entGuess);
            hang.add(hangman);
            getContentPane().add(play);
            getContentPane().add(hang);
        public void ActionPerformed(ActionEvent act)
            Object src = act.getSource();
            if (src==newGame)
            main(); //Calling main to restart program - will that work?
            //if (src==entGuess)
            //Need to submit the guess, while input is not empty to Hangman class
            //if (src==giveUp)
            //Need to go into the losing part of Hangman class
    }As you can see i need help with:
    a - How to complete the other ifs
    b - How to really use the data of my Hangman class in this class and combine the GUI and backend to make a nice GUI Hangman app
    c - btw, right now if i try to compile HangmanGUI it highlights the implements ActionListener line and says cannot resolve symbol - class ActionListener..
    Any help would be greatly appreciated

    Thanks for the explanation pete...
    Anyways, i started implementing my code within abillconsl's code, and im trying to assign a label to a char array using .toString(); but instead of whats in the char array i get [C@<numbers and digits> ..
    Whats wrong?
    [code]
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Random;
    public class HangEmHighGUI extends JFrame implements ActionListener
    private Button newGame,
    entGuess,
    giveUp;
    private TextField input;
    private Label hangman,
    movie;
    private JPanel play,
    hang;
    private GridLayout playLayout;
    private FlowLayout labelLayout;
    private Container container; // To avoid extra meth calls
    String movies[]={"THE/BOURNE/ULTIMATUM","TRANSFORMERS","RUSH HOUR 3","THE INSIDE MAN","THE SIMPSONS MOVIE","THE LORD OF THE RINGS","DIE HARD 4.0"};
    Random rand = new Random();
    char current[]=(movies[rand.nextInt(movies.length)]).toCharArray(); //Convert a random string from movies array into a char array
    char actual[]=new char[current.length]; //Store current state of guessed movie
    public HangEmHighGUI()
    setUp();
    container = this.getContentPane();
    play = new JPanel();
    hang = new JPanel();
    playLayout = new GridLayout(1, 3, 5, 5); // rows, cols, space, space
    labelLayout = new FlowLayout(FlowLayout.CENTER);
    newGame = new Button("New Game");
    entGuess = new Button("Submit Guess");
    giveUp = new Button("Give Up");
    input = new TextField("",1);
    hangman = new Label("HANGMAN");
    movie = new Label(actual.toString());
    hang.setLayout(labelLayout);
    play.setLayout(playLayout);
    play.add(newGame);
    play.add(giveUp);
    play.add(entGuess);
    hang.add(hangman);
    hang.add(movie);
    container.add(hang,BorderLayout.NORTH);
    container.add(input,BorderLayout.CENTER);
    container.add(play,BorderLayout.SOUTH);
    pack();
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public void actionPerformed(ActionEvent act)
    Object src = act.getSource();
    if (src==newGame)
    main(new String[] {""}); //Calling main to restart program, this does not work without parameters, is there some other way to restart?
    if (src==entGuess)
    if (input.getText()=="")
    setUp();
    //if (src==giveUp)
    //Need to go into the losing part of Hangman class
    public static void main(String args[])
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    new HangEmHighGUI();
    private void setUp()
    for (int i=0;i<actual.length;i++)
    if (isVowel(Character.toUpperCase(current)))
    actual[i]=current[i];
    else if (isSpecialChar(Character.toUpperCase(current[i])))
    actual[i]=current[i];
    else if (Character.isWhitespace(current[i]))
    actual[i]='/';
    else
    actual[i]='_';
    private boolean isVowel(char a)
    if (Character.toUpperCase(a)=='A' || Character.toUpperCase(a)=='E' || Character.toUpperCase(a)=='I' || Character.toUpperCase(a)=='O' || Character.toUpperCase(a)=='U')
    return true;
    else
    return false;
    private boolean isSpecialChar(char a)
    if (Character.isLetter(a))
    return false;
    else if (Character.isDigit(a))
    return true;
    else if (Character.isWhitespace(a))
    return false;
    else
    return true;
    private boolean isCorrect(char guess,int turnsleft,char current[],char actual[])
    int flag=0;
    for (int i=0;i<current.length;i++)
    if ( Character.toUpperCase(current[i])==Character.toUpperCase(guess) && actual[i]!=guess ) //Check if guess is correct, and make sure it has not already been entered
    actual[i]=guess;
    flag=1;
    else if (Character.toUpperCase(current[i])!=Character.toUpperCase(guess) && i==current.length-1 && flag==0)
    return false;
    if (flag!=0)
    return true;
    else
    return false;
    private boolean hasWon(char actual[],char current[])
    char actualspc[]=new char[actual.length];
    for (int i=0;i<actual.length;i++)
    if (actual[i]=='/')
    actualspc[i]=' ';
    else
    actualspc[i]=actual[i];
    for (int i=0;i<actual.length;i++)
    if ((Character.toUpperCase(current[i]))==(Character.toUpperCase(actualspc[i])) && i==actual.length-1)
    return true;
    else if ((Character.toUpperCase(current[i]))==(Character.toUpperCase(actualspc[i])) && i!=actual.length-1)
    continue;
    else
    return false;
    return false;
    private void print(char arr[])
    for (int i=0;i<arr.length;i++)
    System.out.print(Character.toUpperCase(arr[i])+" ");
    private boolean hasBeenGuessed(char a,StringBuffer guessed)
    for (int i=0;i<guessed.length();i++)
    if ( Character.toUpperCase(guessed.charAt(i)) == Character.toUpperCase(a))
    return true;
    return false;
    Note that the majority of the code has been taken from my old hangman class, i havent adapted it to the GUI yet, so ignore all of that stuff.

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

  • I need help with a VB Application

    I need help with building an application and I am on a tight deadline.  Below I have included the specifics for what I need the application to do as well as the code that I have completed so far.  I am having trouble getting the data input into
    the text fields to save to a .txt file.  Also, I need validation to ensure that the values entered into the text fields coincide with the field type.  I am new to VB so please be gentle.  Any help would be appreciated.  Thanx
    •I need to use the OpenFileDialog and SaveFileDialog in my application.
    •Also, I need to use a structure.
    1. The application needs to prompt the user to enter the file name on Form_Load.
    2. Also, the app needs to use the AppendText method to write the Employee Data to the text file. My project should allow me to write multiple Employee Data to the same text file.  The data should be written to the text file in the following format (comma
    delimited)
    FirstName, MiddleName, LastName, EmployeeNumber, Department, Telephone, Extension, Email
    3. The Department dropdown menu DropDownStyle property should be set so that the user cannot enter inputs that are not in the menu.
    Public Class Form1
    Dim filename As String
    Dim oFile As System.IO.File
    Dim oWrite As System.IO.StreamWriter
    Dim openFileDialog1 As New OpenFileDialog()
    Dim fileLocation As String
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    openFileDialog1.InitialDirectory = "c:\"
    openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
    openFileDialog1.FilterIndex = 1
    openFileDialog1.RestoreDirectory = True
    If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
    fileLocation = openFileDialog1.FileName
    End If
    'filename = InputBox("Enter output file name")
    'oWrite = oFile.CreateText(filename)
    cobDepartment.Items.Add("Accounting")
    cobDepartment.Items.Add("Administration")
    cobDepartment.Items.Add("Marketing")
    cobDepartment.Items.Add("MIS")
    cobDepartment.Items.Add("Sales")
    End Sub
    Private Sub btnSave_Click(ByValsender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    'oWrite.WriteLine("Write e file")
    oWrite.WriteLine("{0,10}{1,10}{2,10}{3,10}{4,10}{5,10}{6,10}{7,10}", txtFirstname.Text, txtMiddlename.Text, txtLastname.Text, txtEmployee.Text, cobDepartment.SelectedText, txtTelephone.Text, txtExtension.Text, txtEmail.Text)
    oWrite.WriteLine()
    End Sub
    Private Sub btnExit_Click(ByValsender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
    oWrite.Close()
    End
    End Sub
    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
    txtFirstname.Text = ""
    txtMiddlename.Text = ""
    txtLastname.Text = ""
    txtEmployee.Text = ""
    txtTelephone.Text = ""
    txtExtension.Text = ""
    txtEmail.Text = ""
    cobDepartment.SelectedText = ""
    End Sub
    End Class

    Hi Mikey81,
    Your issue is about VB programming, so Visual Basic forum is a better forum for your case. I moved this thread there,
    Thanks,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Need help with Berkeley XML DB Performance

    We need help with maximizing performance of our use of Berkeley XML DB. I am filling most of the 29 part question as listed by Oracle's BDB team.
    Berkeley DB XML Performance Questionnaire
    1. Describe the Performance area that you are measuring? What is the
    current performance? What are your performance goals you hope to
    achieve?
    We are measuring the performance while loading a document during
    web application startup. It is currently taking 10-12 seconds when
    only one user is on the system. We are trying to do some testing to
    get the load time when several users are on the system.
    We would like the load time to be 5 seconds or less.
    2. What Berkeley DB XML Version? Any optional configuration flags
    specified? Are you running with any special patches? Please specify?
    dbxml 2.4.13. No special patches.
    3. What Berkeley DB Version? Any optional configuration flags
    specified? Are you running with any special patches? Please Specify.
    bdb 4.6.21. No special patches.
    4. Processor name, speed and chipset?
    Intel Xeon CPU 5150 2.66GHz
    5. Operating System and Version?
    Red Hat Enterprise Linux Relase 4 Update 6
    6. Disk Drive Type and speed?
    Don't have that information
    7. File System Type? (such as EXT2, NTFS, Reiser)
    EXT3
    8. Physical Memory Available?
    4GB
    9. Are you using Replication (HA) with Berkeley DB XML? If so, please
    describe the network you are using, and the number of Replica’s.
    No
    10. Are you using a Remote Filesystem (NFS) ? If so, for which
    Berkeley DB XML/DB files?
    No
    11. What type of mutexes do you have configured? Did you specify
    –with-mutex=? Specify what you find inn your config.log, search
    for db_cv_mutex?
    None. Did not specify -with-mutex during bdb compilation
    12. Which API are you using (C++, Java, Perl, PHP, Python, other) ?
    Which compiler and version?
    Java 1.5
    13. If you are using an Application Server or Web Server, please
    provide the name and version?
    Oracle Appication Server 10.1.3.4.0
    14. Please provide your exact Environment Configuration Flags (include
    anything specified in you DB_CONFIG file)
    Default.
    15. Please provide your Container Configuration Flags?
    final EnvironmentConfig envConf = new EnvironmentConfig();
    envConf.setAllowCreate(true); // If the environment does not
    // exist, create it.
    envConf.setInitializeCache(true); // Turn on the shared memory
    // region.
    envConf.setInitializeLocking(true); // Turn on the locking subsystem.
    envConf.setInitializeLogging(true); // Turn on the logging subsystem.
    envConf.setTransactional(true); // Turn on the transactional
    // subsystem.
    envConf.setLockDetectMode(LockDetectMode.MINWRITE);
    envConf.setThreaded(true);
    envConf.setErrorStream(System.err);
    envConf.setCacheSize(1024*1024*64);
    envConf.setMaxLockers(2000);
    envConf.setMaxLocks(2000);
    envConf.setMaxLockObjects(2000);
    envConf.setTxnMaxActive(200);
    envConf.setTxnWriteNoSync(true);
    envConf.setMaxMutexes(40000);
    16. How many XML Containers do you have? For each one please specify:
    One.
    1. The Container Configuration Flags
              XmlContainerConfig xmlContainerConfig = new XmlContainerConfig();
              xmlContainerConfig.setTransactional(true);
    xmlContainerConfig.setIndexNodes(true);
    xmlContainerConfig.setReadUncommitted(true);
    2. How many documents?
    Everytime the user logs in, the current xml document is loaded from
    a oracle database table and put it in the Berkeley XML DB.
    The documents get deleted from XML DB when the Oracle application
    server container is stopped.
    The number of documents should start with zero initially and it
    will grow with every login.
    3. What type (node or wholedoc)?
    Node
    4. Please indicate the minimum, maximum and average size of
    documents?
    The minimum is about 2MB and the maximum could 20MB. The average
    mostly about 5MB.
    5. Are you using document data? If so please describe how?
    We are using document data only to save changes made
    to the application data in a web application. The final save goes
    to the relational database. Berkeley XML DB is just used to store
    temporary data since going to the relational database for each change
    will cause severe performance issues.
    17. Please describe the shape of one of your typical documents? Please
    do this by sending us a skeleton XML document.
    Due to the sensitive nature of the data, I can provide XML schema instead.
    18. What is the rate of document insertion/update required or
    expected? Are you doing partial node updates (via XmlModify) or
    replacing the document?
    The document is inserted during user login. Any change made to the application
    data grid or other data components gets saved in Berkeley DB. We also have
    an automatic save every two minutes. The final save from the application
    gets saved in a relational database.
    19. What is the query rate required/expected?
    Users will not be entering data rapidly. There will be lot of think time
    before the users enter/modify data in the web application. This is a pilot
    project but when we go live with this application, we will expect 25 users
    at the same time.
    20. XQuery -- supply some sample queries
    1. Please provide the Query Plan
    2. Are you using DBXML_INDEX_NODES?
    Yes.
    3. Display the indices you have defined for the specific query.
         XmlIndexSpecification spec = container.getIndexSpecification();
         // ids
         spec.addIndex("", "id", XmlIndexSpecification.PATH_NODE | XmlIndexSpecification.NODE_ATTRIBUTE | XmlIndexSpecification.KEY_EQUALITY, XmlValue.STRING);
         spec.addIndex("", "idref", XmlIndexSpecification.PATH_NODE | XmlIndexSpecification.NODE_ATTRIBUTE | XmlIndexSpecification.KEY_EQUALITY, XmlValue.STRING);
         // index to cover AttributeValue/Description
         spec.addIndex("", "Description", XmlIndexSpecification.PATH_EDGE | XmlIndexSpecification.NODE_ELEMENT | XmlIndexSpecification.KEY_SUBSTRING, XmlValue.STRING);
         // cover AttributeValue/@value
         spec.addIndex("", "value", XmlIndexSpecification.PATH_EDGE | XmlIndexSpecification.NODE_ATTRIBUTE | XmlIndexSpecification.KEY_EQUALITY, XmlValue.STRING);
         // item attribute values
         spec.addIndex("", "type", XmlIndexSpecification.PATH_EDGE | XmlIndexSpecification.NODE_ATTRIBUTE | XmlIndexSpecification.KEY_EQUALITY, XmlValue.STRING);
         // default index
         spec.addDefaultIndex(XmlIndexSpecification.PATH_NODE | XmlIndexSpecification.NODE_ELEMENT | XmlIndexSpecification.KEY_EQUALITY, XmlValue.STRING);
         spec.addDefaultIndex(XmlIndexSpecification.PATH_NODE | XmlIndexSpecification.NODE_ATTRIBUTE | XmlIndexSpecification.KEY_EQUALITY, XmlValue.STRING);
         // save the spec to the container
         XmlUpdateContext uc = xmlManager.createUpdateContext();
         container.setIndexSpecification(spec, uc);
    4. If this is a large query, please consider sending a smaller
    query (and query plan) that demonstrates the problem.
    21. Are you running with Transactions? If so please provide any
    transactions flags you specify with any API calls.
    Yes. READ_UNCOMMITED in some and READ_COMMITTED in other transactions.
    22. If your application is transactional, are your log files stored on
    the same disk as your containers/databases?
    Yes.
    23. Do you use AUTO_COMMIT?
         No.
    24. Please list any non-transactional operations performed?
    No.
    25. How many threads of control are running? How many threads in read
    only mode? How many threads are updating?
    We use Berkeley XML DB within the context of a struts web application.
    Each user logged into the web application will be running a bdb transactoin
    within the context of a struts action thread.
    26. Please include a paragraph describing the performance measurements
    you have made. Please specifically list any Berkeley DB operations
    where the performance is currently insufficient.
    We are clocking 10-12 seconds of loading a document from dbd when
    five users are on the system.
    getContainer().getDocument(documentName);
    27. What performance level do you hope to achieve?
    We would like to get less than 5 seconds when 25 users are on the system.
    28. Please send us the output of the following db_stat utility commands
    after your application has been running under "normal" load for some
    period of time:
    % db_stat -h database environment -c
    % db_stat -h database environment -l
    % db_stat -h database environment -m
    % db_stat -h database environment -r
    % db_stat -h database environment -t
    (These commands require the db_stat utility access a shared database
    environment. If your application has a private environment, please
    remove the DB_PRIVATE flag used when the environment is created, so
    you can obtain these measurements. If removing the DB_PRIVATE flag
    is not possible, let us know and we can discuss alternatives with
    you.)
    If your application has periods of "good" and "bad" performance,
    please run the above list of commands several times, during both
    good and bad periods, and additionally specify the -Z flags (so
    the output of each command isn't cumulative).
    When possible, please run basic system performance reporting tools
    during the time you are measuring the application's performance.
    For example, on UNIX systems, the vmstat and iostat utilities are
    good choices.
    Will give this information soon.
    29. Are there any other significant applications running on this
    system? Are you using Berkeley DB outside of Berkeley DB XML?
    Please describe the application?
    No to the first two questions.
    The web application is an online review of test questions. The users
    login and then review the items one by one. The relational database
    holds the data in xml. During application load, the application
    retrieves the xml and then saves it to bdb. While the user
    is making changes to the data in the application, it writes those
    changes to bdb. Finally when the user hits the SAVE button, the data
    gets saved to the relational database. We also have an automatic save
    every two minues, which saves bdb xml data and saves it to relational
    database.
    Thanks,
    Madhav
    [email protected]

    Could it be that you simply do not have set up indexes to support your query? If so, you could do some basic testing using the dbxml shell:
    milu@colinux:~/xpg > dbxml -h ~/dbenv
    Joined existing environment
    dbxml> setverbose 7 2
    dbxml> open tv.dbxml
    dbxml> listIndexes
    dbxml> query     { collection()[//@date-tip]/*[@chID = ('ard','zdf')] (: example :) }
    dbxml> queryplan { collection()[//@date-tip]/*[@chID = ('ard','zdf')] (: example :) }Verbosity will make the engine display some (rather cryptic) information on index usage. I can't remember where the output is explained; my feeling is that "V(...)" means the index is being used (which is good), but that observation may not be accurate. Note that some details in the setVerbose command could differ, as I'm using 2.4.16 while you're using 2.4.13.
    Also, take a look at the query plan. You can post it here and some people will be able to diagnose it.
    Michael Ludwig

  • Need help with almost completed plugin engine project

    Hi all,
    For a while now I have been working on a plugin engine. After a few iterations, the engine is similar to the Eclipse engine, in that plugins use extension points and extensions to allow contributions. Unlike the eclipse engine I have added the ability for plugins to fire events through the engine and other plugins can add listeners, all through the plugin.xml manifest. Dependencies are mostly handled automatically at plugin load time (when extensions get resolved to extension points, and listeners get resolved to events). For the case where a plugin needs to use classes from another plugin, dependencies are also allowed to be declared. Like the eclipse engine, activation of plugins occurs the first time a class is used within the plugin's classpath, OR a plugin can be activated after it is loaded.
    What I need help with is testing, working on examples to provide with the engine project, and feedback/suggestions before we release the M1 build. I am asking for those that are interested in this type of work to volunteer to help where applicable and possible. I want to provide a solid plugin engine to the java community, one that is easy to use, works well, and is pretty effecient in terms of resource usage and performance.
    Of particular interest to me right at the moment is dealing with multiple versions. As I see it, the engine will be used within an application and as such plugins would be distributed with a specific application version. The plugin version itself is more of a notification as to what version a plugin is, although I imagine it will help when updating at runtime as well.
    Just a few other details of the engine. It handles (or will soon) dynamic load, unload and reload of plugins at runtime. Plugins can be distributed in an archive file format, we call .par (Plugin ARchive), with additional plugin filename extensions configurable at runtime. The plugins can be developed and deployed in an expanded directory format as they are in Eclipse as well, or in the archive format. In the archive format they do not need to be unzipped when deployed, and they can contain embeded jar/zip libraries. The engine handles finding and creating classes directly out of the .par file at runtime.
    Multiple locations to find plugins are configurable before the engine starts, and even after it starts more could be added to allow additional locations to find plugins. URLs are supported, and soon the HTTP protocol will be supported so that plugins can be downloaded and installed at runtime.
    The project can be found at www.sourceforge.net/projects/genpluginengine. If you would like to get involved and help out, please sign up on the dev mail list and send an email to introduce yourself to the rest of the members on the list.
    I'll also add that I am working on a Swing UI Framework built entirely from plugins. It provides a ready-to-launce UI application that developers can simply add their plugins to, extending various extension points of the framework to have menu items, toolbar buttons, status bar access, help and preferences dialog additions, file i/o choosers, tons of open-source components ready to use (or extend to add on to), and like Eclipse, hopefully... draggable window frames that can be dropped on any other frame to form a tabbed frame of windows. Some of this is a ways off, some is getting there now. Presently you can add menu items that do allow plugin activation when first clicked, so plugins can be loaded but not activated until needed. The Preference dialog works but is not completed, and a plugin that adds a plugin control panel to view all loaded plugins, activate them, load/unload/reload, view extension points, extensions, dependencies, etc is partially completed. The point is, to allow a ready to run UI framework in Swing with an easy path for developers to quickly build applications with. If you are interested in this, when you join the mail list and introduce yourself, indicate that you are interested in this as well, as we need help with plugin development for it and would appreciate more help here too.
    Look forward to some replies.

    Might I suggest setting up a project at a known project-site? I've seen your progress and questions posted here from time to time, but one of the drawbacks is that you have to fill each post with the entirity of your vision to explain what you're doing. That's a lot of text to read - and most folks will skip right over it.
    On the other hand, a well-crafted, good-looking project web-site, with appropriate links and docs and vision statements, diagrams, etc. will have more likelyhood of attracting volunteers. java.net and sourceforge.net are likely spots to set up shop. In addition, you get CVS and bug-tracking systems, which can be quite valuable in such a large-scale project where there are lots of pieces.

Maybe you are looking for