Swing Handling..

Where do i find the documents regarding the event handling mechanism in the swing framework. What i want basically is how is the event is generated and how is the event propagated from components to containers containing it.
How if i have to trap the keyboard events in the JFrame level, if the user is typing inside a textbox placed inside the panel in that JFrame.

if you want to trap key events in the frame while the user types in a textfield, then you want to look up info on keyboard bindings.
http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html
But if you want general event handling...
http://java.sun.com/docs/books/tutorial/uiswing/events/index.html

Similar Messages

  • How does SWING handle HTML in Tabs (labels, etc)

    Hello,
    I've got a class ("UnderlinedTabbedPane") that extends JTabbedPane and (you guessed it!) underlines the current selection. It does this by just changing the title to <html><u>[title]</u></html>.
    All well and good.
    The trick is that when our customers use a screen reader, this reader speaks out "Title left-slash html greater." I've played around with the accessibility framework and accessible context (which never gets any HTML put into it) but the screen reader kept at it.
    So then I just changed the title to "<html><u>[title]."
    Sure enough, that worked. The next tabs (and other items) don't underline, and the reader is happy. Is SWING just appending a </html> onto my title (so that I'd get two of them, which may be what the screen reader was keying off)? What's going on under the hood with HTML labels?
    Thanks

    Ok, got it. So i´ll answer it myself – of course html and all assets will be integrated if you import your html-folder as an article.
    So, next question – it appears that DPS can´t display .php-files, especially something like this <?php include("menu.html");?>
    won´t be displayed correctly. Any hints on that topic?
    Thanks,
    André

  • Can swing handle Tab Character?

    I output a Message Box using swing like this:
    String s = new String("Sun \tMon \tTue \tWed \tThu \tFri \tSat\n");
    JOptionPane.showMessageDialog(null, s, "The Date!", JOptionPane.PLAIN_MESSAGE);But seems like it cannot print the Tab Character.

    JTextAreas can read tab characters, you might try
    JTextArea textArea = new JTextArea("Sun \tMon \tTue \tWed \tThu \tFri \tSat\n");
    JOptionPane.showMessageDialog(null, textArea, "The Date!", JOptionPane.PLAIN_MESSAGE);

  • Generic error/exception handler

    Well guys, I think I got a challenge for you: I have been thinking for some time about the idea of having a generic error handler for my applications. It's one of these things you should just have: In large GUI apps you usually try to catch all exceptions and display some sort of nice error dialog telling the user what went wrong and what he has to do now. However, there are runtime errors that one can't foresee. These might be bugs, sure, but they happen, so there should be a way of dealing with them. For example, let's say there is a NullPointerException. The clean way would be to display a message box saying something like "Bug!" and giving the user the chance to save his work (or do that automatically). However, this does not seem to be possible. Sure, I could surround every method code with a try { ... }catch(Exception e) and display the dialog, but that seems rather tedious. Does anyone know a better way? Like a common error handling method that is always called when there is an uncaught exception. I dunno, but my IDE JBuilder has something like that, because it is able to stop at "all uncaught exceptions". Any suggestions?
    Thanks guys, or do we have to file a RFE???
    Filip Rindler

    Well, that doesn't work for GUI apps as their main method is done after initializing and all other work is done by the event dispatch thread that is responsible for receiving OS messages (such as mouse motion / clicked / ...). Then this thread calls the event listener methods of registered listeners. It's actually a little more complex how AWT/Swing handles things, but that's the general concept and it is the core of the problem as well: I cannot change any of the event dispatch code (it's deep down in the AWT), so therefore I cannot catch any exceptions there. But maybe there's a hook...

  • Rendering fails, but no error message is provided.

    Hello, I'm encountering a very strange behavior of Swing. I have an application (all used components are Swing) using Java3D (but I don't think that would cause my problems).
    The GUI renders fine most of time, but sometimes (almost randomly) some JPanels are not rendered properly - it looks like just eg. their top and left 10% are rendered and then this small piece is repeated over the whole JPanel. I don't even know if it is only the problem of JPanels. This description wouldn't say you much, so I rather provide some screenshots.
    A normal look on the GUI - http://www.ms.mff.cuni.cz/~peckam/share/swing_rendering_error_good.png
    The GUI with the error - http://www.ms.mff.cuni.cz/~peckam/share/swing_rendering_error_bad.png
    I am able to raise this behavior explicitly by throwing an uncaught exception in my swing-handling code.
    What is worse, sometimes it happens without an uncaught exception (but always it is in response to some user action - selecting a value in combobox, pressing a button or so). I've searched all my code for some blocks that could catch an exception and not write it out to the console, but no such place is in my code. So I know my code doesn't throw any uncaught exceptions.
    Maybe the problem could be in a library I use, I don't know.
    I've even tried to add a uncaught exception listener to both Thread and the EDT, but no exception was written out.
    I'm lost in debugging this, so please help me finding some good start points to find the cause of this problem. Thank you all very much.

    Hello,
    Thanks for the info about Java 3D.
    Andrew Thompson wrote:
    Ensure (...) The GUI is updated on the EDT. Thank you for forcing myself into the unpopular work. That was it.Great. Remember it (that's a classic).
    I now execute as much code on EDT as reasonable and I haven't encountered this error since then. But due to its randomness (...)To make things clear, only code that accesses Swing widgets and their models should run on the EDT, but I think that's what you were implying.
    I'm more concerned by your as much as reasonable . If you meant in terms of, the cost it takes to fix all the code, you should estimate it and plan to do it anyway. As you noticed, the effects of incorrect thread management in Swing are unpredictable, and may, and certainly will, appear sooner or later, in a situation that just escaped your testing, or that stems from a specific race condition.
    Since you haven't frowned at Andrew's warning, you're probably aware of that, but if you aren't, you should really take a look at the tutorial about concurrency in Swing (http://download.oracle.com/javase/tutorial/uiswing/concurrency/), to know the reasons, and the recommendations, as to how to write correctly threaded Swing programs.
    I reserve the option to reopen this thread if it shows again some time later. But I hope it is fixed ;)Fix your non-EDT-aware code first :o)
    And just a note about the form, if you come back with a different problem (even though it is likely due to improper threading), open a new topic instead, and reference this one.
    Much luck.
    J.

  • JButton shows depressed state in 1.4.2 under Windows l&f

    We have an application that is showing a pressed state on a JButton that we previously did not have. Currently this is happening under the Windows look-and-feel.
    We don't want that pressed look on particular buttons, but do want to keep the rest of the look-and-feel properties.
    Anyone know how to turn that off on individual JButton objects?

    You'll have to ask Microsoft why they've designed it this way. The default visual style for XP is called Luna and it contains a bunch of different images for the various widgets. For buttons, they have different images for the normal/rollover/pressed/disabled/default states. The thing is that they provide a different set of these images for toolbar buttons as compared to other buttons. In Luna, the image for the normal toolbar button state is blank.
    The company TGTSoft makes a product called XPStyle that allows you to download visual styles from www.themexp.org and use on your desktop. The Windows L&F for Swing tries as much as possible to make these work, but there are still some bugs. This is partly because Microsoft hasn't bothered to document the style mechanism. TGTSoft also has a product called VisualBuilder which allows you to create and edit these visual styles.
    So how is Swing handling this? Use the source, Luke. Look for the method paintXPButtonBackground() in WindowsButtonUI.java. You'll find it in the src tree that comes with j2sdk.
    We may be able to add a flag to control toolbar vs not toolbar painting in 1.5, but I can't promise anything yet.
    Cheers,
    Leif Samuelsson
    Java Swing Team, Inc.
    Sun Microsystems, Inc.

  • MouseMove problem in JPanel

    Hello I am writing an applet and I am calling a class which extends JPanel.
    In the JPanel I am trying to create a rectangle (fillRect) which than I will be able to move using the method mouseMove().
    I have been able to draw the rectangle on the panel which is in the applet but i havent succeded in moving the rectangle with mouseMove().
    Could somebody please show me to implement the mouseMove correctly .

    Here's a sloppy sort of example for you. It could be vastly improved, but it shows you one example of using a MouseMotionAdapter to change the state of your JPanel subclass.
    Basically, you maintain a model - in this case, the location of your rectangle. When you get input from the mouse, you change the model appropriately. Then you need your view to be redrawn to show your new model. In this case, we just call repaint() and let Swing handle it. In other programs, you might have a loop continuously redrawing the view for you (but that's another story).
    Cheers,
    John
    package moop;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import javax.swing.JPanel;
    public class MyPanel extends JPanel  {
         /** the last known location of the corner of our rectangle  */
         private Point cornerPoint = new Point(0,0);
          * Constructor, giving us a chance to add a mouse motion listener.
         public MyPanel() {
              addMouseMotionListener(new MouseMotionAdapter() {
                    * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
                   public void mouseMoved(MouseEvent e) {
                        cornerPoint.x = e.getX() - 10;
                        cornerPoint.y = e.getY() - 10;
                        repaint();
          * Override the default method to draw a rectangle.
         public void paintComponent(Graphics g) {
              // let the superclass do it's stuff first
              super.paintComponent(g);          
              // draw a red rectangle
              g.setColor(Color.red);
              g.fillRect(cornerPoint.x, cornerPoint.y, 20, 20);
    }

  • I downloaded FireFox, but can not Run, "Server not found " displayed

    I downloaded Firefox in Safe Mode (can not download in normal mode, it blocked by IE), when I run it , it displays, "Firefox can not find the server at www.mozilla.com"
    I wanted temporarily tun off the firewall to let Firefox in. I
    contacted my Anti-virus company Tech support, they did not give me an answer. Any solution?
    Greatly appreciate your help!
    C.Y.

    Thanks for the reply.
    We are still not able to figure out the reason, but the problem seems to orignate in the way swing handles repaint() events in JDK version 1.3. (Paint coalescing, see link below...)
    http://java.sun.com/j2se/1.3/docs/guide/awt/enhancements.html#coalescing
    Our application has multiple swing controls. Each control requests data from the model in its paint event. If model does not have the data it in turn opens a http socket connection to the server and gets the data.
    Our guess is that the calls which were previously sequential, are going simultaneously after coalescing was introduced in swing. But it does not explain why it works if client is not on server machine.
    Also, the application does not fail in a consistent manner. In most cases data does not come at all, but sometimes some controls do get the data. (If server and client are running on different machines, controls always get the data.)
    We have ruled out the possibility that the weblogic server is modifying the classpath or any environment variable at startup and resetting them at shutdown.
    We started server on two machines, machine1 and machine2 and opened a client in machine1 which accessed server running on machine2. Everything ran perfectly.
    Any help will be appreciated. We are all ready to handover to QA except for this inexplicible bug :(
    milinddev, can i send you a mail..... ? The posting has your email-address.
    Thanks again

  • Layout management in a JLayeredPane

    hi All,
    I'm working with a JLayeredPane, and having trouble with controlling the layout. It seems that JLayeredPane is designed for its sub-components to have explicitly set sizes and locations. What I want is to have two layers - one panel on the bottom that takes up all the displayable area (re-sizing to fit the window when necessary), and another transparent one on top that does the same. Does anyone know a way to do this?
    Thanks!

    and one of the components is a JLabel that I want to be semi-translucent to the bottom layer. I did this by calling setBackground with a Color that has an alpha valueThe problem is how Swing handles opaque components.
    If you make the child component non-opaque then Swing searches for the parent component and paints it first (so the background is painted) before the child component is painted. Therefore there is no need for the childs background to be painted and you get transparency.
    If the child component is opaque then Swing doesn't need to find the parent component to paint it, since the childs background will just paint over top of it anyway. So when you use an alpha value the parent isn't repainted and garbage may be left behind.
    So you need to keep you label non-opaque and then override the paintComponent() method of the label with code something like the following to force the child to paint its background:
    protected void paintComponent(Graphics g)
         g.setColor( getBackground() );
         g.fillRect(0, 0, getSize().width, getSize().height);
         super.paintComponent(g);
    }Edited by: camickr on May 7, 2008 11:48 PM
    By the way you really should have started a new posting since the second question is unrelated to the first. Also, since you marked the question as answered most people won't bother to read the question again.

  • AWT List or JList ?

    Hi everybody,
    I am using javax.swing for my layout (buttons, textfields,..) but when I try to use JList and add some text to it (lstLog("hi");) I get this error:
    symbol : method add(java.lang.String)
    location: class javax.swing.JList
    lstLog.add("hi");
    1 error
    BUILD FAILED (total time: 0 seconds)
    But I don't get this error if I use another List from AWT, can u explain this to me pleas ? thank you!

    Rkas wrote:
    why not??Concrete answer: because it just doesn't exist, simple as that. Go to the JList API which you can find here and try to find a method called add(...). You won't find it because JList doesn't have this. It does however inherit an unrelated method of the same name from container (see below).
    Theoretical answer: Swing handles things differently than AWT. With Swing all components have a non-GUI model which handle the logic of the component, and for JList that logic is maintaining the data list itself. So the GUI portion of JList doesn't worry about what data it holds, but its model, which usually is a DefaultListModel does worry about this information and can change the information with the appropriate method calls.
    when I insert JList lstLog. in netbeans I get all the methodes of this component!! Yes, and I'm sure that it will display an "add" method, but understand that this method derives from Container (I wonder if NetBeans displays this information), and so has absolutely nothing to do with adding or removing items from a list.
    so what do u mean by "JList doesn't" ??JList itself doesn't. Again, see the API.

  • Swing: when trying to get the values from a JTable inside an event handler

    Hi,
    I am trying to write a graphical interface to compute the Gauss Elimination procedure for solving linear systems. The class for computing the output of a linear system already works fine on console mode, but I am fighting a little bit to make it work with Swing.
    I put two buttons (plus labels) and a JTextField . The buttons have the following role:
    One of them gets the value from the JTextField and it will be used to the system dimension. The other should compute the solution. I also added a JTable so that the user can type the values in the screen.
    So whenever the user hits the button Dimensiona the program should retrieve the values from the table cells and pass them to a 2D Array. However, the program throws a NullPointerException when I try to
    do it. I have put the code for copying this Matrix inside a method and I call it from the inner class event handler.
    I would thank you very much for the help.
    Daniel V. Gomes
    here goes the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import AdvanceMath.*;
    public class MathF2 extends JFrame {
    private JTextField ArrayOfFields[];
    private JTextField DimOfSis;
    private JButton Calcular;
    private JButton Ativar;
    private JLabel label1;
    private JLabel label2;
    private Container container;
    private int value;
    private JTable DataTable;
    private double[][] A;
    private double[] B;
    private boolean dimensionado = false;
    private boolean podecalc = false;
    public MathF2 (){
    super("Math Calcs");
    Container container = getContentPane();
    container.setLayout( new FlowLayout(FlowLayout.CENTER) );
    Calcular = new JButton("Resolver");
    Calcular.setEnabled(false);
    Ativar = new JButton("Dimensionar");
    label1 = new JLabel("Clique no bot�o para resolver o sistema.");
    label2 = new JLabel("Qual a ordem do sistema?");
    DimOfSis = new JTextField(4);
    DimOfSis.setText("0");
    JTable DataTable = new JTable(10,10);
    container.add(label2);
    container.add(DimOfSis);
    container.add(Ativar);
    container.add(label1);
    container.add(Calcular);
    container.add(DataTable);
    for ( int i = 0; i < 10 ; i ++ ){
    for ( int j = 0 ; j < 10 ; j++) {
    DataTable.setValueAt("0",i,j);
    myHandler handler = new myHandler();
    Calcular.addActionListener(handler);
    Ativar.addActionListener(handler);
    setSize( 500 , 500 );
    setVisible( true );
    public static void main ( String args[] ){
    MathF2 application = new MathF2();
    application.addWindowListener(
    new WindowAdapter(){
    public void windowClosing (WindowEvent event)
    System.exit( 0 );
    private class myHandler implements ActionListener {
    public void actionPerformed ( ActionEvent event ){
    if ( event.getSource()== Calcular ) {
    if ( event.getSource()== Ativar ) {
    //dimensiona a Matriz A
    if (dimensionado == false) {
    if (DimOfSis.getText()=="0") {
    value = 2;
    } else {
    value = Integer.parseInt(DimOfSis.getText());
    dimensionado = true;
    Ativar.setEnabled(false);
    System.out.println(value);
    } else {
    Ativar.setEnabled(false);
    Calcular.setEnabled(true);
    podecalc = true;
    try {
    InitValores( DataTable, value );
    } catch (Exception e) {
    System.out.println("Erro ao criar matriz" + e );
    private class myHandler2 implements ItemListener {
    public void itemStateChanged( ItemEvent event ){
    private void InitValores( JTable table, int n ) {
    A = new double[n][n];
    B = new double[n];
    javax.swing.table.TableModel model = table.getModel();
    for ( int i = 0 ; i < n ; i++ ){
    for (int j = 0 ; j < n ; j++ ){
    Object temp1 = model.getValueAt(i,j);
    String temp2 = String.valueOf(temp1);
    A[i][j] = Double.parseDouble(temp2);

    What I did is set up a :
    // This code will setup a listener for the table to handle a selection
    players.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = players.getSelectionModel();
    rowSM.addListSelectionListener(new Delete_Player_row_Selection(this));
    //Class will take the event and call a method inside the Delete_Player object.
    class Delete_Player_row_Selection
    implements javax.swing.event.ListSelectionListener
    Delete_Player adaptee;
    Delete_Player_row_Selection (Delete_Player temp)
    adaptee = temp;
    public void valueChanged (ListSelectionEvent listSelectionEvent)
    adaptee.row_Selection(listSelectionEvent);
    in the row_Selection function
    if(ex.getValueIsAdjusting()) //To remove double selection
    return;
    ListSelectionModel lsm = (ListSelectionModel) ex.getSource();
    if(lsm.isSelectionEmpty())
    System.out.println("EMtpy");
    else
    int selected_row = lsm.getMinSelectionIndex();
    ResultSetTableModel model = (ResultSetTableModel) players.getModel();
    String name = (String) model.getValueAt(selected_row, 1);
    Integer id = (Integer) model.getValueAt(selected_row, 3);
    This is how I got info out of a table when the user selected it

  • Exception handling for eventlistener inner classes in swing application

    Hi,
    This is probably sooo easy I will kick myself when I find out, but anyway here goes...
    I have an inner class thus...
              cmbOffence.addFocusListener(new FocusAdapter() {
                        public void focusGained(FocusEvent e) {
                             cmbOffence_focusGained(e);
                        public void focusLost(FocusEvent e) {
                        try {
                             cmbOffence_focusLost(e);
                        } catch (XMLConfigurationException xce) {
                   });where cmbOffence.focusLost(e) is looking up to a class that throws an exception which should be fatal i.e. the swing app should close. I want to handle this exception gracefully so therefore want to throw the XMLConfiguratinException to the main application class. How do I do this?? I guess this is more of an inner classes question than a swing one per se, but any help would be appreciated.
    Thanks
    Conrad

    I think you're maybe confusing classes and threads. In the typical Swing application the "main" thread finishes after openning the initial window and there really is no main thread to report back to. In fact the dispatcher thread is about as "main" as they come.
    To exit such a program gracefully is usually a matter of cleaning up resources and calling dispose on the main window, which you can perfectly well do from the dispatcher thread.
    I usually wind up with some centralised method to deal with unexpected exceptions, for example as part of my desk top window in an MDI, but it's called from the dispatcher thread as often as from anywhere.

  • Event Handling - Swing Window to Console Switch

    I have a serious problem with an app I am writing - I have a swing 'main menu' system built around a standard JFrame which calls a new instance of another class. This other class takes input from the keyboard and is displayed in the standard console window; i.e Using the standard System.out.print() syntax.
    My problem is the Swing window will not release the input stream to allow the conole to take input from the keyboard. I have implemented inner-classes within the 'main menu's' class for event handling purposes; in this case the mouse-clicks of the menu's JButton components. The problem only manifests itself when the inner-class' event handling code is called - I wrote some test methods to call the console classes code without using the inner-class' and the console works perfectly. It is my conclusion, therefore, that the calling of the console-based method from within the inner-class of the Swing super-class reserves the input for the Swing components, failing to reactivate the console. I have tried creating new InputStream objects but to no avail.
    Does anyone know how to release or terminate the methods within the inner-classes (they are all void / no return type as they implement the ActionListener abstract class)? This, I hope, will return the focus to the console.
    Any advice would be most greatfully received.
    LEC.

    If you were to have your connection object declared so that it could be referenced from anywhere in your class then you could use it in you actionPerformed method. For example:
    public class Test extends JFrame
    &nbsp&nbsp&nbspprivate Connection con = null;
    &nbsp&nbsp&nbsppublic void actionPerformed(ActionEvent e)
    &nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbspMyDetails appmydet = new MyDetails(con, id); //connection, userID
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbspappmydet.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
    &nbsp&nbsp&nbsp}
    &nbsp&nbsp&nbsppublic void setConnection(Connection theCon)
    &nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbspcon = theCon;
    &nbsp&nbsp&nbsp}

  • A doubt in SWING event handling

    Hi all,
    I'm a beginner in JAVA studying SWING. I learned that if we want to handle an event for a event source(say JButton) we should implement corresponding Event Listener(say ActionListener) .
    I also understood that we should register the Listener with that event source.
    With that knowledge I tried this program
    import javax.swing.*;
    import java.awt.event.*;
    public class SimpleGui2 implements MouseListener,ActionListener {
       SimpleGui2 insGui;
       JButton button= new JButton("Click me");
         public static void main(String[] args) {
              SimpleGui2 gui = new SimpleGui2();
              gui.start();
       public void start() {
            JFrame frame = new JFrame();
            //button.addMouseListener(this);   
            //button.addActionListener(this);
            button.addActionListener(insGui);
            frame.getContentPane().add(button);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300,300);
            frame.setVisible(true);
       public void actionPerformed(ActionEvent ae) {
            button.setText("Triggered");
       public void mouseClicked(MouseEvent me) {
          button.setText("I have been clicked");
       public void mouseEntered(MouseEvent me) { }
       public void mouseExited(MouseEvent me) { }
       public void mousePressed(MouseEvent me) { }
       public void mouseReleased(MouseEvent me) { }  
    }but It's is not working as I expected.
    or precisely why when we clicked the actionPerformed/mouseClicked method is not invoked ?
    if i change the same with argument "this" it's working .
    I guess "this" refers to current object (which is also of type SimpleGui2 which implemented ActionListener)
    Can any one please clarify me what happens behind the scenes ?
    Thanks in advance

    first of all, you never initialize insGui. YOu just declare it, and never use it.
    SimpleGui2 insGui;However, you dont need it anyways. As you suspected, using 'this' when you add your actionListener is what you need.
    button.addActionListener(insGui);
    Can any one please clarify me what happens behind the scenes ?Well my professor always said it was 'black magic'. All I know is that you click a button with an event listener, and an event is fired doing whatever you want it to do. For example, if I want my event to print "Hey" then when I click the button, "Hey" is printed. Simple enough eh? You will probably find a better answer using Google though. It's amazing.

  • Swing locks up during event handling of a simple button... bug or feature?

    I have the following code:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    public class Test extends JFrame {
         private static final long serialVersionUID = 1L;
         private JButton button;
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable(){public void run(){new Test();}});
         public Test()
              setSize(200,00);
              setLayout(new BorderLayout());
              JToolBar toolbar = new JToolBar();
              button = new JButton("button");
              button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { button.setEnabled(false);}});
              toolbar.add(button);
              getContentPane().add(toolbar, BorderLayout.SOUTH);
              JPanel panel = new JPanel();
              panel.setPreferredSize(new Dimension(200,10000));
              for(int i=0;i<10000; i++) { panel.add(new JLabel(""+(Math.random()*1000))); }
              JScrollPane scrollpane = new JScrollPane();
              scrollpane.getViewport().add(panel);
              scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              scrollpane.setPreferredSize(getSize());
              scrollpane.setSize(getSize());
              getContentPane().add(scrollpane, BorderLayout.CENTER);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLocationRelativeTo(null);
              setVisible(true);
              pack();
    }This code is lethal to swing: when pressing the button, for no identifiable reason the entire UI will lock up, even though all the event handler is doing is setting the button's "enabled" property to false. The more content is located in the panel, the longer this locking takes (set -Xmx1024M and the label loop to 1000000 items, then enjoy timing how long it takes swing to realise that all it has to do is disable the button...)
    Does anyone here know of how to bypass this behaviour (and if so, how?), or is it something disastrous that cannot be coded around because it's inherent Swing behaviour?
    I tried putting the setEnabled(false) call in a WorkerThread... that does nothing. It feels very much like somehow all components are locked, while the entire UI is revalidated, but timing revalidation shows that the panel revalidates in less than 50ms, after which Swing's stalled for no reason that I can identify.
    Bug? Feature?
    how do I make it stop doing this =(
    - Mike

    However, if you replace "setEnabled(false)" with "setForeground(Color.red)") the change is instant,I added a second button to the toolbar and invoked setEnabled(true) on the first button and the change is instant as well. I was just looking at the Component code to see the difference between the two. There are a couple of differences:
        public void setEnabled(boolean b) {
            enable(b);
         * @deprecated As of JDK version 1.1,
         * replaced by <code>setEnabled(boolean)</code>.
        @Deprecated
        public void enable() {
            if (!enabled) {
                synchronized (getTreeLock()) {
                    enabled = true;
                    ComponentPeer peer = this.peer;
                    if (peer != null) {
                        peer.enable();
                        if (visible) {
                            updateCursorImmediately();
                if (accessibleContext != null) {
                    accessibleContext.firePropertyChange(
                        AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
                        null, AccessibleState.ENABLED);
         * @deprecated As of JDK version 1.1,
         * replaced by <code>setEnabled(boolean)</code>.
        @Deprecated
        public void enable(boolean b) {
            if (b) {
                enable();
            } else {
                disable();
         * @deprecated As of JDK version 1.1,
         * replaced by <code>setEnabled(boolean)</code>.
        @Deprecated
        public void disable() {
            if (enabled) {
                KeyboardFocusManager.clearMostRecentFocusOwner(this);
                synchronized (getTreeLock()) {
                    enabled = false;
                    if (isFocusOwner()) {
                        // Don't clear the global focus owner. If transferFocus
                        // fails, we want the focus to stay on the disabled
                        // Component so that keyboard traversal, et. al. still
                        // makes sense to the user.
                        autoTransferFocus(false);
                    ComponentPeer peer = this.peer;
                    if (peer != null) {
                        peer.disable();
                        if (visible) {
                            updateCursorImmediately();
                if (accessibleContext != null) {
                    accessibleContext.firePropertyChange(
                        AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
                        null, AccessibleState.ENABLED);
        }The main difference appears to be with the KeyboardFocusManager. So instead of using a toolbar, I changed it to a JPanel (so the buttons are focusable). I then notice the same lag when I try to tab between the two buttons. So the problem is with the focus manager, not the setEnabled() method.

Maybe you are looking for

  • How to make use of values in calling program in a badi

    Hi      I have a badi implementation. i need to make use of some values in the program in the BADI. how do i access values in the program in the BADI. Regards, Chaitanya

  • JMS Threads disappear from JNI application

    My application is a combination of C++/FORTRAN/Java which runs on Solaris 5.9. Messages come into the application via a JMS topic (Sonic implementation). I use JNI (JNI_VERSION_1_2) to embed the JVM. I'm able to process incoming messages for a period

  • TS1363 some apps are not opening since my update of ios 7.0.2

    SOME APPS ARE NOT OPENING SINCE UPGRADE TO IOS 7.0.2 APPS CLOSE ON TOUCH

  • Non latin 1 .CSV support ?

    Hello, When I enable .csv export in my reports everything work fine with latin1 languages. For non-latin1 languages (Russian for example) the .csv export contains ¿¿ (BF hex). The APEX application displays the non-latin1 strings correctly. The "Autom

  • Problem with sales order update from MIGO ( using BADI)

    I have written a BADI while doing MIGO, through which I am updating Sales order “Order Quanity”. I am able to update the Quantity successfully in sales order, but I am getting following update termination message which is mentioned below. "Sales Orde