Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

You missed the ! (not) operator in my code to toggle the glass pane on/off. You aren't ever setting it visible :)
Do this

getGlassPane().setVisible( !getGlassPane().isVisible() );
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

You need to add a call to repaint() after you update your coordinates in the KeyListener.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I just added System.out.println() calls in your KeyListener and ran it in both the applet viewer and a web page and they worked fine as long as it had the focus.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

What do you mean by "can't get it to work"? Because your key listener does respond as long as you make sure it has focus (i.e. click in the panel). You can add a call to requestFocusInWindow() in init() if you want to make sure it gets focus without the click.

I couldn't say if any of the other parts work because they reference variables and classes that do not exist in the code you posted. I just commented those out when I ran it.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

So what you really want is something similar to this perhaps? Assuming you have a 2D array "attributeArray" of "Attribute" objects that contain your data

private Attribute getAttribute() {
  int x = [I]promptForX()[/I];
  int y = [I]promptForY()[/I];
  return attributeArray[x][y];
}
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

If you don't ever change x or y, it's going to keep overwriting the same element forever.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

If you are wanting to paint the line over a grid of JButtons, you'll need to create a small component to install as the glass pane (you read about glass pane here). The code to paint the lines will go in the paintComponent() method of that class. Here is a small example of that to give you a start:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;

public class TicTacToe extends javax.swing.JFrame {

    public TicTacToe() {
        initComponents();
        
        // intall the OverlayPane as this frame's glass pane
        setGlassPane(new OverlayPane());
        
        // installing a listener on jButton1 to toggle 
        // the glass pane painting on/off just for an example.
        jButton1.addActionListener(new ButtonListener());
    }

    /** This component will serve as the glass pane overlay to 
     * paint over all of the other components.
     */
    class OverlayPane extends JComponent{
        /** This is an example of painting a line from button1
         * to button9 over the existing components.
         */
        protected void paintComponent(Graphics g) {
            // from center to center of buttons if you want
            // int x0 = jButton1.getX()+jButton1.getWidth()/2;
            // int y0 = jButton1.getY()+jButton1.getHeight()/2;
            // int x1 = jButton9.getX()+jButton9.getWidth()/2;
            // int y1 = jButton9.getY()+jButton9.getHeight()/2;
            
            // from corner to corner of buttons
            int x0 = jButton1.getX();
            int y0 = jButton1.getY();
            int x1 = jButton9.getX()+jButton9.getWidth();
            int y1 = jButton9.getY()+jButton9.getHeight();
            g.setColor(Color.BLACK);
            g.drawLine(x0, y0, x1, y1);            
        }
    }
    
    class ButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            // toggle line on/off
            getGlassPane().setVisible( !getGlassPane().isVisible() );
        }
    }
    
    /** Everything below here is just the code to generate …
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Then basically like the array loop I posted, but you just check against the input and change the values if needed

int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
while ( [I]userInput()[/I] ){
    if (i<min) min = i;
    if (i>max) max = i;
}

Of course, that still leaves it to you to get the input value and check against -1 as you loop.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Well, if they are four individual variables you could use nested min/max calls

int a = 2;
int b = 22;
int c = 3;
int d = 345;
System.out.println(String.valueOf(Math.min(Math.min(a, b), Math.min(c, d))));
System.out.println(String.valueOf(Math.max(Math.max(a, b), Math.max(c, d))));

If they are an array, you could just call Arrays.sort() and pull the first and last, or loop them and find them yourself.

Unless you're doing it in a tight loop, it probably won't make much difference for just 4 values.

Edit: Actually, I wouldn't bother sorting if they are an array. It's just unnecessary overhead. Just loop them

int[] arr = {2,22,3,345};
int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
for (int i : arr){
    if (i<min) min = i;
    if (i>max) max = i;
}
System.out.println("min: "+min);
System.out.println("max: "+max);
jbennet commented: helpful +32
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Huh? That is exactly what you are doing here

envStack.push(envA);

Perhaps you need to restate the question?

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Well of course it does. You set the text to that number. If you want that label to remain the same then use a separate label for the converted value.

stephen84s commented: Oh dear never could have imagined that was his problem +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

And?

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

It works just fine for me as well. The only "disappearing" I could see is that the label will move depending on the length of the value displayed in the "result". That is because you used FlowLayout.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

"Global" is not the same as instance level scoping. Careful about using those terms interchangeably.

Scoping issue aside, I have to wonder why you nine different unrelated arrays to hold the properties of what should probably be a one dimensional array of objects that contain that data?

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Yes, it's possible to "add further functionality" by composing new classes of your own that use those classes internally to extend or alter the functionality (assuming there are not licensing issues). Of course, you do need to understand the API of the other classes if you expect to do much with them, which was s.o.s's point.

If you stop to think on it a moment, you do this any time you write a program with the JDK. You utilize the existing classes in the API to build new ones of your own that offer some intended functionality.

Alex Edwards commented: Very good point =) +4
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Yes, if that component is in a single column it will. If you need it to span across multiple columns, set the gridwidth property to that number of columns.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Weightx and weighty determine how extra horizontal and vertical space is allocated. It column 0 has a weightx of 0 and column 1 has weightx=1.0, then any extra horizontal space will be given to column 1.

You may need to anchor your components to the west as well, if you want them to remain left-aligned within the container.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Have you already read through the entire tutorial on Using the GridBagLayout? The layout you want isn't difficult to achieve, but getting used to the way the constraints work does take some time and experimentation.

For your particular question, try giving the text fields a weightx of 1.0. This will force any extra horizontal space to be allocated to that column.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I would just guess it stems from the fact you created a fixed size buffer image and rendered the red circle on it without anti-aliasing. You then draw that image in paintComponent. The image itself will be unchanged and I don't think turning on anti-aliasing in paintComponent will affect that image.

VernonDozier commented: Pinpointed the problem. +8
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Here's one way you could monitor progress on the tasks. It involves timed polling of the progress of each task.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.ProgressMonitor;

public class ProgressDemo {

    public static void main(String[] args) {
        WorkQueue work = new WorkQueue();
        work.begin();
    }

    static class WorkQueue {

        final int NUM_THREADS = 5;
        ExecutorService execService = 
          Executors.newFixedThreadPool(NUM_THREADS);
        
        int totalThingsToDo = 0;
        int percentComplete = 0;

        public void begin() {
            totalThingsToDo = 100;
            List<LongTask> tasks = new ArrayList<LongTask>();
            
            // create and submit tasks to thread pool
            for (int i = 0; i < NUM_THREADS; i++) {
                LongTask task = 
                  new LongTask(totalThingsToDo/NUM_THREADS, i);
                tasks.add(task);
                execService.submit(task);
            }
            
            ProgressMonitor monitor = new ProgressMonitor(null, 
              "Doing stuff...", "", 0, 100);
            
            // monitor progress until done
            while (percentComplete < 100) {
                int partialProgress = 0;
                for (LongTask task : tasks) {
                    partialProgress += task.getProgress();
                }
                percentComplete = 
                  (int)(partialProgress / (float)tasks.size());
                
                try {
                    // wait one second between progress updates
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
                
                monitor.setNote(percentComplete+" %");
                monitor.setProgress(percentComplete);
            }
            // shutdown the thread pool
            execService.shutdown();
        }
    }

    /** Mock task that does an arbitrarty number
     * of "things" in a random amount of time.
     */
    static class LongTask implements Callable<Boolean> {

        int thingsToDo = 0;
        int thingsDone = 0;
        int taskId=0;

        public LongTask(int thingsToDo, int taskId) {
            this.thingsToDo = thingsToDo;
            this.taskId = taskId;
        }

        public Boolean call() throws Exception {
            boolean completed = false;
            while (thingsDone < thingsToDo) {
                // random pause to simulate "working" 
                Thread.sleep((int)(Math.random() * 3000));
                thingsDone++; …
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Ok, with your method

public void UpdateTransaction(String q1, String q2, String q3, String q4, String q5, Connection con)

what happens when you only want to execute 2 statements or you need to execute 10 statements? Consider using a List as a parameter instead of coding in an arbitrary set of numbered parameters.

Also, you need to make sure you close your statement in the finally block. Always close statements when you are finished with them.

Alex Edwards commented: Yes, I sometimes forget to do that to with Databases @_@ +4
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Regardless of whether the elements have been separated by a split, regular expressions are the easiest way to provide a match pattern for the phone number that allows for the variability that was described.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I'd recommend reading through these tutorials:
http://java.sun.com/developer/technicalArticles/javase/mvc/
http://java.sun.com/developer/onlineTraining/GUI/Swing2/shortcourse.html#DSGUI

It is not the GUI components that you are needing to update in most cases, but their data.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

There is certainly no reason to dispose of a frame and re-display it to update data, and main() should only be called once in a program as an entry point to minimally set up the object(s) your program needs to run.

To update data in a table, update the table model that is bound to that JTable. If you're using a DefaultTableModel, then you can simply call removeRow(int) and it will remove the row entry and fire the appropriate notification event. If you are using your own table model implementation then you will need to handle that yourself.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Hey, thanks, but from exam point of view, what shall i write True or False? From examples it is clear that surely we can add, but it's not recommended, isn't it? So shall i go with option "True"?

You should answer your exam question based upon your understanding of the subject.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I'd try to give an answer, but as a "beginner here at this ho-dunk little forum" I doubt I can offer any insight on the complexities of "REAL Java programming like the pros"...

(Is Princeton giving credit for Maryland State AP coursework now?)

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Vernon, can you post a simple example or two of what determines whether or not the objects blow up? You mentioned that it's not only a matter of the types themselves that determine the result, as in A + B always explodes while A + C never does.

If you can describe the determination of the result a bit more it would help.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Read the section on work queues in the link that I posted above.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

That still involves runtime instanceof checks. I would agree with Narue's suggestion.

Alex Edwards commented: Yeah, I do to! I was hoping my suggestion would be reasonable, though you make a good point. +4
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Perhaps, but again it all depends on the processes, the hardware, how you divide and synchronize the work, etc. There isn't a single global answer there.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I should actually qualify this part a little bit:

Additionally, if you are running on a single processor, starting 10 threads won't make it go faster - it will just have to time-slice the processing of each thread anyway.

If the process is CPU-bound, such as performing a lot of computations or loops, adding additional threads won't offer any improvement and may even make it slower due to the additional overhead of managing the threads themselves (synchronization, context switching, etc.). If the process performs some tasks that are constrained waiting on other resources like IO, multiple threads may offer improved performance even on single processor machines.

This article on thread pools and work queues covers some of these issues:
http://www.ibm.com/developerworks/library/j-jtp0730.html

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Obviously, this thread is a unique and special gem... just glance down to the bottom at the "Similar Threads" list if you have any doubt.
:yawn:

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Chil i just requested some info or ideas if you have any, so tha means you can think and calculate logical stuff.. etc. so if you can't think you shoudn't be posting at the first place

I'm the Java sections which propably means i would like to hear about ideas or projects that may be implemented in Java...I'm just looking for somthing medium skill and propably not in the networks section somethin up to date, i would like to use java applets and learn about them more but i don't have any other interest than that about a specific section. Thank you for your interest.

I don't think you actually understood a thing I said.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

In case you do want to pursue it, start with the Java concurrency tutorial trail: http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

No, you have absolutely no synchronization there and will have all kinds of concurrency problems.

There are a lot of ways to structure what you are wanting to do, but you have to understand some basics about threading first. Additionally, if you are running on a single processor, starting 10 threads won't make it go faster - it will just have to time-slice the processing of each thread anyway.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Typically a Queue is used for that, often a BlockingQueue. Workers take items off the queue as they become available to process. Is there a reason that you need to leave them in a Map?

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

It depends on what is being processed and what information you need to retain. Also, if your keys are just a sequenced index, you don't even need a Map implementation. A List would work fine. You can either mark the object processed or roll them off to another List of processed items.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I can't see any reason that you would want to. It would render the map useless.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Have you used the search feature here? There are a ton of threads just like this begging for a project idea.

Write a program to do something you find interesting. We don't know a thing about your interests or skill set, so how do you figure we're going to pick a project for you? What areas of CS interest you? If you don't know, then why are you in CS in the first place?

If you refuse to take any initiative to think for yourself in CS, you're user name is going to be sadly apt for a long time.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Check the API doc for JOptionPane. The dialogs have several constructors you can choose from depending on how much you want to specify on it. The docs describe the constants you can supply for each of the parameters.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I have no idea how to change supported source version from 1.3 to 1.5 in NetBeans. It was simple to do with IntelliJ IDEA but this IDE has currently certain issues with Sony Ericsson WTK which I'm using.
Does anyone know where to change this setting?

Since you mention ME only runs against 1.4, the option may not be available, but just for the sake of info you would normally set that in the Project Properties dialog Sources node, Source/Binary Format setting.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

If you only want the sound to be played on app-triggered repaints and not system-triggered (like repainting on resizes or other windows being dragged over it), you can override the update() method

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JOptionPane;

public class PaintExample extends java.awt.Frame {

    public PaintExample() {
        initComponents();
    }

    private void doSomething() {
        JOptionPane.showMessageDialog(this, "done");
    }

    private void formKeyPressed(java.awt.event.KeyEvent evt) {
        repaint();
    }

    @Override
    public void paint(Graphics g) {
        // arbitrary long paint process
        int w = getWidth();
        int h = getHeight();
        int reps = 500000;
        g.setColor(Color.BLACK);
        for (int i = 0; i < reps; i++) {
            int y = (int)(i / (float)reps * h);
            g.drawLine(0, y, w, y);
        }
    }

    @Override
    public void update(Graphics g) {
        super.update(g);
        doSomething();
    }

    private void initComponents() {
        setTitle("PaintExample");
        setMinimumSize(new java.awt.Dimension(400, 400));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        pack();
    }

    private void exitForm(java.awt.event.WindowEvent evt) {                          
        System.exit(0);
    }                         

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PaintExample().setVisible(true);
            }
        });
    }

}

Just press a key to trigger the repaint. It will process the doSomething() code after the paint has completed.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

If you don't have an API that you can use for the target program then about the only thing you could try would be the Robot class. There's a tutorial that demonstrates how it can be used to interact with other programs here: http://www.developer.com/java/other/article.php/2212401

It would be a clunky solution at best, but if you have no API nor command line access, it's about the only thing left. Unless, of course, you can hack the underlying data store and write in the field values directly ;)

PoovenM commented: You're just bloody brilliant mate! Thanks for the reply :) +3
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

The compile error is due to the fact that BlockingQueue does not implement the List interface anywhere in it's hierarchy, which is what the SwingWorker requires in the process(List) method. You really only need to specify the type for the List parameter when you override it, because it is called internally by the mechanics of the publish() method.

Since you are publishing String objects, declare your process() method like this

@Override
protected void process(List<String> lines) {
    for (String i : lines) {
        Form.TraceBox.append(i+"\r\n");
    }
}
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

I can't really speak to the rest of your code. I was just looking at the timer operation.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Sorry, I suppose I could have explained that a bit. If you press a key the timer starts. If you keep pressing keys before the 2 second timer expires, nothing changes. If you don't press a key in 2 seconds, the label changes to "Time up!".

It's just a stripped down version of your own code from the first example you posted. You were calling cancel() on the Time, instead of the object that extended TimerTask.

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

In the first version, I think the only problem is that you are calling cancel on the timer, instead of the timekeeping task. I ran this simplified example here and it works just fine.

import java.util.Timer;
import java.util.TimerTask;

public class FrameThread extends javax.swing.JFrame {

    Timer timer;
    TimeKeeping timeKeeperTask = null;
    boolean timerRunning = false;

    public FrameThread() {
        initComponents();
        timer = new Timer();
    }

    private class TimeKeeping extends TimerTask {
        public void run() {
            timerRunning = false;
            jLabel1.setText("time up!");
            System.out.println("Timer expired");
        }
    }

private void formKeyPressed(java.awt.event.KeyEvent evt) {
    //Rest of the function that is not relevant to problem
//        repaint();

    if (timerRunning) // boolean check, if true execute
    {
        System.out.println("Cancel timer");
        timeKeeperTask.cancel();
    }
    System.out.println("Start new timer");
    jLabel1.setText("running");
    timeKeeperTask = new TimeKeeping();
    timer.schedule(timeKeeperTask, 2000);
    timerRunning = true;
    System.out.println("New timer started");

}

    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });
        getContentPane().setLayout(new java.awt.FlowLayout());

        jLabel1.setText("jLabel1");
        getContentPane().add(jLabel1);

        pack();
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrameThread().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    // End of variables declaration

}
peter_budo commented: Thank you for another great example of code :) +10
Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

AudioInputStream.read(byte[]) will read into a byte array buffer.
This example may be of use: http://www.exampledepot.com/egs/javax.sound.sampled/StreamAudio.html