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

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

I suspect it was merely an oversight and needs to be corrected on that page.

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 see the same behavior occasionally with Firefox on threads with absolutely huge code posts.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

The Swing Timer is great for a lot of things. It just depends on your expectations of precision. The piece to keep in mind with them is this part from the api doc

Although all Timers perform their waiting using a single, shared thread (created by the first Timer object that executes), the action event handlers for Timers execute on another thread -- the event-dispatching thread. This means that the action handlers for Timers can safely perform operations on Swing components. However, it also means that the handlers must execute quickly to keep the GUI responsive.

If a handful of milliseconds or even a half-second perhaps don't have much impact on the operation you are performing, say like updating a GUI text field or repainting a graph or some such, the thread timing is of no real consequence. If more accurate timing is needed, or in your case constant accumulation of a time value over many firings of the timer, then the uncertainty in execution time can become a concern.

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

In Windows, ">" is used to redirect output. The command below will send the standard output (stdout) of "SomeProgram" to a file named "out.txt"

java SomeProgram > out.txt

You can find more information on Windows command redirection here: http://www.microsoft.com/technet/archive/winntas/deploy/prodspecs/shellscr.mspx#EIIAE

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Well, you could pipe the command line output directly to a file with just the OS syntax, but if you want your program to do the file writing just add use a second arg as the the output file path and use a BufferedWriter to write the output similar to this

if (args.length<2){
    System.out.println("Usage: <YourParserClass> inputFile outputFile");
    System.exit(1);
}
File inFile = new File(args[0]);
File outFile = new File(args[1]);

// ... your operations here (including args validation)
// then write it out with BufferedWriter
try {
    BufferedWriter out = new BufferedWriter(new FileWriter(outFile));
    while ( stuffToWrite ){
        out.write( stuff );
        out.newLine(); // If you need to...
    }
    out.close();
} catch (IOException e) {
    e.printStackTrace();
}
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Why not find out for yourself? Run those lines (well, check your syntax before you do, because it's incorrect and "end;" isn't a valid statement) with System.out.println() calls after the operations and see what you get.

Your own computer will give you answers to questions like this much quicker and more accurately than anyone on the net.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Use Integer.parseInt(java.lang.String,int) with a radix of 16 if you need to convert the hex string back to an int.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Correct. You aren't processing all of the text within the line, you are merely looking at one location and then moving on to the next line.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Horizontal wheel scrolling currently it isn't supported, though it's in a request for enhancement: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6315717

You would need to write JNI code for it for the time being.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Sounds like a reasonable assumption. So now step through the code and determine why that scanner has not been initialized when you need to call it.

Consider that your read() method doesn't actually process anything. It just set's the scanner reference. You only call getWordCount() etc after read() has thrown an exception. Perhaps you should let getWordCount() and the other getX methods just return the current count values from the class and move the code that counts those things into countWords(), countX() methods and call those methods within read().

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

A couple of System.out.println() statements at a few key points could probably illuminate exactly what it is trying to copy where in short order. If you are using an IDE with a debugger, stepping though would be even faster.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Well, those NullPointerExceptions tell you the variable that was null and the line it occurs on. Have you looked at those locations and tried to figure out why the variable is null when you use it?

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Right-click is easy to handle

jButton1.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent e){
        JOptionPane.showMessageDialog(null,"Right-click stuff");
    }
});

Changing the button select color is easy if you are wanting to change it for all buttons in your program - even the ones that appear on dialogs and such. For that you can set "Button.select" property in the UIManager properties

UIManager.put("Button.select", Color.BLUE);

If you want only specific buttons to have the different selected color, you'll have to install your own button UI delegate that extends BasicButtonUI and override the

protected void paintButtonPressed(Graphics g, AbstractButton b)

method and perhaps delegate all other operations to the current look and feel ButtonUI, which may get tricky if you aren't used to pluggable look and feel UI delegation model. There is a complete custom ButtonUI implementation here: http://www17.homepage.villanova.edu/william.pohlhaus/is/doc/Java%20Look%20and%20Feel.htm#_Toc49238503 if you want to wade through it.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

The scanner that you are initializing in the read() method is not the same one the rest of the class is using. You have declared a new Scanner with the same name that is local just to that method

public void read(Scanner console) throws FileNotFoundException
   {
       String input = console.next();
       FileReader reader = new FileReader(input);
       [B]// This is not the same as your class-level "in" variable[/B]
       [B]Scanner in = new Scanner(reader);[/B]

   }
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

Just run it like any other java file, from either the right-click menu or the Run menu. Netbeans will start it in the Applet Viewer.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

All of the above suggestions are valid and using a regex pattern is another option. Regex will allow a pretty complex input string to be validated rather simply.

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

Not really sure why you are getting that behavior. Your writeToLog() code wrote a StringBuffer with newline characters in it to multiple lines just fine here in a tiny test program.

Are you viewing the file with an editor that's okay with just linefeeds or does it expect carriage return and linefeed pairs?

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

If you want reasonable answers from adults, you need to make the effort to communicate like one.

Do you want career advice from teens only?

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

You only need to know failure or success now. And then later you'll need to know something else and after that something else will come up...
Just start with static final int constants for those return code from the start and even if you don't need to add more, reading this

System.exit(PROCESS_FAILURE);

is a lot clearer than

System.exit(2);
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Be sure to define named constants for any error codes you plan on returning and use those instead of the int values. You don't want to to have to go searching through code looking for '16' to figure out what happened with the code.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Sure, you can return any int you want from System.exit() and the convention is that a non-zero value is abnormal termination. You can return a specific int for any condition you wish to pass back to the script and report the specific problems or take further action based on that info.

I would recommend a highest-level catch for Throwable and reserve a specific int return code for that. If you hit that catch block, something blew up that all of your other handlers failed to address. You probably want to capture the stack trace and cause information for that Throwable and log it to an error log file.

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

can anyone give me another solution?

Why would they? You haven't explained what you have tried, what problems you encountered, your thoughts on potential solutions, or anything demonstrating any effort on your part. Programming involves thinking for yourself and "give me another solution" certainly doesn't imply that you have done any of that.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Technically none of those will work as written, but your original is only wrong by one detail

MySuperType mytype = null;
if (sub_type) {
     mytype = new MySubType (); // this is fine
     mytype.setD(4); // these will fail to compile
     mytype.setE(5);
} else {
     mytype = new MySuperType (); 
}

mytype.setA(1);
mytype.setB(2);
mytype.setC(3);

If your variable is of MySuperType, then you can only call MySuperType methods on it. To call MySubType methods you will need to cast to MySubType for those calls, like so

MySuperType mytype = null;
if (sub_type) {
     mytype = new MySubType (); 
     ((MySubType)mytype).setD(4); // just fine
     ((MySubType)mytype).setE(5);
} else {
     mytype = new MySuperType (); 
}

mytype.setA(1);
mytype.setB(2);
mytype.setC(3);
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Returning results whether they match or not defeats the entire purpose of regex. If you want to split input into groups, you obviously have an idea as to how you want that data broken out. Those decisions drive the design of those capturing group patterns. They can be very broad or very narrow, but matching some pattern within the input has to drive the process of extracting groups.

There are plenty of tutorial on using regex:
http://www.google.com/search?q=regex+java+tutorial&btnG=Search&hl=en&sa=2
but it still always comes down to some trial and error to tweak the pattern to your needs.

If you can post a specific example of your input and what you are trying to capture from it, perhaps we can give you some specific pointers on it.

I've posted a small regex testing form here: http://www.daniweb.com/forums/post392585-8.html that I use sometimes to test and tweak patterns. It's pretty limited in it's intent, but perhaps you may find it useful in playing with your patterns and capturing groups.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Then ask for explanation on the point that is confusing you rather than asking for direct corrections to your code. You are the one studying and if you actually want to learn the material then you need to make the effort to clarify the points that you are having problems with.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Most of the example I can find use a small inner class for the Authenticator, such as

private class SMTPAuthenticator extends javax.mail.Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
           String username = SMTP_AUTH_USER;
           String password = SMTP_AUTH_PWD;
           return new PasswordAuthentication(username, password);
        }
    }

The full example is here: http://www.rgagnon.com/javadetails/java-0538.html

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

They can share the same UndoableEditListener. Example

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;


public class UndoDmeo extends javax.swing.JFrame {
    private javax.swing.JTextField txt1;
    private javax.swing.JTextField txt2;

    final UndoManager undo = new UndoManager();

    final UndoableEditListener editListener = new UndoableEditListener() {
        public void undoableEditHappened(UndoableEditEvent evt) {
            undo.addEdit(evt.getEdit());
        }
    }; 
    
    public UndoDmeo() {
        initComponents();
        getRootPane().getActionMap().put("Undo",
          new AbstractAction("Undo") {
              public void actionPerformed(ActionEvent evt) {
                  try {
                      if(undo.canUndo()) {
                          undo.undo();
                      }
                  } catch(CannotUndoException e) {
                  }
              }
          });
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
           KeyStroke.getKeyStroke("control Z"), "Undo");
        
        txt1.getDocument().addUndoableEditListener(editListener);
        txt2.getDocument().addUndoableEditListener(editListener);
    }

    private void initComponents() {

        txt1 = new javax.swing.JTextField();
        txt2 = new javax.swing.JTextField();

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.FlowLayout());

        txt1.setPreferredSize(new java.awt.Dimension(100, 20));
        getContentPane().add(txt1);

        txt2.setPreferredSize(new java.awt.Dimension(100, 20));
        getContentPane().add(txt2);

        pack();
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UndoDmeo().setVisible(true);
            }
        });
    }
}
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Well, if that action listener is attached to a button, then the source will be that button and has nothing to do with the component that you want to act upon. So I don't think you really want to call paste on that anyway. I was merely addressing the casting problem.

You may want to take a look through some of the tutorial on implementing copy and paste: http://java.sun.com/docs/books/tutorial/uiswing/dnd/textpaste.html

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

From what I can tell, JCreator has build capabilities that should allow you to create the jar within the IDE. After you have learned to create it from the command line (which you definitely should learn to do), you should also learn how to do it with the IDE build capabilities.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

You need to cast e.getSource() to an appropriate type that implements the paste() method.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Read the API doc for ArrayList.add(int,E) It states that will be thrown if index < 0 or index > size(). Your error message gives that information to you as well. How can you insert an element at index position 1 when size is 0? The indexes are zero-based, so you must insert the first element... (your answer here)

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Please find the below code which might solve your problem:

Giving the answer to the exam question does nothing to promote active thought on the problem. Hints and suggestions, rather than canned solutions, are more appropriate.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Take a look at the Map.keySet() method. It will return a Set of the keys in the map. A for-each on that Set will allow you to compare the key value easily and Map.put(key, value) will replace the value if key already exists in the map. You should be able to implement your method pretty easily with that info.

Also, on "iii", you may want to look at the enclosures you used around the method parameters. Do those look right for a method call?

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Look at this loop and walk through each iteration in your head or write down the values for one or two iterations and I think you will see the problem

for(i = 0;i <=(i-1);i++)
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

round() returns a long if you pass it a double, which your calc is doing. You can just cast that to an int.

Array1[size]= (int)Math.round (Math.random()*100);
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Ok, 2 main problems with the method that creates your array - see comments in the code belowe

int[] Array1= new int[size];
        // you are changing 'size' in this loop
        // use a new variable in the loop
	[B]for(size = 0;size <=(size-1);size++)[/B]
	{
	    // casting Math.random() to an int will always yield zero
           [B]Array1[size]=(int)Math.random();[/B]
	}

If you need a random number between 0 and X, use Math.round(Math.random()*X).

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

The location of the component within the cell(s) is affected by the anchor. Depending upon the .fill setting, it will also affect the direction in which components expand to fill available space in conjunction with the weightx and weighty properties.

GridBag does take some experimentation to get comfortable with how all of those properties work together. As you have already discovered, grouping related components into their own panels and them placing those panels into other containers makes managing those layouts much easier. Also, sometimes placing a "spacer" blank label into the grid to absorb "dead" space can be helpful if you just can't get certain areas to stay put while others expand.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Try giving the comment text area a grid width of 4, fill both, and weightx/y of 1.0. Place the button panel in the fifth column. Here's an example of that layout that might help

public class GridBagFrame extends javax.swing.JFrame {

    public GridBagFrame() {
        initComponents();
    }

    private void initComponents() {
        java.awt.GridBagConstraints gbc;

        panDetail = new javax.swing.JPanel();
        panTime = new javax.swing.JPanel();
        panTemp = new javax.swing.JPanel();
        panTank = new javax.swing.JPanel();
        panTimePoint = new javax.swing.JPanel();
        scrollComment = new javax.swing.JScrollPane();
        txaComment = new javax.swing.JTextArea();
        lblComment = new javax.swing.JLabel();
        btnQuit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        panDetail.setBorder(javax.swing.BorderFactory.createTitledBorder("Detail"));
        panDetail.setMinimumSize(new java.awt.Dimension(120, 60));
        panDetail.setPreferredSize(new java.awt.Dimension(120, 60));
        gbc = new java.awt.GridBagConstraints();
        gbc.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gbc.anchor = java.awt.GridBagConstraints.WEST;
        getContentPane().add(panDetail, gbc);

        panTime.setBorder(javax.swing.BorderFactory.createTitledBorder("Time"));
        panTime.setMinimumSize(new java.awt.Dimension(120, 60));
        panTime.setPreferredSize(new java.awt.Dimension(120, 60));
        gbc = new java.awt.GridBagConstraints();
        gbc.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gbc.anchor = java.awt.GridBagConstraints.WEST;
        getContentPane().add(panTime, gbc);

        panTemp.setBorder(javax.swing.BorderFactory.createTitledBorder("Temp"));
        panTemp.setMinimumSize(new java.awt.Dimension(120, 60));
        panTemp.setPreferredSize(new java.awt.Dimension(120, 60));
        gbc = new java.awt.GridBagConstraints();
        gbc.gridx = 2;
        gbc.gridy = 0;
        gbc.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gbc.anchor = java.awt.GridBagConstraints.WEST;
        getContentPane().add(panTemp, gbc);

        panTank.setBorder(javax.swing.BorderFactory.createTitledBorder("Tank"));
        panTank.setMinimumSize(new java.awt.Dimension(120, 60));
        panTank.setPreferredSize(new java.awt.Dimension(120, 60));
        gbc = new java.awt.GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gbc.anchor = java.awt.GridBagConstraints.WEST;
        getContentPane().add(panTank, gbc);

        panTimePoint.setBorder(javax.swing.BorderFactory.createTitledBorder("Time Point"));
        panTimePoint.setMinimumSize(new java.awt.Dimension(120, 60));
        panTimePoint.setPreferredSize(new java.awt.Dimension(120, 60));
        gbc = new java.awt.GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gbc.anchor = java.awt.GridBagConstraints.WEST;
        getContentPane().add(panTimePoint, gbc);

        txaComment.setColumns(20);
        txaComment.setRows(5);
        scrollComment.setViewportView(txaComment);

        gbc = new java.awt.GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 4;
        gbc.fill = java.awt.GridBagConstraints.BOTH;
        gbc.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        getContentPane().add(scrollComment, gbc);

        lblComment.setText("Comments:");
        gbc = new java.awt.GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 4;
        gbc.fill …
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Alex is correct. Generics became available with 1.5. And 1.2 is way too old to be using for anything these days.