Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Yes.

VernonDozier commented: Couldn't have said it better myself. :) +6
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Perhaps research how a complete lack of attention to written communication skills may impact a career.

jwenting commented: well said! +18
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

With a Timer.

Alex Edwards commented: Short, subtle and sufficient all at once! +4
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

If this is for your "email marketing campaign" (spamming), we're not going to show you how to scrape email addresses for your spam list.

jwenting commented: well said +18
sciwizeh commented: agreed +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Also, don't make everything in your class static for no reason.

sciwizeh commented: can't believe i didn't notice nice catch +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Yes, some of their examples can be more complex than need be and obscure the usage they are trying to demonstrate. :(

One more thing worth noting with respect to AffineTransforms is that they represent the current state of the coordinate system within the graphics context. Since you can store references to as many AffineTransforms as you want, you can effectively "save" any state (translation, orientation, scale, and sheer) you wish and restore it at will. If you have many objects that render themselves independently, each can maintain it's own transform that it uses for rendering. When that object's turn to be rendered comes, you can save the current transform of your graphics context, apply that object's transform, render it, and then restore the original transform.

Here's an example of that:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TransformExample extends JFrame {

    GraphicPanel gPanel;

    public TransformExample() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        gPanel = new GraphicPanel();
        getContentPane().add(gPanel);
        setBounds(100, 100, 200, 200);
        setVisible(true);
    }

    class GraphicPanel extends JPanel {
        TextLabel label1;
        TextLabel label2;
        TextLabel label3;

        protected void paintComponent(Graphics g) {
            if (label1 == null) {
                // lazy initilization so I have dimensions to work with
                FontMetrics fm = g.getFontMetrics();
                int width = getWidth();
                int height = getHeight();
                
                label1 = new TextLabel("Hi Vernon", Color.YELLOW, 
                  20, height/2, -Math.PI/2);
                
                String labelText = "I'm over here";
                int labelLen = fm.stringWidth(labelText);
                label2 = new TextLabel(labelText, Color.CYAN, 
                  width-labelLen, height/2, …
VernonDozier commented: Exactly what I was looking for! +6
Alex Edwards commented: Excellent example of professional programming. +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

i don't understand how byte stream could read images. does it need help of applets or else.

Images are comprised of bytes.
You want to read them.
Byte streams read bytes.
You use a byte stream.

...

Alex Edwards commented: Spoon feed-- +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

If you have specific questions, post your current code in [code] [/code] tags and your questions or errors. If you have no idea how to proceed and need someone to walk you through the whole thing you are probably out of luck.

(And using 17 exclamation points does not get help faster - it might just have the opposite effect)

Alex Edwards commented: ! +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I already provided links above that cover the major steps involved. If you need more general links on Java, look through the "Read Me: Starting Java" thread that is stickied at the top of the forum.

Alex Edwards commented: You have a lot of patience. +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

i would ask that all software developers make programs that work and do the job right the first time

Oh, well sorry, that goes against our desire to make programs that don't work and do the job wrong, just to laugh at your frustration with it.

i also think techies that work on computers should share a close bond with software developers. it is very important for it to all live in harmony like it does when it exists in side of a computer case.

Your statement above calls into question your desire for harmony.

Nick Evan commented: Haha +8
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

It's not Java, obviously - it's gibberish.

Alex Edwards commented: I cannot stop laughing... good one +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Well

public void actionPerformed(ActionEvent e)
            {
            	JFrame About = new JFrame();
    			JLabel label = new JLabel("Hello World");
            	About.getContentPane().add(label);
    			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            	setTitle("About");
            	setVisible(true);
            	
            }

only one of those statements is calling a method on your "About" frame - the rest are acting on your current frame class. The errors of the last two posts just show a lack of attention rather than a lack of knowledge. If you have an error or improper behavior in the code, look at it critically and try to see why it could possibly be doing that before you post it.

As far as the blank menu, look at the super() calls in the constructors of the other menu actions and look at your own action class constructor.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

If you can use them, key bindings are easier to handle with regards to focus:
http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
but if you can't use those then you could call requestFocusInWindow() on the JApplet (or whatever other container you need to have focus) at the end of your button listener code

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JOptionPane;


public class FocusTest extends JApplet {
 
    JButton button;

    public void init() {
        button = new JButton("Ok");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                requestFocusInWindow();
            }
        });
        setLayout(new BorderLayout());
        add(button,BorderLayout.SOUTH);
        
        setFocusable(true);
        addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                JOptionPane.showMessageDialog(FocusTest.this, "Key pressed");
            }
            
        });
    }
}
Alex Edwards commented: You rock! +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Ask them?

Salem commented: Simply elegant, who would have thought it so simple! +20
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Have you tried it?

Alex Edwards commented: Probably the answer to many questions on these forums. +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Was it a Baptist church?
:twisted:

scru commented: hehe +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Given the above discussion on using a panel to draw on and the fact that overriding paintComponent() really is the better way to go, I'd recommend the following, which is only a minor re-arrangement of your existing code (see comments on changes)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Hangman extends JFrame implements ActionListener {

    // DECLARATIONS
    JLabel inputL,
      lettersL,
      wordL;
    JTextField inputTF,
      lettersTF,
      wordTF;
    JButton checkB,
      exitB;
    final String WORD[] = {"SPLINTER", "MAGICAL", "FUNDAMENTAL", "ONYX", "UNIVERSAL", "MYSTERIOUS", "QUAIL", "DISCOVER", "UNIQUE", "OLYMPICS"};
    static int index;
    int chances = 6;
    char[] blanks, guess;
    String usedLetters = "";
    // New reference to your hangman panel
    JPanel graphicPanel;

    public Hangman() {
        // override paintComponent to call the drawHangman() method
        graphicPanel = new JPanel() {
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                drawHangman(g);
            }
        };
        graphicPanel.setBackground(Color.black);

        inputL = new JLabel("Enter a letter");
        lettersL = new JLabel("Used Letters");
        wordL = new JLabel("The Word");

        inputTF = new JTextField();
        lettersTF = new JTextField(26);
        wordTF = new JTextField(16);

        inputTF.setFont(new Font("Arial", Font.BOLD, 20));
        inputTF.setHorizontalAlignment(0);
        lettersTF.setFont(new Font("Arial", Font.BOLD, 20));
        lettersTF.setEditable(false);
        lettersTF.setHorizontalAlignment(JTextField.CENTER);
        wordTF.setFont(new Font("Arial", Font.BOLD, 20));
        wordTF.setEditable(false);
        wordTF.setHorizontalAlignment(JTextField.CENTER);

        String text = "";
        for(int ctr = 0; ctr<WORD[index].length(); ctr++) {
            text = text+"_ ";
        }
        wordTF.setText(text);
        blanks = text.toCharArray();

        checkB = new JButton("Check");
        checkB.addActionListener(this);

        exitB = new JButton("EXIT");
        exitB.addActionListener(this);

        Container pane = getContentPane();
        pane.setLayout(new GridLayout(1, 2, 10, 0));

        Container pane1 = new Container();
        pane1.setLayout(new GridLayout(8, 1, 8, 8));
        pane1.add(wordL);
        pane1.add(wordTF);
        pane1.add(lettersL);
        pane1.add(lettersTF);
        pane1.add(inputL);
        pane1.add(inputTF);
        pane1.add(checkB, BorderLayout.EAST);
        pane1.add(exitB, BorderLayout.SOUTH);

        pane.add(graphicPanel);
        pane.add(pane1);

        setResizable(false);
        setTitle("Hangman BETA VERSION");
        setLocation(120, 120);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(500, 500);
    } …
sciwizeh commented: useful information +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Can any one tell about the difference between the Abstract Class and Interface?

Abstract classes can contain implementations of some methods, while interfaces cannot. This allows abstract classes to serve as a base implementation of a class hierarchy that shares some (or much) common code and require that subclasses implement only the portions that are specific to themselves.

Can abstract class replaces Interface?

In some cases, yes, in others, no. See next comment below.

If all things can be done in Abstract class Why we need Interface?

Java only allows for single inheritance of classes, but the number of interfaces implemented is unlimited. Use of interfaces allows classes to act as more than one type of object. Without interfaces, all methods that you may want a group of classes to share must be stuffed into a common base class. What if some of these methods only apply to some classes but not others? Your class hierarchy would become a polluted mess, littered with methods that may not even apply to a particular class. Interfaces operate as a contract that guarantees a class implements one or more methods without forcing them to descend from a common base class. Many different kinds of class hierarchies may want to be Printable, or Comparable, or Displayable, without having to extend from some common ancestor. That can only be accomplished with interfaces.

You read more about this here if you wish: http://www.codeguru.com/java/tij/tij0080.shtml

Alex Edwards commented: Expert Answer +2
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Here is the code I used to dump a "colorscan" display of some sensor data to an image file so I could fiddle with it in an external image processing package. Our component was using an offscreen Image buffer to draw on and then rendering with g.drawImage() in the paintComponent method, so I already had an Image of the panel, but I fiddled with the code just a bit and the following should work for you if you don't need to save the frame decorations (title bar, etc), just the contents .
The action listener code to save:

public void actionPerformed(java.awt.event.ActionEvent e){
    try {
        File saveFile = new File(jobFile+"_colorscan@"+centerSampleIndex+".gif");
        Image img = createImage(getWidth(),getHeight());
        Graphics g = img.getGraphics();
        paint(g);
        ImageIO.write(toBufferedImage(img),"gif",saveFile);
        JOptionPane.showMessageDialog(null,"Image saved to "+saveFile.toString());
        g.dispose();
    } catch (Exception ex){
        ex.printStackTrace();
    }
}

The method to convert the Image to a BufferedImage (which I found in some example somewhere):

// This method returns a buffered image with the contents of an image
private BufferedImage toBufferedImage(Image image) {
    if (image instanceof BufferedImage) {
        return (BufferedImage)image;
    }

    // This code ensures that all the pixels in the image are loaded
    image = new ImageIcon(image).getImage();

    // Determine if the image has transparent pixels; for this method's
    // implementation, see e661 Determining If an Image Has Transparent Pixels
    boolean hasAlpha = hasAlpha(image);

    // Create a buffered image with a format that's compatible with the screen
    BufferedImage bimage = null;
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    try {
        // Determine the type of transparency of the …
VernonDozier commented: Code worked perfectly. +5
darkagn commented: Great post with lots of useful info +1
Alex Edwards commented: You deserve a promotion, dude. Epic win. +2
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Handing students completed solutions to their projects only enables laziness and incompetence. Limited examples, links to concept tutorials, and answers to specific questions are more appropriate.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Ok, here is a small example of a multi-threaded server that I was playing around with a little while working on an auto-update launcher for an app here, maybe it will help. "Launcher" is the client portion. Each needs to be run separately on the same machine (since the client is connecting to localhost in the example)
Server:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Server {
    final static int PORT = 12100;
    Thread processThread;
    
    public Server() {
        try {
            processThread = new ProcessThread(new ServerSocket(PORT));
            processThread.start();
        } catch(IOException ex) {
            ex.printStackTrace();
        }
    }
    
    private class ProcessThread extends Thread {
        ServerSocket server;
        ExecutorService requestPool;
        
        public ProcessThread(ServerSocket server){
            this.server = server;
            requestPool = Executors.newCachedThreadPool();
        }
        
        public void run() {
            try {
                System.out.println("server waiting to process..");
                while(true) {
                    Socket sock = server.accept();
                    // start an UpdateTask for this client
                    requestPool.submit(new UpdateTask(sock));
                    sleep(100);
                }
            } catch(IOException ex) {
                ex.printStackTrace();
            } catch(InterruptedException e) {
                   // Disable new tasks from being submitted
                   requestPool.shutdown(); 
                   try {
                     // Wait a while for existing tasks to terminate
                     if (!requestPool.awaitTermination(60, TimeUnit.SECONDS)) {
                       // Cancel currently executing tasks
                       requestPool.shutdownNow(); 
                       // Wait a while for tasks to respond to being cancelled
                       if (!requestPool.awaitTermination(60, TimeUnit.SECONDS))
                           System.err.println("Pool did not terminate");
                     }
                   } catch (InterruptedException ie) {
                     // (Re-)Cancel if current thread also interrupted
                     requestPool.shutdownNow();
                     // Preserve interrupt status
                     Thread.currentThread().interrupt();
                   }
                Thread.currentThread().interrupt();
            }
        }
    }
    
    public void shutdown(){
        if (processThread != null && processThread.isAlive()){
            processThread.interrupt();
        }
    }
    
    /** …
Alex Edwards commented: Thank you for providing an example =) +2
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I haven't seen any tutorials for JSP , so I guess I will post this one link that I found.

http://www.visualbuilder.com/jsp/tutorial/pageorder/1/

Perhaps that is because JSP has it's own forum over in the Web Development section.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Vernon is completely correct. We volunteer our time helping people out as we see fit. Your current posting trend is leading you towards less help, not more.

VernonDozier commented: Here's some rep for agreeing with me :) and because you've written some good posts that I haven't given you rep for yet. :) +5
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Two suggestions:
1) Read the forum rules on using proper English - not text-speak - here: http://www.daniweb.com/forums/faq.php?faq=daniweb_policies#faq_keep_it_clean
This isn't a chat room.

2) Use the search function. There are probably a thousand "Need a project topic" posts for you to peruse.

Nick Evan commented: yup, that works for me +8
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Well, actually those directions aren't quite correct on the tutorial page. The file they reference has a package declaration

package start;

but they do not mention that and the command to run that file won't work as they have it written. Remove that package declaration and re-compile it and it should work fine.

If you leave in the package statement, you would need to have that class file in a directory called 'start' and from it's parent directory you would execute it as follows

java start.HelloWorldSwing
peter_budo commented: Thanx for the tip :) +9
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I really didn't think something like this would be this hard. It's going to take awhile, and a lot of study and practice, but I am going to eventually figure it out.

You never "finish" learning good design skills. Each project is different in some way (if it wasn't, you would just keep using the first one right?) and there are many possible ways to design it. Finding the one that best suits the particulars of the problem at hand is the "art" portion of programming and comes only through experience - it's also the challenging part that keeps it interesting.

While good design skills only come with experience, there are several good books available with valuable and thought-provoking advice. If you're interested, I would recommend:

Design Patterns: Elements of Reusable Object-Oriented Software - the canonical book on software design patterns. You will surely here criticism regarding the overuse of patterns and some can certainly be "overkill" for a lot of simple design tasks, but reading and knowing about them will give you a perspective on design and object interaction that you won't get from simple coursework or tutorials.

Refactoring: Improving the Design of Existing Code covers just what the title says: Improving the design of code you already have written and working.

Code Complete, Second Edition has all kinds of useful information and advice on many aspects of programming, design, and software project management. While geared more towards working …

Alex Edwards commented: I will have to purchase those books sometime soon =) +2
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I really wouldn't recommend trying to keep accurate time information by incrementing your own variables, since you have little control over things like processor time-slicing and garbage collection. This portion here presents an additional unknown

ActionListener al = new ActionListener(){
		public void actionPerformed(ActionEvent e){
			finishTime++;
		}
	};

That listener code will execute on the AWT event dispatching thread, in a single-threaded queue with all of the other AWT events. You have no way of knowing exactly when actionPerformed() will get executed.

If you need accurate timing use System.nanoTime() in conjuction with variables to capture the time at crucial points and make timing decisions based on a calculated elapsed time against the current value of System.nanoTime().

Alex Edwards commented: Thank you for the clarification on how Timer really works. I wasn't aware of its unpredictable execution. +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Exactly. You are just supporting the same point that I was trying to make: each has it's own strengths and weaknesses that need to be taken into consideration when deciding which to use for a specific purpose.

Alex Edwards commented: Ezzaral, you rock dude! +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

C++ is powerful.

And Java is powerful and so is Assembly.

As was mentioned, the JVM was written in C++.

It couldn't be written in Java, now could it? This is irrelevant.

If you can't do something in another language, do it in C++.

Or some other language. Take your pick, there are a ton to choose from.

As is evident by the fact that the JVM is written in C++, you can create languages with C++.

You can create languages from most any language. They are just mechanisms to convert text instructions to machine code.

Almost all of the software you use relies in some way on C++.

No, it all relies on machine instructions, as does C++ itself.

Certain things in C++ just seem like they're more correct than in other languages.

Seem more correct to whom? You? Computer scientists? Your third grade teacher? Jesus? "Seem more correct" is hardly an objective basis for any comparison.

I'm just beginning to learn Java, but Java seems to be a very web-oritented lanaguage

It was originally designed with network computing needs in mind, yes, but there is plenty in Java that has nothing whatsoever to do with networks or the web.

(I read somewhere that its web oritentation iS why it doens't have pointers - since one of the qualities of being web-friendly is security, getting rid of pointers ensured that Java programs can't access memory outside of the JVM).

Not allowing direct …

VernonDozier commented: Great post. +5
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Perhaps you should be more concerned with attending to your studies than whether your phone is "trendy and expensive looking" or "out of fashion".

Salem commented: Damn straight! +18
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Use String input = in.nextLine(); instead of in.next().

Also realize that you are not reading anything from a file, you are appending the filename they entered to your StringBuilder. You have to open that file and read it's contents into your StringBuilder.

s.o.s. makes a good point about managing how much you are accumulating into that StringBuilder in memory before you write it out to your output file. You haven't stated the details of the assignment, but you may want to review the specifics on file size assumptions and io buffering. Those are things that you would have to manage if this were a real application.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Look over his shoulder.

Ancient Dragon commented: great idea, and useful too. +34
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Needs more commas.

Ancient Dragon commented: HaHa :) +31
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

thxs all and i said i need some help here
since i know the loops and String and Array and many many thing

Start writing it then and post your code and questions when you have difficulties. We are not here to walk you through the entire thing.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Who knows? Never heard of "ArrayInitializer". Though that code does not compile due to a missing semi-colon, and it does not produce a correct result if corrected to compile.

jasimp commented: stephen84s knows +7
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I don't follow what you mean. If the class extends Applet or JApplet, it runs in the Applet viewer when you run or debug the file.

Alex Edwards commented: Hah! I figured it out. I kept trying to create an Applit from a new Project, and not an existing package! I'm such a nub! +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Ok, yeah, Notepad needs a "\r\n" carriage return and line feed pair. Using just the newline shows up as a little square symbol. Wordpad will handle the newlines by themselves just fine. If you want to avoid having to mess with knowing which to use when, you can get the system-specific line separator from the system properties like so

String newLine = System.getProperty("line.separator");
StringBuffer sb =new StringBuffer ();
sb.append("First line");
sb.append(newLine);
sb.append("this should go to second line");
PrintStream.println(sb.toString());
darkagn commented: Excellent explanation and good solution to the problem +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Ok, the only thing preventing your loop from working is that that the call to hasNextInt() does not actually read (advance) past the input, it just determines what is there. If you enter a number then your code reads it with the nextInt() call, but if something other than an int is entered, the input is never read and the scanner stays at that position, so every hasNextInt() call still says "Nope, the input isn't an int". To fix that, you need to read off the invalid input before asking again, like so

while(num1==false){
System.out.print("Enter an Integer: ");
    if (input.hasNextInt())
    {
            number1=input.nextInt();
            num1=true;
    }
    else {
        System.out.println("Invalid Input!");
        [B]input.next();  // This will advance the scanner[/B]
    }
}

redZero's code is completely invalid for what you are trying to do, so just disregard it. It doesn't use Scanner, it has no loop to re-query after invalid input, and throws IOException from main() rather than dealing with it in a try-catch block, which is a really bad idea. Exceptions should never be thrown by main().

Something you might want to consider is putting the code that gets the int input into a separate method. You have repeated the same code twice to get two numbers and repetition like that should stand out as a candidate for it's own method.

esy928 commented: AWESOME!!! +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I haven't messed around with styled text panes much, so there may be a more appropriate way to do this, but I did get it to alternate the alignment with the following listener:
(txtInput is just a text field component and I pass the listener a reference to the text panes getStyledDocument() result)

class StyledInsertListener implements ActionListener {

    boolean alignLeft = true;
    StyledDocument doc;

    public StyledInsertListener(StyledDocument doc) {
        this.doc = doc;

        Style defaultStyle = StyleContext.getDefaultStyleContext().
          getStyle(StyleContext.DEFAULT_STYLE);

        Style styleRef = doc.addStyle("left", defaultStyle);
        StyleConstants.setAlignment(styleRef, StyleConstants.ALIGN_LEFT);

        styleRef = doc.addStyle("right", defaultStyle);
        StyleConstants.setAlignment(styleRef, StyleConstants.ALIGN_RIGHT);
    }

    public void actionPerformed(ActionEvent e) {
        String input = txtInput.getText()+"\n";
        try {
            if(alignLeft) {
                doc.setLogicalStyle(doc.getLength(), doc.getStyle("left"));
                doc.insertString(doc.getLength(), input, doc.getStyle("left"));
                alignLeft = false;
            } else {
                doc.setLogicalStyle(doc.getLength(), doc.getStyle("right"));
                doc.insertString(doc.getLength(), input, doc.getStyle("right"));
                alignLeft = true;
            }
        } catch(BadLocationException ex) {
            ex.printStackTrace();
        }
    }
}

The insertString() call by itself would not respect the alignment of the style, so I presume that it was treating it as within the same paragragh. Adding the setLogicalStyle() call did the trick, though it seems redundant to specify that style twice. I couldn't find a mechanism to force a new paragraph prior to insertion, but I would assume there is a way to do that. I just didn't have time to delve much deeper into it.

sciwizeh commented: quite useful info +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Well, unless your BaseConversion.stackreturn() method throws that exception, nothing else in that code will.

It looks like you are actually wanting to catch NumberFormatException from the parseInt() call. Read the API doc on that method: http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
There's a lot of useful into in those docs - use them.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

It's just an extended break ("relaxation") until you can begin another cycle as described :)

twomers commented: The vicious... I mean beautiful circle! +6
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

On which line? The stack trace provides the line number and specifics of the error.

"adv" is not defined in addAdvice(), which is most likely the source of your error.

Also, I would point out that the method

public void addAdvice (String advice)
    {
           
       if (index < advice.length) 
       {
           advice[index] = adv;
           index++;
       }
                   
    }

gives you plenty of room to create errors. You have named the string parameter the same as your array instance variable. I would recommend changing that parameter name to something like "entry" to avoid ambiguity and scope issues.

sktr4life commented: thanks for all the help... +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

You don't need to declare char arrays for every value in the word list. You have a single word chosen randomly from that list and you only need to worry about the characters in that word

char[] characters = randomString.toCharArray();

or you can dispense with the array and check any character with

randomString.charAt(0)

for any position 0 to length-1.

majestic0110 commented: A relentless helper!! +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

telekinesis has been demostrated many times througout time go and see for your self there are many famous psychic out there.view all the articles in mytelekinesis.com

Ok enough plugs for that ridiculous site.

i am not asking you to believe me.

That's good. At least you are being realistic on one point.

decide for yourself

Done. You're delusional.

Salem commented: That works for me :) +17
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Here's an article that describes the separation and interaction as it pertains to Swing apps:
http://www.javaworld.com/jw-04-1998/jw-04-howto.html

peter_budo commented: Another 100% score for you, great link +8
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Plzz solve my problem.........
@JavaAddict-- look through it,plzzzzz

"Plzz" is not a word. Please have the consideration to use proper English (at least as much as possible if your English is limited) if you are requesting help. Demanding help in bold text with gibberish words is just plain rude and not likely to get much help.

VernonDozier commented: I agree. +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Yes, focus issues can be a pain with key listeners. The InputMap and ActionMap make it easier to handle this. Try using this instead of the KeyListener.

private void launch() {
    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
      KeyStroke.getKeyStroke("R"), "reset");
    
    getRootPane().getActionMap().put("reset", new AbstractAction() {
        public void actionPerformed(java.awt.event.ActionEvent e) {
            System.out.println("reset");
        }
    });

    setBounds(100, 100, 300, 300);

    add(new JButton("hi")); //here is the perp

    setVisible(true);
}
TheWhite commented: great post! +1
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

There is no paintComponent() method on JFrame, which is why it is not being called from repaint(). There is a paintComponents() method that paints all of the child components in the container by calling paintComponent() on each of them.

Because JFrame is a top-level container, you have to override paint() instead of paintComponent(). Be sure that you call super.paint(g) before your custom code so that everything else get's rendered properly. Your code will work with the following method

public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D)g;
        clock = new Clock(minuteY, hourY, hourX, minuteX);
        clock.draw(g2);
    }
VernonDozier commented: Good post. +2
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Well, tech is an ever changing subject - seems only right that it wouldn't stay in the same place long :P

majestic0110 commented: hehe +2
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

You can do whatever you want when the mouse enters or leaves the button

jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseEntered(java.awt.event.MouseEvent evt) {
        jButton1.setBackground(Color.GREEN);
    }
    public void mouseExited(java.awt.event.MouseEvent evt) {
        jButton1.setBackground(UIManager.getColor("control"));
    }
});

or to just underline

jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
    Font originalFont = null;

    public void mouseEntered(java.awt.event.MouseEvent evt) {
        originalFont = jButton1.getFont();
        Map attributes = originalFont.getAttributes();
        attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        jButton1.setFont(originalFont.deriveFont(attributes));
    }

    public void mouseExited(java.awt.event.MouseEvent evt) {
        jButton1.setFont(originalFont);
    }
});
jasimp commented: Is there anything you don't know? +7
sukhpalsingh31 commented: it is nice way to change text attributes +0