GUI Update

I am a newbie in using Swing. I was written a GUI class and a application. When i run the Gui and click a button on it to start the application program, the gui has no response, only the application is running.
I think i should use thread, but i really don't know how to implement Thread in this case:
public Tx extends JFrame implements ActionListener, WindowsListener, KeyListener, MousListener{
public Tx(){
public void actionPerformed (ActionEvent event){
Object source = event.getSource();
if ( source == start){
Hello hello = new Hello();
// Hello is the class of the application program
I was search other ppl's message posted in this forum, but i don't understand how to use it. Can anyone help me Please?
Regards
Regards

Your best bet is to create an actionListener specifically for the button, using an anonymous inner class. As follows:
JButton myButton = new JButton("Start");
Container contentPane = getContentPane(); // I'm guessing you've done this already.
contentPane.add(myButton); // This too...
myButton.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent event) {
      Hello hello = new Hello();
});You can write one actionListener to catch all events, but if this is the only thing this button is going to do, it's a lot easier to have it in an anonymous inner class like above. This way, if something goes wrong with the button's action, you know exactly where to go to troubleshoot. That's just my personal coding style. I think one ActionListener to catch all events is rather slick, but your button is doing nothing but starting the application. Hope this helps!
James

Similar Messages

  • Making GUI update at correct time

    I'm creating an engine that can display experimental stimuli for my lab working with kids with reading disabilities. I have a GUI which can display the next stimuli in the test. Once the stimuli are displayed, the program does nothing until the user presses a button and a key event is called.
    I'm now trying to get my GUI to play recorded words to the user. Because it's the responsibility of the GUI to display stimuli, the GUI will be the one playing the sound (even though that's not typically thought of as a GUI responsibility). Unfortunately, even though the commands to update the GUI display are placed before the command to play the sound, the GUI does not update until it has finished playing the sound.
    This has nothing to do with the sound itself: if I replace the clip.play() line with a loop that wastes time and spins around for five seconds, the GUI does not update for those five seconds.
    The GUI updates itself the moment the program leaves the setStimuli() method. How can I get it to update itself before then? Commands such as this.repaint() don't appear to work.
    Any thoughts on how to get the GUI to update itself before exiting the method?
    public class TestingEngine {
    public void setStimuli(String[] values) {
       gui.setStimuli(values);
    public class GUI extends javax.swing.JFrame {
    public void setStimuli(String[] values){
           switch (testType){
             case SOUND:
                   String soundImageFile = "Headphones.jpg";
                   ImageIcon soundImage = new ImageIcon(soundImageFile);
                   JLabel soundImageLabel = new JLabel(soundImage);
                   SoundImageJPanel.removeAll();
                   SoundImageJPanel.repaint();
                   SoundImageJPanel.add(soundImageLabel);
                   soundImageLabel.setVisible(true);
                   label_S_Option1.setText(values[1]);
                   label_S_Option2.setText(values[2]);           // <-- nothing has updated yet
                   SoundClip clip = new SoundClip(values[0]);
                   if (clip.isInitialized())                     // <-- this section could also be replaced
                       clip.play();                             // by a time-wasting loop
                   break;
        }      // <-- once program reaches here, GUI finally updates
    }

    Ok, so just for the sake of it, I tried using the Timer method as suggested in the thread you pointed me to. This doesn't do anything, but thinking about it, I don't see why it would. Timer calls repaint() every 50 ms, but, after all, the setStimuli() method also called repaint() before playing the soundclip. If the original call of repaint() didn't do anything, then I don't think that calling it more often would.
    Is there another command that I should be using? In other words, how can I tell my JFrame and JLabels to "UPDATE RIGHT NOW, NOT IN A MINUTE!"? (It would be easier if I were the JFrame's mother...)
    Current version of code, with Timer class:
    public class GUI extends javax.swing.JFrame {
       private Thread refresh;
       public GUI() {
           initComponents();
           refresh = new Timer(this);
           refresh.start();
       public void setStimuli(String[] values){
           switch (testType){
             case SOUND:
                   String soundImageFile = "Headphones.jpg";
                   ImageIcon soundImage = new ImageIcon(soundImageFile);
                   JLabel soundImageLabel = new JLabel(soundImage);
                   SoundImageJPanel.removeAll();
                   SoundImageJPanel.repaint();
                   SoundImageJPanel.add(soundImageLabel);
                   soundImageLabel.setVisible(true);
                   label_S_Option1.setText(values[1]);
                   label_S_Option2.setText(values[2]);           // <-- nothing has updated yet
                   SoundClip clip = new SoundClip(values[0]);
                   if (clip.isInitialized())                     // <-- this section could also be replaced
                       clip.play();                              // by a time-wasting loop (same problem)
                   break;
       }      // <-- once program reaches here, GUI finally updates
       public void callback(){
           repaint();
    class Timer extends Thread
         private Gui parent;
         public Timer(Gui g) {
              parent = g;
         synchronized public void run() {
              while(true) {
                   try{
                       wait(50);
                   }catch(InterruptedException ie) {return;}
                   parent.callBack();
    }

  • Suspending GUI update

    I have an app which runs a background thread. While the thread is running I want to disable various clickable GUI elements. My problem is that the elements all disable rather slowly and it looks funny (they don't all disable simultaneously). Is there a way I can suspend GUI update, set all my elements to disabled, and then force the GUI to update them all at once?

    Well I'm actually doing this:
    @Action
    public Task runSimulation() {
        SimulationTask simulationTask = new SimulationTask();
        // some code to init my Task
        for (JPanel panel : playerPanels) { // playerPanels is a JPanel[10]
            panel.setEnabled(false);
        return simulationTask;
    }So the code to disable the panels runs before the task is even started. I tried adding the disabling code to the doInBackground method of my TaskListener attached to simulationTask but the delay is worse. The panels disable almost simultaneously using the above method but are out of sync just enough to make everything look amateurish and poorly done.
    As a side note this is written using the swing application framework in netbeans. The runSimulation method is attached to a button that runs a pretty CPU intensive task in the background.

  • Great Challenge !! No one is able to Tell Solution ? Dynamic GUI Updation

    Topic: Dynamic GUI Updation on msWindows when user changes Display properties.
    (I post this Question last month and have't got any answer, Is there no way for this ?)
    I want to dynamicly Update my UI on msWindows when user changes Display properties, Like other windows applications.
    i am doing this procedure-
    1.to get windows look & feel-
    UIManager.getSystemLookAndFeelClassName()
    2.To receive Events when when user changes Display properties-
    Toolkit.getDefaultToolkit().addPropertyChangeListener( "win.desktop.backgroundColor" ,new Java.beans.PropertyChangeListener()
    public void propertyChange(java.beans.PropertyChangeEvent e)
    3.To Reflect it in GUI-
    SwingUtilities.updateComponentTreeUI(TOP COMPONENT);
    But it only reflects the Border & Title Bar of My application.
    pls. suggest what can i do ?
    Regards
    Naveen Sharma

    I seem to remember looking at a similar thing in the Java demos that came with jdk1.3. I could be wrong...
    Let me see...
    Aha! Here it is.
    on my pc the path is
    C:\jdk1.3\demo\jfc\Metalworks
    then click on the jar file. The demo allows you to change the background color, font size on the toolbar etc..Another demo Swingset2 allows you to dynamically change the look and feel. I hope this helps. If you don`t have these demos I could always send you the code.
    Regards
    Grahame

  • GUI Update and Threads

    Hello all, I'm new to Java and am having a hard time trying to understand how to implement multi-threading. I've built a simple app with GUI for converting files between encodings. The program works fine but some files take a long time to convert so I want to show the user some status text in the GUI. The conversion function is called from within a button click event, and further from within a loop that cycles through a directory of files to convert. I'm trying to show the name of the file being converted in a label in the GUI, but the label won't update until the button click event finishes, so only the last file converted is displayed.
    I've read through countless examples on this forum and others, and in several online books. I understand the concept of multi-threading and some of the issues surrounding them, but can't seem to grasp the mechanics of getting them set up in code at this point.
    Can anyone provide some coding tips? The code is provided below minus the NetBeans generated layout code. I can provide this also if needed. You'll see some lines commented out in the For loop that I tried but that didn't work.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class EnCon4 extends javax.swing.JFrame {
        //Declare variables and set default values
        String fname="UTF-16";
        String tname="UTF8";
        String infile;
        String outfile;
        /** Creates new form EnCon4 */
        public EnCon4() {
            initComponents();
        private void encodingToListActionPerformed(java.awt.event.ActionEvent evt) {                                              
            tname=(String)encodingToList.getSelectedItem();
        private void encodingFromListActionPerformed(java.awt.event.ActionEvent evt) {                                                
            fname=(String)encodingFromList.getSelectedItem();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            jLabelStatus.setText("Converting From: " + fname + "  To: " + tname);
            jLabelStatus.repaint();
         File dir1 = new File ("."); //Set current directory
         //Create new subdirectory for converted files
         String newDirName = dir1 + File.separator + "Conv"; 
             File dir2 = new File(newDirName);
             if (!dir2.exists()) {
                dir2.mkdir();
             try {
                //Set path to current directory
                File pathName = new File(dir1.getCanonicalPath());
                File[] contents = pathName.listFiles();
                for (File file : contents) {
                    if (!file.isDirectory()) {
                        //Create the converted files
                    //Set variables
                    infile = dir1.getCanonicalPath() + File.separator + file.getName();
                    outfile = dir2.getCanonicalPath() + File.separator + file.getName();
                    //Check file names to exclude converting the java class file
                    if (!infile.endsWith("class") & !infile.endsWith("jar")) {
                            //Print the file name
                            jLabelStatus.setText("Converting file:  " + file.getName());
                            jLabelStatus.repaint();
                            //catch (Exception econ) {
                            //    System.out.print(econ.getMessage());
                            //    System.exit(1);
                            //System.out.println(file.getName());
                       //Call conversion function in a new thread.
                       //Example with static args //try { convert("NamesASCII.txt", "UTF8.txt", "ISO8859_1", "UTF8"); }
                           //Thread t = new Thread(new Runnable() {
                                //public void run() {
                                try {convert(infile, outfile, fname, tname);
                                catch (Exception econ) {
                                    jLabelStatus.setText(econ.getMessage());
                                    jLabelStatus.repaint();
                                    //System.out.print(econ.getMessage());
                                 //System.exit(1);
                            //t.start();
                //jLabelStatus.setText("Conversion complete.");
                //jLabelStatus.repaint();
             catch(IOException econ) {
                jLabelStatus.setText("Error: " + econ);
                //System.out.println("Error: " + econ);
        public static void convert(String infile, String outfile, String from, String to)
            throws IOException, UnsupportedEncodingException {
            // set up byte streams
            InputStream in;
            if (infile != null) in = new FileInputStream(infile);
            else in = System.in;
            OutputStream out;
            if (outfile != null) out = new FileOutputStream(outfile);
            else out = System.out;
            // Set up character stream
            Reader r = new BufferedReader(new InputStreamReader(in, from));
            Writer w = new BufferedWriter(new OutputStreamWriter(out, to));
            // Copy characters from input to output.  The InputStreamReader
            // converts from the input encoding to Unicode, and the OutputStreamWriter
            // converts from Unicode to the output encoding.  Characters that cannot be
            // represented in the output encoding are output as '?'
            char[] buffer = new char[4096];
            int len;
            while((len = r.read(buffer)) != -1)
              w.write(buffer, 0, len);
            r.close();
            w.flush();
            w.close();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new EnCon4().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JComboBox encodingFromList;
        private javax.swing.JComboBox encodingToList;
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabelStatus;
        private javax.swing.JPanel jPanel1;
        // End of variables declaration                  
    }

    There are two key principles here. The first is "remove long-running
    processes from the event dispatch thread". If in doubt, you
    can check with SwingUtilities.isEventDIspatch(). The second is
    "put GUI updates on the event dispatch thread", preferable
    with SwingUtilities.invokeLater().
    Today is my last day at work, so here's a fish:
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    public class EnCon extends JFrame{
        String fname="UTF-16";
        String tname="UTF8";
        String infile;
        String outfile;
        /** Creates new form EnCon4 */
        public EnCon() {
            super("EnCon");
            jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(final ActionEvent ae) {
                    final Thread t = new Thread(new MyRunner());
                    t.start();
            final JPanel container = new JPanel();
            container.add(jButton1);
            container.add(jLabelStatus);
            this.getContentPane().add(container);
            this.pack();
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        private class MyRunner implements Runnable {
            public void run() {
                sendMessage("Converting From: " + fname + "  To: " + tname);
                File dir1 = new File ("."); //Set current directory
                //Create new subdirectory for converted files
                String newDirName = dir1 + File.separator + "Conv";
                File dir2 = new File(newDirName);
                if (!dir2.exists()) {
                    dir2.mkdir();
                try {
                    //Set path to current directory
                    File pathName = new File(dir1.getCanonicalPath());
                    File[] contents = pathName.listFiles();
                    for (File file : contents) {
                        if (!file.isDirectory()) {
                            infile = dir1.getCanonicalPath() + File.separator + file.getName();
                            outfile = dir2.getCanonicalPath() + File.separator + file.getName();
                            if (!infile.endsWith("class") & !infile.endsWith("jar")) {
                                sendMessage("Converting file:  " + file.getName());
                                try {
                                    convert(infile, outfile, fname, tname);
                                    sendMessage("Done");
                                catch (Exception econ) {
                                    sendMessage(econ.getMessage());
                catch(IOException econ) {
                    sendMessage("Error: " + econ);
            private void sendMessage(final String message) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        jLabelStatus.setText(message);
        public static void convert(String infile, String outfile, String from, String to)
        throws IOException, UnsupportedEncodingException {
            // set up byte streams
            InputStream in;
            if (infile != null) in = new FileInputStream(infile);
            else in = System.in;
            OutputStream out;
            if (outfile != null) out = new FileOutputStream(outfile);
            else out = System.out;
            // Set up character stream
            Reader r = new BufferedReader(new InputStreamReader(in, from));
            Writer w = new BufferedWriter(new OutputStreamWriter(out, to));
            // Copy characters from input to output.  The InputStreamReader
            // converts from the input encoding to Unicode, and the OutputStreamWriter
            // converts from Unicode to the output encoding.  Characters that cannot be
            // represented in the output encoding are output as '?'
            char[] buffer = new char[4096];
            int len;
            while((len = r.read(buffer)) != -1)
                w.write(buffer, 0, len);
            r.close();
            w.flush();
            w.close();
        public static void main(String args[]) {
            new EnCon().setVisible(true);
        // Variables declaration - do not modify
        private JButton jButton1 = new JButton("Convert");
        private JLabel jLabelStatus = new JLabel("jLabelStatus");
        // End of variables declaration
    }

  • GUI Update stops

    Hello,
    i'm implementing an application, which permanently updates a TableView and a Label. This works fine in general. But sometimes updating the gui stops, for example if the application was in background and is focused again. Nothing is displayed in the application window in this case (its black or just frozen), but if i manage to find the button positions they react normally.
    Did anyone experienced this before? Do you have any suggenstion?
    I already tried to call Platform.runLater() less often, but that did not solve the problem.
    I also added:
    final EventDispatcher eventDispatcher = myScene.getEventDispatcher();  // the original dispatcher
    myScene.setEventDispatcher(new EventDispatcher() {
    @Override
    public Event dispatchEvent(Event event, EventDispatchChain tail) {
    long millis = System.currentTimeMillis();
    Event returnedEvent = eventDispatcher.dispatchEvent(event, tail);  // let original one handle it as usual
    millis = System.currentTimeMillis() - millis;
    if(millis >= 100) {  // check if it was slow
    System.out.println("[WARN] Slow Event Handling: " + millis + " ms for event: " + event);
    return returnedEvent;
    as suggested somewhere else in the forum. I did not get any "Warnings".

    Adapting the event dispatcher is a strange thing to do.  I wouldn't recommend that.
    I'm not sure why you need Platform.runLater either (you might need it, but nothing in your question indicates you do).
    To get any help you will almost certainly need to provide an SSCCE.
    There are a few jira bugs filed about black screens in JavaFX applications.
    For example:
    RT-25178 Regression: Background of controls becomes black after waking from sleep
    RT-32636 All JavaFX apps stop rendering when coming out of screen lock
    You can search for others at:
    https://javafx-jira.kenai.com
    Whether the bugs apply to your case will depend on your code, environment and what JavaFX version you are using - you will need to check and verify.

  • [WMI] QFE InstalledOn date property differs from GUI "update history", WMI bug?

    Hello,
    When I use get-hotfix (uses WMI under the hood) on a Windows 2012 box to retrieve the Installdate for windows hotfixes, there is a difference between the date Powershell reports and the date visible in the update history GUI.
    http://i.imgur.com/HJVdsY4.png
    The GUI shows an install date of July 11th, where the get-hotfix shows an install date of September 21st.
    The hotfix is installed in July, not in September. it doesn't seem to be a date formatting issue.
    Is this a known issue? if so is there a fix available?
    thanks in advance,
    Sander

    Hello,
    When I use get-hotfix (uses WMI under the hood) on a Windows 2012 box to retrieve the Installdate for windows hotfixes, there is a difference between the date Powershell reports and the date visible in the update history GUI.
    http://i.imgur.com/HJVdsY4.png
    The GUI shows an install date of July 11th, where the get-hotfix shows an install date of September 21st.
    The hotfix is installed in July, not in September. it doesn't seem to be a date formatting issue.
    Is this a known issue? if so is there a fix available?
    thanks in advance,
    Sander

  • Thread.start vs SwingUtilities - GUI update

    Hi
    how come the GUI is not updated ( moving label ) using
            SwingUtilities.invokeAndWait(new AThread(label));when I use
            Thread t = new Thread(new AThread(label));
            t.start();the GUI is updated
    Thanks
    public class Test {
        public static void main(String[] args) throws Exception {
            JFrame frame = new JFrame("test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new FlowLayout());
            frame.setSize(400, 400);
            frame.setVisible(true);
            JLabel label = new JLabel("000000");
            frame.getContentPane().add(label);
            //SwingUtilities.invokeLater(new AThread(label));
            SwingUtilities.invokeAndWait(new AThread(label));
            //Thread t = new Thread(new AThread(label));
            //t.start();
    class AThread implements Runnable {
        private JLabel alabel;
        public AThread(JLabel alabel) {
            this.alabel = alabel;
        public void run() {
            try {
                while (alabel.getY() < 200) {
                    Thread.sleep(50);
                    Point p = alabel.getLocation();
                    double x = p.getX();
                    double y = p.getY();
                    alabel.setLocation((int) x + 1, (int) y + 1);
                    System.out.println( alabel.getY());
            } catch (InterruptedException e) {
            System.out.println("done");
    }Edited by: sc3sc3 on Feb 8, 2008 10:06 AM

    The invokeAndWait call waits for the thread to finish. So until that thread finishes, the event dispatch thread (EDT) cannot update and so you never see any changes to the label until the thread is complete.
    In the second case, the EDT can incorrectly sporadically update the label because they are running concurrently. I say incorrectly here because you are modifying the label outside of the EDT which is an error and can have various unforeseen consequences. If you want to modify the label, you should queue another runnable to the EDT so the update can occur there. Something like
    import java.awt.*;
    import javax.swing.*;
    public class TestLabelEdt {
        public static void main(String[] args) throws Exception {
            JFrame frame = new JFrame("test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new FlowLayout());
            frame.setSize(400, 400);
            frame.setVisible(true);
            JLabel label = new JLabel("000000");
            frame.getContentPane().add(label);
            //SwingUtilities.invokeLater(new AThread(label));
            //SwingUtilities.invokeAndWait(new AThread(label));
            Thread t = new Thread(new AThread(label));
            t.start();
    class AThread implements Runnable {
        private JLabel alabel;
        public AThread(JLabel alabel) {
            this.alabel = alabel;
        public void run() {
            try {
                while (alabel.getY() < 200) {
                    Thread.sleep(50);
                    Point p = alabel.getLocation();
                    final double x = p.getX();
                    final double y = p.getY();
                    Runnable doRun = new Runnable() {
                        public void run() {
                            alabel.setLocation((int) x + 1, (int) y + 1);
                            System.out.println( alabel.getY());                              
                    SwingUtilities.invokeLater( doRun );               
            } catch (InterruptedException e) {
            System.out.println("done");
    }

  • Delayed Gui Update / Observed effect / Timer problem

    Hello-
    I've a small jpanel I wrote that intercepts mouse clicks and performs some logic with them. When used independently on a jframe, it highlights where the user clicked with a red square.
    I have since modified it to use a notification object so that I can tell a gui window when it has received a valid mouse click... but I need still to be able to display the red square and 'pause' for about 500ms before advancing to the next target.
    Currently, when the high level GUI receives a notification of a valid mouse click it immediately goes to the next target. I'd like it to pause for 500ms... but if I use something similiar to Thread.sleep(500) or SwingUtilities.invokeLater the red patch won't show since it still takes time to update .
    So.... suggestions as to how I can 'know' when my panel is presented properly and can pause before moving onto the next one?
    Thanks in advance-
    Jason

    There's a 'target' on the screen consisting of a couple of boxes. When the user selects one, they turn red to notify they've been selected... and then about 500ms later you move onto the next 'target' (different look and feel, same handling).
    Yes I've found out that sleeping and drawing in the same thread doesn't work at all ;)

  • GUI Updating

    Dear All,
    I have a problem with updating values in a gui.
    I have a class with obviously a constructor and my own updateGUI method which is reproduced here. However the elements aren't updating on the gui itself. Can anyone please tell me why?
    public void updateGUI()
              trustRatingValueLabel.setText(tokenTable.getEvaluationAverage());
              upLoadsValueLabel.setText(tokenTable.getNumberOfUploads());
              jLabel1.setText(tokenTable.getNumberOfDownloads());
              ArrayList<String> strings = tokenTable.getStringRepresentation();
              fileListTextArea.setColumns(40);
              fileListTextArea.setRows(strings.size()*3);
              fileListTextArea.setText("");
              for (int loop = 0; loop < strings.size(); loop++)
                   fileListTextArea.append(strings.get(loop) + "\n\n");
         }and here is my constructor
    public StatisticsGUI(TrustService trustService, TokenTable tokenTable)
              super();
              this.trustService = trustService;
              this.trustGroup = trustService.getTrustGroups();
              this.tokenTable = tokenTable;
              this.service = trustService.getService();
              initGUI();
              updateGUI();
              this.setVisible(true);
         }Thanks guys. P.s. - The class extends JFrame

    Does it update the values when you resize the window? Often after changing values you need to get the JFrame to repaint just by calling the repaint() method. When resizing the window the JFrame automatically repaints() the JFrame so it's the easiest way to check.
    Hope this helps,
    Lauren

  • Java GUI updates

    Hey. I'm having issues where elements of my GUI that I am updating are plain not showing or they're flickering on updates rather than running smoothly. Any help would be greatly appreciated. I've included methods that I feel might be of use below.
         public void mouseDragged(MouseEvent event) {
              if(
                        event.getLocationOnScreen().x < 700 && event.getLocationOnScreen().x > 100 &&
                        event.getLocationOnScreen().y > 100)
                   if(oldSource != null)
                        eraseRectangle(oldLocation, oldSource);
                   Point newPoint = calculateRectangle(event.getLocationOnScreen(), event.getSource());
                   drawRectangle(newPoint, event.getSource());
                   oldLocation = newPoint;
                   oldSource = event.getSource();
         public void mouseReleased(MouseEvent event) {
              // REMOVE RECTANGLE
              if(oldSource != null)
                   eraseRectangle(oldLocation, oldSource);
         public void mousePressed(MouseEvent event) {          
              //DRAW RECTANGLE
              if(
                        event.getLocationOnScreen().x < 700 && event.getLocationOnScreen().x > 100 &&
                        event.getLocationOnScreen().y > 100)
                             Point newPoint = calculateRectangle(event.getLocationOnScreen(), event.getSource());
                             drawRectangle(newPoint, event.getSource());
                             oldLocation = newPoint;
                             oldSource = event.getSource();
                             System.out.println(newPoint.y + "fuck!");
        private void drawRectangle(Point locationOnScreen, Object obj){
             ScreenPanel p = (ScreenPanel) obj;
             Graphics g = p.getGraphics();
             g.setColor(Color.RED);
             g.fillRect(locationOnScreen.x, locationOnScreen.y, 50, 500 - locationOnScreen.y);
             update();
        private void eraseRectangle(Point locationOnScreen, Object obj){
             ScreenPanel p = (ScreenPanel) obj;
             Graphics g = p.getGraphics();
             g.setColor(Color.WHITE);
             g.fillRect(locationOnScreen.x, locationOnScreen.y, 50, 500 - locationOnScreen.y);
             update();
        }I realize I've included a lot of code, sorry! Thanks :)

    cmoney wrote:
    So are you suggesting I create a Graphics object at the top of my class and set that graphics object in the paintComponent method and then use that around?oh no, no, no.
    You instead may wish to have a collection such as an ArrayList of Points where rectangles are to be located. Your Mouse Listeners will then change points or add or delete points as needed. The paintComponent will then iterate through the collection drawing the rectangles based on the locations of the Points.

  • GUI Update for JDialog/JFileChooser

    Hello, Howdy, Greets, Yo and anything else I missed!
    Lets see if I can explain this well...
    I have a JDialog open in the background. One of the choices on the JDialog is to open the JFileChooser. Whenever I open the JFileChooser the JFileChooser opens in front of the JDialog (like it's supposed to). Therefore there is some overlap of the JFileChooser on top of the JDialog.
    When exiting the JFileChooser (a directory is selected), The JFileChooser GUI partially closes. It closes everywhere but where it overlaps the JDialog. So, for a few seconds it has the GUI of the JFileChooser ONLY where it overlaps the JDialog on the screen. Then after some processing (doing what it does with the JFileChooser data), it finishes removing the JFileChooser GUI that overlaps the JDialog.
    I want the JFileChooser to completely disappear at the same time. I've tried every variation I can think of, to no avail:
    dialog.repaint();
    dialog.validateTree();
    dialog.validate();
    jfc.hide();
    jfc.updateUI();
    jfc.revalidate();
    jfc.repaint();
    Here's an example:
    int choice = jfc.showDialog(new JFrame(), "Select Directory");
    // Tried everything here to hide/remove the jfc GUI
    if (choice == JFileChooser.APPROVE_OPTION )
      // do what it does with the selected directory
    }This happens on every look and feel, so that's probably not the problem. Any ideas?

    Thanks for the advice on threads. I got it working by doing the following...
          int state = jfc.showDialog(new JFrame(), "Select Directory");
          if (state == JFileChooser.APPROVE_OPTION )
            defaultDir = jfc.getSelectedFile();
            Thread myThread=new Thread()
              public void run()
                // Do my other stuff here
            myThread.start();       
          }

  • Premature GUI update

    Hello. I'm making a game of monopoly. When the game first loads, the main window (JFrame subclass) calls upon the New Game window (JDialog subclass). This new game window allows the players to specify their names and tokens. For this purpose, I've got 8 JPanel subclasses and a JLabel organized in a 3x3 GridLayout (in the center pane of a borderlayout) with the JLabel (containing an image and instructions) in the middle.
    ie:  ***  where an asterisk is an instance of a JPanel subclass
         * *  and the center whitespace is the JLabel
         ***(For those groping about GUI standards: The idea is that the layout of the JPanels represent the positions of the players around conventional board game table. I figured is was more fun than having the instructions at the top of the window, because after all, this is a game)
    I got everything working and I decided to add some eye-candy without going into major CGI work: when the jDialog first opens up, each JPanel would be highlight (background would change colors) one after the other in a clockwise fashion (sort of like lights around a Los Vegas sign). The code for highlighting the JPanels work; I use ComponentAdapter on the JDialog to detect when the window opens. The problem is that the JPanel "animation" takes place after the JDialog border (or insets) is drawn, but before the JDialog background, JLabel, and the other BorderLayout panes are drawn.
    What should I do to make sure the JPanel animation is triggered only after the JDialog is fully drawn?

    Depends on your requirment.
    Your description of requirement is vague.
    If you are going to view the xml file on a JTextArea, you won't need any parser.

  • GUI update problem: button take time to be disabled

    I have a Stop button. In the actionPerformed() method for the button, I disable the button and also some other buttons (using setEnabled(false)) then there are some other codes that include Thread.sleep() method. Then again I enable some other buttons. Problem is the Stop button take time to be disabled. The time exactly equals sec provided in the sleep() method. I tried by puting the button disabling buttons' code in another thread that is called from SwingUtilies.invokeLater() method just before the sleep() method. It is very important to disable some buttons before Thread.sleep() is called. And only after the sleep() method I can enable some other buttons.
    Please help me.

    Hello Experts! I can't hear you. 1) Swing related questions should be posted in the Swing forum
    2) Quit bumping your question, you only posted it 30 minutes ago. People will answer when they have the time.
    Your code in the actionListener needs to be executed in a separate Thread, so that when you invoke the "sleep" method the separate Thread sleeps, not the Event Thread.

  • Binding a component to a property and GUI update

    I have a problem regarding the following code:
    <h:selectBooleanCheckbox
    id="chackBox"
    rendered="false"
    binding="#{BackingBean.newsletter}" />
    <h:outputLabel for="newsletterLabel"
    rendered="false"
    binding="#{BackingBean.newsletterText}" >
    <h:outputText id="newsletterLabel" value="Do you want to subscribe to our newsletter ?" />
    </h:outputLabel>
    before this page is displayed the first time the isRendered value of newsletterText and newsletter is set to true (newsletterText.isRendered(true)) by BackingBeans.getData() method.
    But the components are not displayed.
    If the same method (BackingBeans.getData()) is called by a link on the page the components are displayed then.
    Seams that the isRendered() method only works correct if the page has already displayed at least once.
    Can anyboby explain that behaviour ?

    I have similar issue. The binding didn't rebuinding for select drop down, but it is rebinding for the hyper link.
    The code is like:
    <h:selectOneMenu value="#{userBean.preferedLanguage}" >
    <f:selectItems value="#{languageBean.languageDropdownList}"/>
         </h:selectOneMenu>
    <cc:tabSet id="tabset1" binding="#{tabManagedBean.tabs}" />
    After selecting language, the getTabs() is not called from backing bean. any suggestion?

Maybe you are looking for

  • How do I reduce photo size

    am trying to load my photos onto photobucket and they are bigger than 250kb. how do I reduce them so they load quicker.

  • Forgotten Password

    Embarrassed to say that for the first time in ages I have connected my Blackberry device to my laptop to back up and the password I thought was correct clearly isn't the one. I have tried other favourites but all faied and have now used 4 out of my 5

  • Calendar add question

    hi all ! Im needing to configure a date to be the first day of the next month we are atm. For example if we are now at second of march the date should be for april's first. This is how Im calculating it atm.            String sfechap = ("01" + "/" +

  • Logical Database Reads

    Hi All, Logical Reads = DB Block Gets + Consisten Gets. What are consistent gets? and the difference between DB Block Gets and Consistent Gets.

  • Howto Display Worksheet in IE browser other than thru Portlet/Viewer

    Howto Display Worksheet in IE browser other than thru Portlet/Viewer. We wish to develop some worksheets and display them as BI Dashboards links on our Intranet Home page. Is it possible to host it on Oracle10gAS HTTP server as jsp pages?