Swing trouble

Hi,
I am using javac to compile an applet off the command line, and I am getitng a ton of "cannot find symbol" errors, all that reference swing classes, such as JCheckbox, JRadioButton, JList, etc.
I have the following import statement in my applet:
import java.swing.*;
I don't understand why javac can't find these classes - which I thought were directly packaged under swing???
-Zac

thank you, that was a typo mistake. I have one final (and unrelated) question, concerning a second slew of compilation errors:
Let's say I have 100 JButton's. Here is how I have learned how to set one of those buttons up:
JButton jb = new JButton("My button");
this.add(jb);
jb.addActionListener(this);
In the second line, I am instructing that the current JApplet class should add the button to its interface. In the third line, I am trying to set the current JApplet's ActionListener to the listener for the button.
javac is complaining about all 100 buttons using this implementation, saying that: "addActionListener in javax.swing.AbstractButton cannot be applied to [each of the 100 buttons]."
What does anybody think is going on here?

Similar Messages

  • Troubles with inner classes in swing-panel

    hi,
    I'm having troubles using innner classes as ActionListeners in my swing-panel. I keep getting compile-time errors:
    C:\Java programmer\DocGenerator\ListPanel.java:53: cannot resolve symbol
    symbol : class Actionlistener
    location: class ListPanel.RemoveListener
         class RemoveListener implements Actionlistener {
    ^
    C:\Java programmer\DocGenerator\ListPanel.java:33: addActionListener(java.awt.event.ActionListener) in javax.swing.AbstractButton cannot be applied to (ListPanel.RemoveListener)
              removeButton.addActionListener(new RemoveListener());
    ^
    2 errors
    Here is the source code:
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    class ListPanel extends JPanel implements ListSelectionListener{
         private JButton addButton = new JButton("add");     
         private JButton removeButton = new JButton("remove");
         private JButton resetButton = new JButton("reset");
         private JList list;
         private DefaultListModel listModel;
         public ListPanel(){
              listModel = new DefaultListModel();
              listModel.addElement("nummer1");
              listModel.addElement("nummer2");
              list = new JList(listModel);
              list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              list.setSelectedIndex(0);
              list.addListSelectionListener(this);
              JScrollPane listScrollPane = new JScrollPane(list);
              setLayout(new GridLayout(1,2));
              JPanel buttons = new JPanel();
              buttons.setLayout(new GridLayout(3,1));
    //          addButton.addActionListener(this);
              removeButton.addActionListener(new RemoveListener());
    //          resetButton.addActionListener(this);
              buttons.add(addButton);
              buttons.add(removeButton);
              buttons.add(resetButton);
              list.setBorder(BorderFactory.createLineBorder(Color.black,3));
              add(buttons);
              add(list);
         public void actionPerformed(ActionEvent e){
              System.out.println(e);
         public void valueChanged(ListSelectionEvent e){
         class RemoveListener implements Actionlistener {
              public void actionPerformed(ActionEvent e){
                   int index = list.getSelectedIndex();
                   listModel.remove(index);
                   int size = listModel.getSize();
                   if(size==0){
                        addButton.setEnabled(false);
                   } else {
                        if (index==listModel.getSize())
                             index--;
                        list.setSelectedIndex(index);

    Both of the errors is because Actionlistener is not the same as ActionListener. Note the capital 'L' there!

  • I have trouble with swing tutorial demos

    I 'm trying swing tutorial. I already have downloaded the IconDemo in zip format. Compilation and execution are Ok but the application hasn't show anyimage.
    I have done with other appplication about Icon image, and it occur the same. Can anybody help me?

    in IconDemoApp change this
    private String imagedir = "images/";
    to
    private String imagedir = "../images/";recompile/rerun

  • Swing---JTextPane(a boring trouble---looking forward to answer)

    In the following program the JLabel inherited can'nt be seen when it inserted into the JTextPane, I wander why?
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class AdvancedJTextPane extends JFrame
    JTextPane jtp;
    public AdvancedJTextPane(){
         jtp=new JTextPane();
         this.getContentPane().setLayout(new BorderLayout());
         JScrollPane js = new JScrollPane();
         js.getViewport().add(jtp);
         this.getContentPane().add(js);
         this.pack();
         this.setSize(350, 250);
         this.setVisible(true);
         jtp.insertComponent(new DrawLabel(""));
         this.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    public static void main(String[] args) {
    new AdvancedJTextPane();
    class DrawLabel extends JLabel {
    public DrawLabel(String label) {
    super(label);
    Dimension size = getPreferredSize();
    size.width = size.height = Math.max(size.width,
    size.height);
    setPreferredSize(size);
    protected void paintComponent(Graphics g) {
    g.setColor(Color.lightGray);
    g.drawOval(0, 0, getSize().width-3, getSize().height-3);
    super.paintComponent(g);
    protected void paintBorder(Graphics g) {
    g.setColor(getForeground());
    g.drawOval(0, 0, getSize().width-1, getSize().height-1);
    }

    Here's your culprit:
    jtp.insertComponent(new DrawLabel(""));You need to use something other than an empty string (spaces will work):
    jtp.insertComponent(new DrawLabel("     "));

  • Troubles with Swing Timers

    I am trying to learn how to use javax.swing.timer. I'm simply trying to update a JLabel on an interval. The code I have looks like this:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    class GUI extends JFrame implements ActionListener
    Timer clock;
    JLabel label;
    int numberFrames;
    GUI()
         clock = new Timer(25, this);
         JLabel label = new JLabel("0");
         getContentPane().add(label, BorderLayout.NORTH);
         numberFrames = 0;
         clock.setInitialDelay(0);
         clock.setCoalesce(true);
         clock.start();
    public void actionPerformed(ActionEvent e)
         numberFrames++;
         label.setText("" + numberFrames);
    public class Timed
    public static void main(String argv[])
         GUI window = new GUI();
         window.setSize(100,100);
         window.setVisible(true);     
    Unfortuantely, the ActionPerformed executes only once and throws a NullPointerException whenever it tries to update the label. I also looked at Java's site for learning how to use Swing Timers, but I didn't understand what they were doing when they put in multiple actionListeners.
    Please Help.

    The problem is with variable scoping:
    GUI()
    clock = new Timer(25, this);
    JLabel label = new JLabel("0"); <<<<<<<<<<<<<DONT DECLARE A JLABEL HERE
    getContentPane().add(label, BorderLayout.NORTH);
    numberFrames = 0;
    clock.setInitialDelay(0);
    clock.setCoalesce(true);
    clock.start();
    The JLabel declaration in the constructor means the 'real' JLabel never get initialised, hence the NullPointerException

  • Trouble with focus, swing & keyListener

    can anybody out there help me with this problem, I got stuck with:
    I create a JDialog in a JFrame & would like to add Keylistener to the JDialog as soon as it opens..........but the it doesn't seem to be working....

    Oops! As bbhangale pointed out, my previous post is incorrect. It should read as follows:
    dialog.getRootPane().getInputMap...
    dialog.getRootPane().getActionMap...Actually, I've created MyDialog, an abstract sub-class of JDialog. In it, I over-ride the createRootPane() method and delcare the abstract onDialogClose() method. Here's what that looks like:
    public abstract class MyDialog extends JDialog
       // Implement MyDialog wrappers for all the JDialog constructors
       public MyDialog()
          super();
        * Overriding this method to register an action so the 'Esc' key will dismiss
        * the dialog.
        * @return a <code>JRootPane</code> with the appropiate action registered
       protected JRootPane createRootPane()
          JRootPane rootPane = new JRootPane();
          rootPane.getInputMap( JComponent.WHEN_IN_FOCUSED_WINDOW ).
             put( KeyStroke.getKeyStroke( KeyEvent.VK_ESCAPE, 0 ), "escPressed" );
          rootPane.getActionMap().
             put( "escPressed", new AbstractAction( "escPressed" )
             public void actionPerformed( ActionEvent actionEvent )
                onDialogClose();
          return rootPane;
        * This method gets called when the user attemps to close the JDialog via the
        * 'Esc' key.  It is up to the sub-class to implement this method and handle
        * the situation appropriately.
       protected abstract void onDialogClose();
    }Then, anytime I need a dialog, I sub-class MyDialog and implement onDialogClose() to do whatever I want it to do when the user presses 'Esc'.
    I swear I've been using it for quite some time now and it works beautifully!
    Jamie

  • Having Trouble Closing a JFrame With a Button Click in Swing

    I am brand new to Java so this is probably something really stupid.
    On my main form I have a table displaying records from a database. When you double click a record, it pops up a second form showing the details of that record. You can then edit the data in this second form and click a "save" button which saves the data to the database. I want this button to also close that second form, however in the button click event, the second form variable is null.
    Here is some code showing the basic concept:
    public class SampleForm {
        private JButton  saveJobButton;
        private JFrame frame;
        private JFrame editDetailFrame;
        public static void main(String[] args) {
            SampleForm sample = new SampleForm();
            sample.createMainFrame();
        public void createMainFrame() {
            frame = new JFrame();
            JComponent panel = buildPanel(); 
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.getContentPane().add(panel); 
            frame.pack();
            frame.setVisible(true);
        public void createEditFrame() {
            editDetailFrame = new JFrame();
            editDetailFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            JComponent editPanel = new SampleForm().buildDetailPanel();
            editDetailFrame.getContentPane().add(editPanel);
            editDetailFrame.pack();
            editDetailFrame.setVisible(true);
            editDetailFrame.validate();
    // save button
        private JButton getSaveJobButton() {
            if (saveJobButton == null) {
                saveJobButton = new JButton();
                saveJobButton.setText("Save Job");
                saveJobButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                       .. saves data to database.
                        // here is where I thought the dispose() should go but the editDetailFrame is null at this point.
                        editDetailFrame.dispose();
            return saveJobButton;
        }Any assistance would be much appreciated.

    That handles the NullPointer, but still doesn't close my second Frame. The editDetailFrame should not be null at this point as I am clicking a button on the editDetailFram itself so I think the problem is that I just don't have a reference to the actual object at that point and my variable is just an empty one.

  • Troubles with Swing (repainting/revalidating)

    ok this is a newbie question I will admit...
    I have a JLabel that shows the String.valueOf() an integer.
    I have a JButton that changes the value of the integer displayed by the JLabel.
    (I do know this much works as I watched the button's action listener to the display via System.out.println().)
    I want the label to update the integer display every time the button is pressed.
    I tried putting a repaint() call in the button's Action Listener. Nothing happened.
    I tried insantiating my own RepaintManager(), added the button to the markCompletelyDirty() list, and called paintDirtyRegions() on the button. Nothing happened.
    What am I doing wrong?
    Theory or implementation?
    Is there an easier way to get a "real time" display of my integer?
    help and/or guidence would be greatly appreciated...
    I learned JAVA out of many books (mostly O'Reilly and Wrox) but they aren't really helping at the moment.
    derek

    Having the label display the integer doesn't mean the label will update the value of the integer once its changed. This is because a copy of the integer has been passed to the label. No amounts of repaints will work.
    To update the label you need to explicitly call the setText() method of the Label. Therefore, inside your button's ActionListener, add label.setText(...) after you update the integer.

  • Trouble opening swing Applet in browser

    Hi,
    I am not being able to view an Applet written in Java 2 using javax.* packages on any browser!
    Does anybody know any way to do that please?
    Thanks in advance.

    I did not understand most of the messages the java console shows here.
    Java console message:
    Java Plug-in 1.5.0_06
    Using JRE version 1.5.0_06 Java HotSpot(TM) Client VM
    User home directory = C:\Documents and Settings\Admin
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    o: trigger logging
    p: reload proxy configuration
    q: hide console
    r: reload policy configuration
    s: dump system and deployment properties
    t: dump thread list
    v: dump thread stack
    x: clear classloader cache
    0-5: set trace level to <n>
    java.security.AccessControlException: access denied (java.io.FilePermission queen.gif read)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkRead(Unknown Source)
         at sun.awt.SunToolkit.getImageFromHash(Unknown Source)
         at sun.awt.SunToolkit.getImage(Unknown Source)
         at QueenMoves.init(QueenMoves.java:20)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Exception in thread "thread applet-QueenMoves.class" java.lang.NullPointerException
         at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
         at sun.plugin.AppletViewer.showAppletException(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Any help will be very very much appreciated.
    Thanks in advance

  • Swing Timer issues on a faster machine.

    Hi everyone,
    I'm having some trouble using Swing Timers. I have built a system which uses three javax.swing.Timers, these are as follows:
    timerLeft = new Timer(timerDelay, new ActionListener() {
    public void actionPerformed(ActionEvent evt)
    {if(pathPointerLeft==leftCyclePoints.length) {
    pathPointerLeft=0;
    leftHandX=leftCyclePoints[pathPointerLeft][0];
    leftHandY=leftCyclePoints[pathPointerLeft][1];
    pathPointerLeft++;
    jugglingPanel.repaint();
    timerRight = new Timer(timerDelay, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    if(pathPointerRight==rightCyclePoints.length) {
    pathPointerRight=0;
    rightHandX=rightCyclePoints[pathPointerRight][0];
    rightHandY=rightCyclePoints[pathPointerRight][1];
    pathPointerRight++;
    jugglingPanel.repaint();
    myApp.timerBalls = new Timer(myApp.timerDelay, new ActionListener() {
    public void actionPerformed(ActionEvent evt){
    for(int i=0;i<myApp.ballCycleVector.capacity();i++){
    myApp.ballPoints = (int[][])myApp.ballCycleVector.elementAt(i);
    if(myApp.startAnimatingBall){
    if(myApp.ballPoints[myApp.pathPointerBalls][2]==1 && myApp.transitionDone){
    for(int j=0;j<200;j++) {
    if(myApp.ballPoints[myApp.pathPointerBalls][2]!=1) {
    break;
    myApp.pathPointerBalls++;
    if(lastLocationX==myApp.ballPoints[myApp.pathPointerBalls][0] && lastLocationY==myApp.ballPoints[myApp.pathPointerBalls][1]) {
    myApp.pathPointerBalls++;
    if(myApp.pathPointerBalls!=myApp.ballPoints.length) {
    myApp.ballLocations[0]=myApp.ballPoints[myApp.pathPointerBalls][0];
    myApp.ballLocations[1]=myApp.ballPoints[myApp.pathPointerBalls][1];
    lastLocationX= myApp.ballPoints[myApp.pathPointerBalls][0];
    lastLocationY = myApp.ballPoints[myApp.pathPointerBalls][1];
    } else{
    myApp.pathPointerBalls=0;
    for(int j=0;j<200;j++) {
    if(myApp.ballPoints[myApp.pathPointerBalls][2]!=1) {
    break;
    myApp.pathPointerBalls++;
    if(myApp.pathPointerBalls!=0 && myApp.ballPoints[myApp.pathPointerBalls-1][2]==1) {
    myApp.pathPointerBalls++;
    myApp.ballLocations[0]=myApp.ballPoints[myApp.pathPointerBalls][0];
    myApp.ballLocations[1]=myApp.ballPoints[myApp.pathPointerBalls][1];
    lastLocationX= myApp.ballPoints[myApp.pathPointerBalls][0];
    lastLocationY = myApp.ballPoints[myApp.pathPointerBalls][1];
    myApp.pathPointerBalls++;
    if(myApp.pathPointerBalls==myApp.ballPoints.length) {
    myApp.pathPointerBalls=0;
    if(myApp.pathPointerBalls!=0 && myApp.ballPoints[myApp.pathPointerBalls][2]==0 && myApp.ballPoints[myApp.pathPointerBalls-1][2]==1) {
    myApp.transitionDone=true;
    myApp.jugglingPanel.repaint();
    Apologies if these do not coform to standard coding conventions. When I run these on my home PC (P4 2.56GHz, 512MB RAM, 64MB Graphics) it runs beautifully. The same on a laptop (P3 1.8GHz, 512MB RAM, 64MB Graphics card). However, when I run it on the campus machines (3.20GHz, 1.5GB RAM, 128MB Graphics), the animated display (as controlled by the Timers above) stutters and does not remain in sync. I'm guessing that this is because it is being ran on a faster machine. Could anyone suggest a solution to this problem so that the animation remains in sync for a faster machine, or even suggest another reason why this problem is occuring. This is a very important project and I really need to resolve this issue. Thanks in advance.

    The code you posted means nothing:
    a) it is not readable, since you didn't use the "Code Formatting Tags" when you posted the code
    b) its not executable, so we can't see what it is attempting to do.
    c) we don't know the frequency of event firing
    Obviously a faster machine will be able to repaint Components faster then slower machines.
    I use a 3.3Ghz machine and my TimerAnimation example here seems to keep in sync:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=631379

  • I can't use swing components in my applets

    When I write an applet without any swing components, my browser never has any trouble finding the classes it needs, whether they're classes I've written or classes that came with Java. However, when I try to use swing components it cannot find them, because it is looking in the wrong place:
    On my computer I have a directory called C:\Java, into which I installed my Java Development Kit (so Sun's classes are stored in the default location within that directory, wherever that is), and I store my classes in C:\Java\Files\[path depends on package]. My browser gives an error message along the lines of "Cannot find class JFrame at C:\Java\Files\javax\swing\JFrame.class"; it shouldn't be looking for this non-existent directory, it should find the swing components where it finds, for example, the Applet class and the Graphics class.
    Is there any way I can set the classpath on my browser? Are the swing components stored separately from other classes (I'm using the J2SE v1.3)?
    Thanks in advance.

    Without having complete information, it appears that you are running your applets using the browser's VM. Further, I assume you are using either IE or Netscape Navigator pre-v6. In that case, your browser only supports Java 1.1, and Swing was implemented in Java 1.2. You need to use the Java plug-in in order to use the Swing classes (see the Plug-in forum for more information), or else download the Swing classes from Sun and include them in your CLASSPATH.
    HTH,
    Carl Rapson

  • Please help: RMI and Swing/AWT issue

    Hi guys, I've been having a lot of trouble trying to get a GUI application to work with RMI. I'd appreciate any help. Here's the story:
    I wrote a Java application and its GUI using Netbeans. In a nutshell, the application is about performing searches. I am now at the point where I need exterior programs to use my application's search capabilities, thus needing RMI. Such exterior programs are to call methods currently implemented in my application.
    I implemented RMI, and got the client --> server communication working. However, the GUI just breaks. It starts outputting exceptions, gets delayed, doesn't update properly, some parts of it stop working.... basically hysterical behavior.
    Now take a look at this line within my server class:
    Naming.rebind("SearchProgram", mySearchProgram);
    If I take it out, RMI obviously does not work... but the application and its GUI work flawlessly. If I put it in, the RMI calls work, but the GUI's above symptoms occur again. Among the symptoms are null pointer exceptions which all look similar, are related to "AWT-EventQueue-0", and keep ocurring. Here's just snippet of the errors outputted:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalScrollBarUI.getPreferredSize(MetalScrollBarUI.java:102)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1615)
    at javax.swing.JScrollBar.getMinimumSize(JScrollBar.java:704)
    at javax.swing.ScrollPaneLayout.minimumLayoutSize(ScrollPaneLayout.java:624)
    at java.awt.Container.minimumSize(Container.java:1598)
    at java.awt.Container.getMinimumSize(Container.java:1583)
    at javax.swing.JComponent.getMinimumSize(JComponent.java:1697)
    at java.awt.BorderLayout.minimumLayoutSize(BorderLayout.java:634)
    at java.awt.Container.minimumSize(Container.java:1598)
    at java.awt.Container.getMinimumSize(Container.java:1583)
    at javax.swing.JComponent.getMinimumSize(JComponent.java:1697)
    at java.awt.BorderLayout.minimumLayoutSize(BorderLayout.java:634)
    at java.awt.Container.minimumSize(Container.java:1598)
    at java.awt.Container.getMinimumSize(Container.java:1583)
    at javax.swing.JComponent.getMinimumSize(JComponent.java:1697)
    at javax.swing.BoxLayout.checkRequests(BoxLayout.java:433)
    at javax.swing.BoxLayout.layoutContainer(BoxLayout.java:375)
    at java.awt.Container.layout(Container.java:1401)
    at java.awt.Container.doLayout(Container.java:1390)
    at java.awt.Container.validateTree(Container.java:1473)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validate(Container.java:1448)
    at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:379)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:113)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicMenuItemUI.getPreferredMenuItemSize(BasicMenuItemUI.java:400)
    at javax.swing.plaf.basic.BasicMenuItemUI.getPreferredSize(BasicMenuItemUI.java:310)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1615)
    at javax.swing.BoxLayout.checkRequests(BoxLayout.java:434)
    at javax.swing.BoxLayout.preferredLayoutSize(BoxLayout.java:251)
    at javax.swing.plaf.basic.DefaultMenuLayout.preferredLayoutSize(DefaultMenuLayout.java:38)
    at java.awt.Container.preferredSize(Container.java:1558)
    at java.awt.Container.getPreferredSize(Container.java:1543)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1617)
    at javax.swing.JRootPane$RootLayout.layoutContainer(JRootPane.java:910)
    at java.awt.Container.layout(Container.java:1401)
    at java.awt.Container.doLayout(Container.java:1390)
    at java.awt.Container.validateTree(Container.java:1473)
    at java.awt.Container.validate(Container.java:1448)
    at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:379)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:113)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    There are no complaints about anything within my code, it's all GUI related whenever I make a bind() or rebind() call.
    Again, any help here would be great... cause this one's just beating me.
    Thanks!

    Maybe you want to change that worker thread to
    not do RMI but anything else (dummy data) to see if it really is RMI, I doubt it, I think you are updating some structures that have to do with swing GUI and hence you will hang.
    Just check this out.

  • Open image in Swing Application

    Hi,
    I'm having trouble getting an image to open into my swing application and I cant figure out whats wrong. In response to selecting the "Open" button or menu item a JFileChooser opens up and i select an image but the image doesn't actually load. If anyone could help i'd really appreciate it.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.swing.border.*;
    import javax.imageio.*;
    class PhotoEditor extends JPanel implements ActionListener {
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        JMenu imageMenu, effectsMenu;
        JFileChooser fc = new JFileChooser();
        BufferedImage img = null;
           public JMenuBar createMenuBar() {     
         JMenuBar menuBar = new JMenuBar();
        /* Build the first menu: */
        JMenu fileMenu = new JMenu("File");
        menuBar.add(fileMenu);
        fileMenu.setMnemonic(KeyEvent.VK_F);
        //a group of JMenuItems under the File option:
            String[] menuItems1 = {"Open", "Save","Save As..", "Close"};
        String[] menuIcons1 = {"Open.gif", "Save.gif", "", ""};
        for (int i = 0; i<menuItems1.length; i++)
                  JMenuItem fileMI = new JMenuItem(menuItems1, new ImageIcon(menuIcons1[i]));
              fileMI.addActionListener(this);
              fileMenu.add(fileMI);
    //adding a separator to the drop down menu list
    fileMenu.addSeparator();
    JMenuItem exitMI = new JMenuItem("Exit", new ImageIcon("Exit.gif"));
    exitMI.addActionListener(this);
    fileMenu.add(exitMI);
    /* Code which builds all the menu here */
    return menuBar;
         public JToolBar createToolBar() {     
         JToolBar toolB = new JToolBar(FlowLayout.LEFT);
    toolB.setLayout(new FlowLayout());
    // contentPane.add(toolB, "North");
    JButton newButton = new JButton(new ImageIcon("new24.gif"));
    newButton.addActionListener(this);
    toolB.add(newButton);
    newButton.setToolTipText("New");
    newButton.setActionCommand("New");
    //adding a separator to the drop down menu list
    toolB.addSeparator();
    JButton openButton = new JButton(new ImageIcon("open24.gif"));
    openButton.addActionListener(this);
    toolB.add(openButton);
    openButton.setToolTipText("Open");
         openButton.setActionCommand("Open");
    /* More code building the toolbar*/
    return toolB;
         public void actionPerformed(ActionEvent e) {
    Object eventSource = e.getSource();
    if ((eventSource instanceof JMenuItem) || (eventSource instanceof JButton));{
    String label = (String) e.getActionCommand();
    //Sets up the Action Listeners
    if (label.equals("Exit")) {
    System.exit(0);
    // Closes application
    else if (label.equals("Open")) {
         openImage();
    /* More codes for each button or menu item */
    protected void openImage() {
              int returnVal = fc.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
         try {
                   img = ImageIO.read(file);
                        catch (IOException e1) {
    public void paintComponent(Graphics g) {
         super.paintComponent(g);
    g.drawImage(img, 500, 500, null);
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("Photo Editor");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create a main label to put in the content pane.
    JLabel main = new JLabel();
    // main.setOpaque(true);
    // main.setBackground(new Color(128, 128, 128));
    main.setPreferredSize(new Dimension(800, 600));
    //Set the menu bar and add the label to the content pane.
    PhotoEditor mainmenu = new PhotoEditor();
    frame.setJMenuBar(mainmenu.createMenuBar());
         frame.getContentPane().add(mainmenu.createToolBar(), BorderLayout.PAGE_START);
    frame.getContentPane().add(main, BorderLayout.CENTER);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

    Your PhotoEditor class extends JPanel. In that class you override paintComponent(). But you never add the panel to the GUI, so that method is never invoked.
    Personally I would have the PhotoEditor class extend JFrame. Then in the constructor you build all the components for the frame
    a) build the menu
    b) build the toolbar
    Then I would create a PhotoPanel class that you extend and override the paintComponent(). Then you add this panel to the GUI as your main panel.
    For a simple example of drawing a background image on a panel search the forum for my BackgroundImage example.

  • How to print a JTable  in Java Swing ?

    Hi,
    I have an application written in java swing.Now I want to write a print module that prints some details.The details includes the JTextArea and JTable that changes in size dynamically.One solution i found is to put them in a panel and print that panel.But it is static.The size of JTable and JTextArea changes, according to the given input.Please give me a solution for this.

    Printing is a bit of a nightmare, actually. Most of the trouble is layout. Basically a Printable is passed a page number and a graphics context and has to work out what components go on that page and where. It can't depend on the pages being requested in sequence.
    You can call getPrintable from a JTable, and you can call that through your own Printable in order to add extra pages. However you can't ask a Printable how many pages it's going to produce, you just have to invoke it and see if it returns a code to say that the page is out of range.
    And the Printable JTable generates is very limited, the table has to occupy full pages, you can't tell it to start in a different place on the first page, or find out how much space it's used on the last page. The headers and footers generate JTable's own idea of a page number, not yours.
    You can call print() on most Swing components, but you'll need to set their size and location first, and/or mess with the transformation in the graphics context.

  • Removing a window and adding a new one with swing.

    Hi,
    A friend of mine recently asked me to add a GUI for a small chat he made, so I thought I'd help him out. I've come across something that's troubled me in the past, and I could never find a solution. What I'm trying to do is make it so a log in window pops up (have that working alright) and then when you press sign in, it removes that window (log in) and adds the main chat window (have this fully functional, too).
    If someone could provide an example or point me in the direction of the proper API to look into, so that I don't have to look through them all, I'd be extremely grateful.
    Here's an SSCCE example:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTextPane;
    import javax.swing.ListSelectionModel;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.SwingUtilities;
    public class Gui extends JFrame {
         public static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
         public String sessionId;
         public int returnCode;
         public boolean recievedReturnCode;
         public boolean errorConnecting;
         public long lastActionDelay;
         private JScrollPane listScrollPane;
         private JList list;
         private JTextPane console;
         private JButton signInButton;
         private JScrollPane consoleScrollPane;
         private JTextField typingField;
         private DefaultListModel userList;
         private JButton sendButton;
         public static void main(String[] args) {
              try {
                   SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                             new Gui().setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
         public Gui() {
              setResizable(false);
              setSize(500, 500);
              consoleScrollPane = new JScrollPane();
              console = new JTextPane();
              typingField = new JTextField();
              userList = new DefaultListModel();
              sendButton = new JButton();
              initializeLoginWindow();
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public void initializeLoginWindow() {
              setTitle("Login");
              signInButton = new JButton("Sign in");
              signInButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                        initializeChatWindow();
              signInButton.setBounds(5, 100, 75, 20);
              getContentPane().add(signInButton);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new JPanel());
         public void initializeChatWindow() {
              consoleScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
              consoleScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
              consoleScrollPane.setViewportView(console);
              consoleScrollPane.setBounds(5, 5, 575, 350);
              console.setEditable(false);
              typingField.setEditable(true);
              typingField.setBounds(5, 360, 575, 25);
              list = new JList(userList);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.setSelectedIndex(0);
            list.setVisibleRowCount(5);
            listScrollPane = new JScrollPane(list);
              listScrollPane.setBounds(585, 5, 110, 350);
              sendButton.setText("Send");
              sendButton.setBounds(585, 360, 111, 25);
              getContentPane().add(consoleScrollPane);
              getContentPane().add(typingField);
              getContentPane().add(listScrollPane);
              getContentPane().add(sendButton);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new JPanel());
    }Thanks in advanced!

    jduprez wrote:
    I've come across something that's troubled me in the past, and I could never find a solutionWhat is the problem?
    a log in window pops up (have that working alright)
    and then when you press sign in, it removes that window (log in) and adds the main chat window (have this fully functional, too).Hum, between what is working alright and what is already functional, I fail to see what is missing. Again, what is your problem/question?
    If someone could provide an example or point me in the direction of the proper API to look into, so that I don't have to look through them all, I'd be extremely grateful.
    [url http://download.oracle.com/javase/tutorial/uiswing/components/frame.html]JFrames and [url http://download.oracle.com/javase/tutorial/uiswing/components/dialog.html]dialogs seem to show enough API usage to do that. Still, I stronlgy encourage you to read the whole Swing tutorial: http://download.oracle.com/javase/tutorial/uiswing/index.html
    Incase you didn't see the hyperlink above, here's the SSCCE link: http://www.mediafire.com/?e5e3ci3kbvickla
    The "S" in SSCCE stands for "Short" (or, depending on authors, "Simple"). Anyway, a decent SSCCE should fit within a forum post (between code tags please). The whole idea is to provide the simplest thing to people willing to help. No doubtful sites. No non-standard extensions.
    Best regards,
    The problem is that I cannot seem to remove the first pane, leaving the second one to be drawn on the current one.
    In reguards to SSCCE, I always thought it was just a short runnable class example, but I've added the class to the main post. I'll take a look at the API in a few as well.

Maybe you are looking for