Building a Jframe

Hi ,
I am having a wierd problem with one of th tutorials onavaiable on this site. It is the Divelog tutorial. I am running java 1.4.1_02 on windows 2000. When I run the tutorial on this machine it hangs at the point when it is supposed to build the Jframe. (I figured this out by placing some system.println commands in there) Whe one of my office mates run it on the same type of machine it works. I know this is a long shoty, but any advice or ideas???
Thanks,
Bernie

ok, but like I said it works on other machines with similar configs.
package divelog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DiveLog
{ //Opens DiveLog class
private JTabbedPane tabbedPane;
private JFrame dlframe;
public DiveLog()
{ //Opens DiveLog constructor
//Create a frame object to add the application
//GUI components to.
     System.out.println("creating frame");
dlframe = new JFrame();
System.out.println("setting title");
          dlframe.setTitle("A Java Technology Dive Log");
// Closes from title bar
//and from menu
     System.out.println("adding window listener");
dlframe.addWindowListener(new WindowAdapter()
{ // Opens addWindowListener method
public void windowClosing(WindowEvent e)
{ // Opens windowClosing method
System.exit(0);
} // Closes windowClosing method
}); // Closes addWindowListener method
// Tabbed pane with panels for Jcomponents
     System.out.println("creating tabbedpane");
tabbedPane = new JTabbedPane(SwingConstants.LEFT);
tabbedPane.setBackground(Color.blue);
tabbedPane.setForeground(Color.white);
// Calls a method that adds individual tabs to the
//tabbedpane object.
populateTabbedPane();
//Calls the method that builds the menu
buildMenu();
} // Ends class constructor
private void populateTabbedPane()
{ // Opens populateTabbedPane method definition
// Create tabs with titles
tabbedPane.addTab("Welcome",
null,
new Welcome(),
"Welcome to the Dive Log");
tabbedPane.addTab("Diver Data",
null,
new Diver(),
"Click here to enter diver data");
tabbedPane.addTab("Log Dives",
null,
new Dives(),
"Click here to enter dives");
tabbedPane.addTab("Statistics",
null,
new Statistics(),
"Click here to calculate dive statistics");
tabbedPane.addTab("Favorite Web Site",
null,
new WebSite(),
"Click here to see a web site");
tabbedPane.addTab("Resources",
null,
new Resources(),
"Click here to see a list of resources");
} //Ends populateTabbedPane method
private void buildMenu()
{ // Opens buildMenu method definition
JMenuBar mb = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem item = new JMenuItem("Exit");
//Closes the application from the Exit
//menu item.
item.addActionListener(new ActionListener()
{ // Opens addActionListener method
public void actionPerformed(ActionEvent e)
{ // Opens actionPerformed method
System.exit(0);
} // Closes actionPerformed method
}); // Closes addActionListener method
menu.add(item);
mb.add(menu);
dlframe.setJMenuBar(mb);
}// Closes buildMenu method
          dlframe.getContentPane().add(tabbedPane);
          System.out.println("packing");
dlframe.pack();
dlframe.setSize(765, 690);
     dlframe.setLocation(200,200);
dlframe.setBackground(Color.white);
dlframe.setVisible(true);
// main method and entry point for app
public static void main(String[] args)
{ // Opens main method
DiveLog dl = new DiveLog();
} // Closes main method
} //Ends class DiveLog

Similar Messages

  • Tutorial/HowTo for Java JFrame image map

    I am a first semester Java student and am required to program a very simple game. I want to paint a Super Mario theme using 30x30 pixel blocks. I have been going through tutorials for a few days on displaying gif/jpg/png within a jframe and all use different methods. Does anyone know of a tutorial that focuses on building a jframe that is filled by a 2d array, each array element being a png?
    I am new to JFrames having spent most my time with console/text only programming.

    Welcome to the Sun forums.
    atozer wrote:
    I am a first semester Java student and am required to program a very simple game. A 'very simple' game would be console based. Perhaps 'hangman' would fit the bill.
    .. I want to paint a Super Mario theme using 30x30 pixel blocks. Huhh.. What does 'theme' mean to you? Searching for 'Super Mario theme' all I could see was hits for the theme music. I take it this would be better described in a screen-shot. Do you have a link to one?
    ..I have been going through tutorials for a few days on displaying gif/jpg/png within a jframe and all use different methods. Does anyone know of a tutorial that focuses on building a jframe that is filled by a 2d array, each array element being a png?1) It is generally not a good idea to consider a root component such as a JFrame, JApplet, JWindow or JDialog to be the 'main area' of the GUI. Instead it is more common/useful to put the main GUI into a JPanel, which can then be put into any of the root level components as needed.
    2) I suspect your tutorial requirements are too specific for any single tutorial. Instead look to tutorials on 2D rendering, and separately to tutorials dealing with images. The 'creating a GUI' part is worthy of its own tutorial as well.
    I am new to JFrames having spent most my time with console/text only programming.And we come back to. A simple game is a console based game.
    If somebody was set on learning to create GUIs, I would recommend they steer clear of GUI based games until they have completed a number of GUI based projects that do not involve custom painting (let alone the intricacies of doing custom painting in a responsive game that renders at nn FPS), which I suspect is what is needed to recreate a Super Mario game.
    KISS!

  • Passing arraylist between constructors?

    Hi guys,
    I've pretty new to java, and I think i'm having a little trouble
    understanding scope. The program I'm working on is building a jtree
    from an xml file, to do this an arraylist (xmlText) is being built and
    declared in the function Main. It's then called to an overloaded
    constructor which processes the XML into a jtree:
    public Editor( String title, ArrayList xmlText ) throws
    ParserConfigurationException
    Later, in the second constructor which builds my GUI, I try and call
    the same arraylist so I can parse this XML into a set of combo boxes,
    but get an error thrown up at me that i'm having a hard time solving- :
    public Editor( String title ) throws ParserConfigurationException
    // additional code
    // Create a read-only combobox- where I get an error.
    String [] items = (String []) xmlText.toArray (new String[
    xmlText.size () ]);
    JComboBox queryBox = new JComboBox(items);
    JComboBox queryBox2 = new JComboBox(items);
    JComboBox queryBox3 = new JComboBox(items);
    JComboBox queryBox4 = new JComboBox(items);
    JComboBox queryBox5 = new JComboBox(items);
    This is the way I understand the Arraylist can be converted to a string
    to use in the combo boxs. However I get an error thrown up at me here
    at about line 206, which as far as I understand, is because when the
    overloaded constructor calls the other constructor:
    public Editor( String title ) throws ParserConfigurationException -
    It does not pass in the variable xmlText.
    I'm told that the compiler complains because xmlText is not defined
    at that point:
    - it is not a global variable or class member
    - it has not been passed into the function
    and
    - it has not been declared inside the current function
    Can anyone think of a solution to this problem? As I say a lot of this
    stuff is still fairly beyond me, I understand the principles behind the
    language and the problem, but the solution has been evading me so far.
    If anyone could give me any help or a solution here I'd be very
    grateful- I'm getting totally stressed over this.
    The code I'm working on is below, I've highlighted where the error
    crops up too- it's about line 200-206 area. Sorry for the length, I was
    unsure as to how much of the code I should post.
    public class Editor extends JFrame implements ActionListener
    // This is the XMLTree object which displays the XML in a JTree
    private XMLTree XMLTree;
    private JTextArea textArea, textArea2, textArea3;
    // One JScrollPane is the container for the JTree, the other is for
    the textArea
    private JScrollPane jScroll, jScrollRt, jScrollUp,
    jScrollBelow;
    private JSplitPane splitPane, splitPane2;
    private JPanel panel;
    // This JButton handles the tree Refresh feature
    private JButton refreshButton;
    // This Listener allows the frame's close button to work properly
    private WindowListener winClosing;
    private JSplitPane splitpane3;
    // Menu Objects
    private JMenuBar menuBar;
    private JMenu fileMenu;
    private JMenuItem newItem, openItem, saveItem,
    exitItem;
    // This JDialog object will be used to allow the user to cancel an exit
    command
    private JDialog verifyDialog;
    // These JLabel objects will be used to display the error messages
    private JLabel question;
    // These JButtons are used with the verifyDialog object
    private JButton okButton, cancelButton;
    private JComboBox testBox;
    // These two constants set the width and height of the frame
    private static final int FRAME_WIDTH = 600;
    private static final int FRAME_HEIGHT = 450;
    * This constructor passes the graphical construction off to the
    overloaded constructor
    * and then handles the processing of the XML text
    public Editor( String title, ArrayList xmlText ) throws
    ParserConfigurationException
    this( title );
    textArea.setText( ( String )xmlText.get( 0 ) + "\n" );
    for ( int i = 1; i < xmlText.size(); i++ )
    textArea.append( ( String )xmlText.get( i ) + "\n" );
    try
    XMLTree.refresh( textArea.getText() );
    catch( Exception ex )
    String message = ex.getMessage();
    System.out.println( message );
    }//end try/catch
    } //end Editor( String title, String xml )
    * This constructor builds a frame containing a JSplitPane, which in
    turn contains two
    JScrollPanes.
    * One of the panes contains an XMLTree object and the other contains
    a JTextArea object.
    public Editor( String title ) throws ParserConfigurationException
    // This builds the JFrame portion of the object
    super( title );
    Toolkit toolkit;
    Dimension dim, minimumSize;
    int screenHeight, screenWidth;
    // Initialize basic layout properties
    setBackground( Color.lightGray );
    getContentPane().setLayout( new BorderLayout() );
    // Set the frame's display to be WIDTH x HEIGHT in the middle of
    the screen
    toolkit = Toolkit.getDefaultToolkit();
    dim = toolkit.getScreenSize();
    screenHeight = dim.height;
    screenWidth = dim.width;
    setBounds( (screenWidth-FRAME_WIDTH)/2,
    (screenHeight-FRAME_HEIGHT)/2, FRAME_WIDTH,
    FRAME_HEIGHT );
    // Build the Menu
    // Build the verify dialog
    // Set the Default Close Operation
    // Create the refresh button object
    // Add the button to the frame
    // Create two JScrollPane objects
    jScroll = new JScrollPane();
    jScrollRt = new JScrollPane();
    // First, create the JTextArea:
    // Create the JTextArea and add it to the right hand JScroll
    textArea = new JTextArea( 200,150 );
    jScrollRt.getViewport().add( textArea );
    // Next, create the XMLTree
    XMLTree = new XMLTree();
    XMLTree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.SINGLE_TREE_SELECTION
    XMLTree.setShowsRootHandles( true );
    // A more advanced version of this tool would allow the JTree to
    be editable
    XMLTree.setEditable( false );
    // Wrap the JTree in a JScroll so that we can scroll it in the
    JSplitPane.
    jScroll.getViewport().add( XMLTree );
    // Create the JSplitPane and add the two JScroll objects
    splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, jScroll,
    jScrollRt );
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(200);
    jScrollUp = new JScrollPane();
    jScrollBelow=new JScrollPane();
    // Here is were the error is coming up
    String [] items = (String []) xmlText.toArray (new String[
    xmlText.size () ]);
    JComboBox queryBox = new JComboBox(items);
    JComboBox queryBox2 = new JComboBox(items);
    JComboBox queryBox3 = new JComboBox(items);
    JComboBox queryBox4 = new JComboBox(items);
    JComboBox queryBox5 = new JComboBox(items);
    * I'm adding the scroll pane to the split pane,
    * a panel to the top of the split pane, and some uneditible
    combo boxes
    * to them. Then I'll rearrange them to rearrange them, but
    unfortunately am getting an error thrown up above.
    panel = new JPanel();
    panel.add(queryBox);
    panel.add(queryBox2);
    panel.add(queryBox3);
    panel.add(queryBox4);
    panel.add(queryBox5);
    jScrollUp.getViewport().add( panel );
    // Now building a text area
    textArea3 = new JTextArea(200, 150);
    jScrollBelow.getViewport().add( textArea3 );
    splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
    jScrollUp, jScrollBelow);
    splitPane2.setPreferredSize( new Dimension(300, 200) );
    splitPane2.setDividerLocation(100);
    splitPane2.setOneTouchExpandable(true);
    // in here can change the contents of the split pane
    getContentPane().add(splitPane2,BorderLayout.SOUTH);
    // Provide minimum sizes for the two components in the split pane
    minimumSize = new Dimension(200, 150);
    jScroll.setMinimumSize( minimumSize );
    jScrollRt.setMinimumSize( minimumSize );
    // Provide a preferred size for the split pane
    splitPane.setPreferredSize( new Dimension(400, 300) );
    // Add the split pane to the frame
    getContentPane().add( splitPane, BorderLayout.CENTER );
    //Put the final touches to the JFrame object
    validate();
    setVisible(true);
    // Add a WindowListener so that we can close the window
    winClosing = new WindowAdapter()
    public void windowClosing(WindowEvent e)
    verifyDialog.show();
    addWindowListener(winClosing);
    } //end Editor()
    * When a user event occurs, this method is called. If the action
    performed was a click
    * of the "Refresh" button, then the XMLTree object is updated using
    the current XML text
    * contained in the JTextArea
    public void actionPerformed( ActionEvent ae )
    if ( ae.getActionCommand().equals( "Refresh" ) )
    try
    XMLTree.refresh( textArea.getText() );
    catch( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    else if ( ae.getActionCommand().equals( "OK" ) )
    exit();
    else if ( ae.getActionCommand().equals( "Cancel" ) )
    verifyDialog.hide();
    }//end if/else if
    } //end actionPerformed()
    // Program execution begins here. An XML file (*.xml) must be passed
    into the method
    public static void main( String[] args )
    String fileName = "";
    BufferedReader reader;
    String line;
    ArrayList xmlText = null;
    Editor Editor;
    // Build a Document object based on the specified XML file
    try
    if( args.length > 0 )
    fileName = args[0];
    if ( fileName.substring( fileName.indexOf( '.' ) ).equals(
    ".xml" ) )
    reader = new BufferedReader( new FileReader( fileName )
    xmlText = new ArrayList();
    while ( ( line = reader.readLine() ) != null )
    xmlText.add( line );
    } //end while ( ( line = reader.readLine() ) != null )
    // The file will have to be re-read when the Document
    object is parsed
    reader.close();
    // Construct the GUI components and pass a reference to
    the XML root node
    Editor = new Editor( "Editor 1.0", xmlText );
    else
    help();
    } //end if ( fileName.substring( fileName.indexOf( '.' )
    ).equals( ".xml" ) )
    else
    Editor = new Editor( "Editor 1.0" );
    } //end if( args.length > 0 )
    catch( FileNotFoundException fnfEx )
    System.out.println( fileName + " was not found." );
    exit();
    catch( Exception ex )
    ex.printStackTrace();
    exit();
    }// end try/catch
    }// end main()
    // A common source of operating instructions
    private static void help()
    System.out.println( "\nUsage: java Editor filename.xml" );
    System.exit(0);
    } //end help()
    // A common point of exit
    public static void exit()
    System.out.println( "\nThank you for using Editor 1.0" );
    System.exit(0);
    } //end exit()
    class newMenuHandler implements ActionListener
    public void actionPerformed( ActionEvent ae )
    textArea.setText( "" );
    try
    // Next, create a new XMLTree
    XMLTree = new XMLTree();
    XMLTree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.SINGLE_TREE_SELECTION );
    XMLTree.setShowsRootHandles( true );
    // A more advanced version of this tool would allow the JTree
    to be editable
    XMLTree.setEditable( false );
    catch( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    }//end actionPerformed()
    }//end class newMenuHandler
    class openMenuHandler implements ActionListener
    JFileChooser jfc;
    Container parent;
    int choice;
    openMenuHandler()
    super();
    jfc = new JFileChooser();
    jfc.setSize( 400,300 );
    jfc.setFileFilter( new XmlFileFilter() );
    parent = openItem.getParent();
    }//end openMenuHandler()
    public void actionPerformed( ActionEvent ae )
    // Displays the jfc and sets the dialog to 'open'
    choice = jfc.showOpenDialog( parent );
    if ( choice == JFileChooser.APPROVE_OPTION )
    String fileName, line;
    BufferedReader reader;
    fileName = jfc.getSelectedFile().getAbsolutePath();
    try
    reader = new BufferedReader( new FileReader( fileName ) );
    textArea.setText( reader.readLine() + "\n" );
    while ( ( line = reader.readLine() ) != null )
    textArea.append( line + "\n" );
    } //end while ( ( line = reader.readLine() ) != null )
    // The file will have to be re-read when the Document
    object is parsed
    reader.close();
    XMLTree.refresh( textArea.getText() );
    catch ( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    jfc.setCurrentDirectory( new File( fileName ) );
    } //end if ( choice == JFileChooser.APPROVE_OPTION )
    }//end actionPerformed()
    }//end class openMenuHandler
    class saveMenuHandler implements ActionListener
    JFileChooser jfc;
    Container parent;
    int choice;
    saveMenuHandler()
    super();
    jfc = new JFileChooser();
    jfc.setSize( 400,300 );
    jfc.setFileFilter( new XmlFileFilter() );
    parent = saveItem.getParent();
    }//end saveMenuHandler()
    public void actionPerformed( ActionEvent ae )
    // Displays the jfc and sets the dialog to 'save'
    choice = jfc.showSaveDialog( parent );
    if ( choice == JFileChooser.APPROVE_OPTION )
    String fileName;
    File fObj;
    FileWriter writer;
    fileName = jfc.getSelectedFile().getAbsolutePath();
    try
    writer = new FileWriter( fileName );
    textArea.write( writer );
    // The file will have to be re-read when the Document
    object is parsed
    writer.close();
    catch ( IOException ioe )
    ioe.printStackTrace();
    }//end try/catch
    jfc.setCurrentDirectory( new File( fileName ) );
    } //end if ( choice == JFileChooser.APPROVE_OPTION )
    }//end actionPerformed()
    }//end class saveMenuHandler
    class exitMenuHandler implements ActionListener
    public void actionPerformed( ActionEvent ae )
    verifyDialog.show();
    }//end actionPerformed()
    }//end class exitMenuHandler
    class XmlFileFilter extends javax.swing.filechooser.FileFilter
    public boolean accept( File fobj )
    if ( fobj.isDirectory() )
    return true;
    else
    return fobj.getName().endsWith( ".xml" );
    }//end accept()
    public String getDescription()
    return "*.xml";
    }//end getDescription()
    }//end class XmlFileFilter
    } //end class Editor
    Sorry if this post has been a bit lengthy, any help you guys could give
    me solving this would be really appreciated.
    Thanks,
    Iain.

    Hey. Couple pointers:
    When posting, try to keep code inbetween code tags (button between spell check and quote original). It will pretty-print the code.
    Posting code is good. Usually, though, you want to post theminimum amount of code which runs and shows your problem.
    That way people don't have to wade through irrelevant stuff and
    they have an easier time helping.
    http://homepage1.nifty.com/algafield/sscce.html
    As for your problem, this is a scope issue. You declare an
    ArrayList xmlText in main(). That means that everywhere after
    the declaration in main(), you can reference your xmlText.
    So far so good. Then, inside main(), you call
    Editor = new Editor( "Editor 1.0", xmlText );Now you've passed the xmlText variable to a new method,
    Editor(String title, ArrayList xmlText) [which happens to be a
    constructor, but that's not important]. When you do that, you
    make the two variables title and xmlText available to the whole
    Editor(String, ArrayList) method.
    This is where you get messed up. You invoke another method
    from inside Editor(String, ArrayList). When you call
    this(title);you're invoking the method Editor(String title). You aren't passing
    in your arraylist, though. You've got code in the Editor(String) method
    which is trying to reference xmlText, but you'd need to pass in
    your ArrayList in order to do so.
    My suggestion would be to merge the two constructor methods into
    one, Editor(String title, ArrayList xmlText).

  • Problem with JPanel, JMenuBar

    Hi, I'm new here so I'm not even sure if I'm posting in the correct forum ^^
    I usually don't have problems when building a JFrame and adding items into it but now I'm confused.
    When the JFrame is "built", I get a NullPointerException from the Panel's paintComponent method when it's trying to draw an image (g.drawImage())
    This is the whole JPanel class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PanneauDe extends JPanel
      private static final String [] TAB_IMAGE = { "De1.GIF", "De2.GIF", "De3.GIF",
                                                   "De4.GIF", "De5.GIF", "De6.GIF" };
      private static final int [] TAB_FREQUENCE = {0,0,0,0,0,0};
      private static final int SIDE = 100;
      private De unDe;
      private ImageIcon imageDe;
      private boolean aFirstTime;
      private int aX, aY; 
      public PanneauDe()
        unDe = new De();
        aX = aY = 0;
        aFirstTime = true;  
        addMouseListener(new EcouteurSouris());   
      public String getStats()
        String statsMsg = "";
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          statsMsg += "Face " + (iPos + 1) + " : " + TAB_FREQUENCE[iPos] + " fois\n\n";
        return statsMsg;
      public String getTotal()
        int total = 0;
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          total += TAB_FREQUENCE[iPos];
        return "Le d� a �t� lanc� " + total + " fois";
      public void throwDice()
        unDe.throwAgain();
        TAB_FREQUENCE[unDe.getFace() - 1] ++;   
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        g.drawImage (imageDe.getImage(), aX, aY, null); // <---- THIS GENERATES THE NULLPOINTEREXCEPTION
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          repaint();
    }When I click in the windows, a picture of a dice (different side, randomly generated by the method throwDice() ), when I click again the first image dissapear and another one appears... and I make statistics about the results.
    I tried ...
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        //g.drawImage (imageDe.getImage(), aX, aY, null);
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          Graphics g = getGraphics();
          g.drawImage (imageDe.getImage(), aX, aY, null);
          g.dispose();
        }Everything works correctly, no more NullPointerException, but the images don't dissapear when I click again. They just stay there.
    I'm not completly familiar with the repaint/dispose/paintComponent but I really don't understand why i get this NullPointerException error :\
    If you see some weird words in the code, it's because i'm canadian-frenchy! :)
    Full program is here

    The real question is why are you trying to override the paintComponent() method. Just add the image to a JLabel and add the label to a panel.
    However, the problem is that the paintComponent() method is invoked when the frame is shown and since you don't create the image until you do a mouseClick, the image in null.

  • Adding Components to a JPanel not working correctly

    I'm trying to build a JFrame that contains a parent JPanel that will hold a JPanel used to display a message view, a vertical strut and a JPanel that holds VCR-like buttons to cycle through the messages.
    My parent JPanel uses a BorderLayout and the Border is a TitledBorder which tells which product you are viewing (i.e., Message 1 of 5). I build the message JPanel, vertical strut and button JPanel and add them all in order to the parent JPanel which then gets added to the rootContentPane of the JFrame. All that appears is the parent JPanel's TitledBorder, the strut and the button JPanel. Using JSwat, I've been able to determine that the message JPanel has 0 for both its height and width after adding the message components to the JPanel.
    I create the message JPanel with a BorderLayout and an OvalBorder as copied from Manning Press's Swing book (which works fine in other JFrames that I have built), then add other components as necessary to the individual messages (mostly items around the edges with a central display for the actual message). What I can't figure out is why the height and width of the message JPanel isn't growing as I add components.
    I had previously used the same code to display a single message (minus the parent JPanel, strut and button JPanel) where I added the border panels (northPanel, eastPanel, southPanel and westPanel) created in createMsgPanel() directly to the contentPane and it worked perfectly, so I know that the code that adds the message works fine. Then, the requirements changed (go figure) and I had to display multiple messages from the same screen.
    Here's what I've got:
    public class Layout
                 extends JFrame
                 implements ActionListener
       private MissionData missionData;
       private JPanel messagePanel = null;
       private int index = 0;
       private int numMsgs = 0;
       private JPanel mainPanel = null;
       private JPanel buttonPanel = null;
       private TitledBorder titledBorder = null;
       Layout ()
       public Layout (MissionData msn)
          super ();
          missionData = msn;
          setSize (640, 640);
          setIconImage (new ImageIcon ("Icon.jpg").getImage());
          setTitle (((Message) (missionData.messages.elementAt(0))).name);
          numMsgs = missionData.messages.size();
          titledBorder = new TitledBorder (
                            new LineBorder (Color.BLACK),
                            "Message " + String.valueOf (index + 1) +
                            " of " + String.valueOf (numMsgs),
                            TitledBorder.LEFT,
                            TitledBorder.TOP);
          mainPanel = new JPanel ();
          mainPanel.setLayout (new BorderLayout());
          mainPanel.setBorder (new CompoundBorder (titledBorder,
                                                   new EmptyBorder (
                                                      new Insets (3, 3, 3, 3))));
          messagePanel = new JPanel();
          messagePanel.setLayout (new BorderLayout ());
          messagePanel.setBorder (new CompoundBorder (
                                     new EmptyBorder (50, 50, 50, 50),
                                     new OvalBorder (20, 20, Color.white)));
          messagePanel.setBackground (Color.black);
          createButtonPanel ();
          createMsgPanel ((Message) missionData.messages.elementAt (0));
          mainPanel.add (messagePanel);
          mainPanel.add (Box.createVerticalStrut (20));
          mainPanel.add (buttonPanel);
          Container mainContentPane = getContentPane();
          mainContentPane.add (mainPanel);
       private void createMsgPanel (Message msg)
          MessageType msgType = null;
          if (msg.getFunctionalAreaDesignator(0) == Message.GENERAL_INFO)
             if (msg.getMessageNumber(0) == 1)
                msgType = FREE_TEXT;
          else if (msg.getFunctionalAreaDesignator(0) == Message.SUPPORT)
             if (msg.getMessageNumber(0) == 33)
                msgType = CAS;
             else if (msg.getMessageNumber(0) == 34)
                msgType = OSR;
          // Setup NORTH Panel of Display
          JPanel northPanel = new JPanel (new GridLayout (2, 6));
          northPanel.setBackground (Color.black);
          northPanel.add (new JTIMLabel ("", false));
          northPanel.add (new JTIMLabel ("<html>RECV</html>", false));
          if (msgType == CAS)
             northPanel.add (new JTIMLabel ("<html>PCLR</html>", false));
             northPanel.add (new JTIMLabel ("<html>MSN</html>", false));
             northPanel.add (new JTIMLabel ("<html>SAVE</html>", false));
          else if (msgType == OSR)
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
          else if (msgType == FREE_TEXT)
             northPanel.add (new JTIMLabel ("<html>ERASE</html>", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("<html>BRDCST</html>", false));
          northPanel.add (new JTIMLabel ("<html>SEND</html>", false));
          northPanel.add (new JTIMLabel ("", false));
          northPanel.add (new JTIMLabel ("", false));
          if (msgType == CAS)
             northPanel.add (new JTIMLabel ("<html>CAS</html>", false));
          else if (msgType == OSR)
             northPanel.add (new JTIMLabel ("<html>OSR</html>", false));
          else if (msgType == FREE_TEXT)
             northPanel.add (new JTIMLabel ("<html>FTXT</html>", false));
          if (msgType == FREE_TEXT)
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
          else
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("<html>CAS</html>", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
          messagePanel.add (northPanel, BorderLayout.NORTH);
          // Setup EAST Box of Display
          Box eastBox = new Box (BoxLayout.Y_AXIS);
          if (msgType == CAS)
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("<html>F<br>T<br>X<br>T</html>", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("<html>O<br>S<br>R</html>", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("<html>D<br>P<br>I<br>P</html>", false));
             eastBox.add (Box.createGlue());
          else if (msgType == FREE_TEXT)
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
          eastBox.add (new JTIMLabel ("<html>W<br>L<br>C<br>O</html>", false));
          eastBox.add (Box.createGlue());
          eastBox.add (new JTIMLabel ("<html>C<br>N<br>T<br>C<br>O</html>",
                                        false));
          eastBox.add (Box.createGlue());
          messagePanel.add (eastBox, BorderLayout.EAST);
          // Setup SOUTH Panel of Display
          JPanel southPanel = new JPanel (new GridLayout (2, 5));
          southPanel.setBackground (Color.black);
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("<html>ON</html>", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          if (msgType == CAS)
             southPanel.add (new JTIMLabel ("<html>USE</html>", false));
             southPanel.add (new JTIMLabel ("<html>RCALL</html>", false));
          else if ((msgType == OSR) || (msgType == FREE_TEXT))
             southPanel.add (new JTIMLabel ("", false));
             southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("<html>MENU</html>", false));
          southPanel.add (new JTIMLabel ("<html>VMF</html>", false));
          if (msgType == CAS)
             southPanel.add (new JTIMLabel ("<html>NETS</html>", false));
          else if ((msgType == OSR) || (msgType == FREE_TEXT))
             southPanel.add (new JTIMLabel ("<html>CAS</html>", false));
          southPanel.add (new JTIMLabel ("", false));
          messagePanel.add (southPanel, BorderLayout.SOUTH);
          // Setup WEST Box of Display
          JTIMLabel incrLabel = null;
          JTIMLabel decrLabel = null;
          Box westBox = new Box (BoxLayout.Y_AXIS);
          if (msgType == FREE_TEXT)
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("<html>N<br>E<br>X<br>T</html>", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("<html>P<br>R<br>E<br>V</html>", false));
          else
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("<html>U<br>F<br>C</html>", false));
             westBox.add (Box.createGlue());
             if (msgType == CAS)
                westBox.add (new JTIMLabel ("<html>/\\</html>", false));
                westBox.add (Box.createGlue());
                westBox.add (new JTIMLabel ("<html>\\/</html>", false));
                westBox.add (Box.createGlue());
                incrLabel = new JTIMLabel ("<html>I<br>N<br>C<br>R</html>", false);
                westBox.add (incrLabel);
                westBox.add (Box.createGlue());
                decrLabel = new JTIMLabel ("<html>D<br>E<br>C<br>R</html>", false);
                westBox.add (decrLabel);
                westBox.add (Box.createGlue());
          messagePanel.add (westBox, BorderLayout.WEST);
          // Create CENTER Box to display message bodies
          GriddedPanel centerBox = new GriddedPanel ();
          centerBox.setBackground (Color.black);
          messagePanel.add (centerBox, BorderLayout.CENTER);
          if (msgType == CAS)
             new CASDisplay (msg, centerBox, incrLabel, decrLabel);
          else if (msgType == OSR)
             new OSRDisplay (msg, centerBox);
          else if (msgType == FREE_TEXT)
             new FreeTextDisplay (msg, centerBox);
       private void createButtonPanel ()
          // build the button panel
          buttonPanel = new JPanel ();
          buttonPanel.setLayout (new BoxLayout (buttonPanel, BoxLayout.X_AXIS));
          buttonPanel.setBorder (new LineBorder (Color.BLACK));
          // Create and add the buttons
          buttonPanel.add (createButton ("FIRST_BUTTON"));
          buttonPanel.add (createButton ("PREV_BUTTON"));
          buttonPanel.add (createButton ("NEXT_BUTTON"));
          buttonPanel.add (createButton ("LAST_BUTTON"));
       private JButton createButton (String buttonName)
          JButton button = new JButton ();
          button.addActionListener (this);
          button.setActionCommand (buttonName);
          Image image = null;
          String tooltip = "Press to go to the ";
          if (buttonName.equals ("FIRST_BUTTON"))
             image = new ImageIcon ("firstArrowIcon.gif").getImage();
             tooltip += "First";
          else if (buttonName.equals ("PREV_BUTTON"))
             image = new ImageIcon ("previousArrowIcon.gif").getImage();
             tooltip += "Previous";
          else if (buttonName.equals ("NEXT_BUTTON"))
             image = new ImageIcon ("nextArrowIcon.gif").getImage();
             tooltip += "Next";
          else if (buttonName.equals ("LAST_BUTTON"))
             image = new ImageIcon ("lastArrowIcon.gif").getImage();
             tooltip += "Last";
          tooltip += " message in the lst";
          button.setToolTipText (tooltip);
          button.setIcon (new ImageIcon (image.getScaledInstance (36, 36, Image.SCALE_FAST)));
          return button;
       public void actionPerformed (ActionEvent e)
          if (e.getActionCommand ().equals ("FIRST_BUTTON"))
             index = 0;
          else if (e.getActionCommand ().equals ("PREV_BUTTON"))
             if (index > 0)
                index--;
          else if (e.getActionCommand ().equals ("NEXT_BUTTON"))
             if (index < numMsgs - 1)
                index++;
          else if (e.getActionCommand ().equals ("LAST_BUTTON"))
             index = numMsgs - 1;
          titledBorder.setTitle ("Message " + String.valueOf (index + 1) +
                                 " of " + String.valueOf (numMsgs));
          createMsgPanel ((Message) missionData.messages.elementAt (index));
       private static class MessageType
                            extends EnumeratedType
                            implements Serializable
          final static long serialVersionUID = 1;
          protected MessageType (int value, String desc)
             super (value, desc);
       private static MessageType FREE_TEXT =
          new MessageType (0, "Free Text");
       private static MessageType CAS =
          new MessageType (1, "Call Accounting System");
       private static MessageType OSR =
          new MessageType (2, "Occupational Survey Report");
    }

    That's all well and good, but I've had more times that not where
    people want the entire program, not bits and pieces.Then you missed the whole point of that link.
    We don't want to see bits and pieces of code. We want to see an executable program, but we want an executable program the demonstrates the incorrect behaviour without all the unnecessary code. 90% of the code you posted was not related to your problem. That is we what you do to some basic debugging and remove the parts of code that are not related to the problem so we can concentrate on the code that is related to the problem.

  • How can I access data in different panels?

    Hi,
    I'm a beginner in Swing and have a simple(?) question. Unfortunately I didn't find the answer by oneself so I hope you can help me.
    I have three classes. In the GUI.java class I build the JFrame and it's components. All components are added to the frame via panels that a separate classes.
    My problem is: how can I acces the values in PanelB when I call the actionPerfomed in PanelA? Or is that always a bad design? How can I make it better?
    GUI.java
    JFrame frame = new JFrame();
    PanelA panelA = new PanelA();
    PanelB panelB = new PanelB();
    frame.getContentPane().add(panelA);
    frame.getContentPane().add(panelB);PanelA.java
    private class ButtonCalculateAction implements ActionListener {
         public void actionPerformed(ActionEvent e){
              //calculate with valuesX and valuesY from Panel B
    JButton buttonCalculate;
    ...PanelB.java
    JList valuesX;
    JList valuesY;
    JButton addValueX;
    ...

    Here is the code for a Short, Self Contained, Correct (Compilable), Example
    GUI.java
    import java.awt.FlowLayout;
    import javax.swing.JFrame;
    public class GUI {
         public GUI(){
              JFrame frame = new JFrame();
              PanelA panelA = new PanelA();
              PanelB panelB = new PanelB();
              frame.getContentPane().setLayout(new FlowLayout());
              frame.getContentPane().add(panelA);
              frame.getContentPane().add(panelB);
              frame.setSize(400, 200);
              frame.setVisible(true);
         public static void main(String[] args) {
              GUI gui = new GUI();
    }PanelA.javaimport java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class PanelA extends JPanel {
         public PanelA(){
              this.setLayout(new FlowLayout());
              this.buttonCalculate = new JButton("Calculate");
              this.buttonCalculate.addActionListener(new ButtonCalculateAction());
              this.add(buttonCalculate);
              this.result = new JTextField("...");
              this.add(result);
         private class ButtonCalculateAction implements ActionListener {
              public void actionPerformed(ActionEvent e){
                   //calculate with values from PanelB. How??
                   //result = ?
         private JButton buttonCalculate;
         private JTextField result;
    }PanelB.java
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class PanelB extends JPanel {
         public PanelB(){
              this.addValueX = new JButton("Add X");
              this.addValueX.addActionListener(new ButtonAddAction());
              this.valuesXList = new DefaultListModel();
              this.valuesX = new JList();
              this.valuesX.setModel(valuesXList);
              this.add(addValueX);
              this.add(valuesX);
         private class ButtonAddAction implements ActionListener {
              public void actionPerformed(ActionEvent e){
                   valuesXList.addElement(47);
         private JList valuesX;
         private DefaultListModel valuesXList;
         private JButton addValueX;
    }

  • How to print diffrent color and diffrent size of text in JTextArea ?

    Hello All,
    i want to make JFrame which have JTextArea and i append text in
    JTextArea in diffrent size and diffrent color and also with diffrent
    fonts.
    any body give me any example or help me ?
    i m thanksfull.
    Arif.

    You can't have multiple text attributes in a JTextArea.
    JTextArea manages a "text/plain" content type document that can't hold information about attributes ( color, font, size, etc.) for different portions of text.
    You need a component that can manage styled documents. The most basic component that can do this is JEditorPane. It can manage the following content types :
    "text/rtf" ==> via StyledDocument
    "text/html" ==> via HTMLDocument
    I've written for you an example of how a "Hello World" string could be colorized in a JEditorPane with "Hello" in red and "World" in blue.
    import javax.swing.JEditorPane;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledEditorKit;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import java.awt.Color;
    public class ColorizeTextTest{
         public static void main(String args[]){
              //build gui
              JFrame frame = new JFrame();
              JEditorPane editorPane = new JEditorPane();
              frame.getContentPane().add(editorPane);
              frame.pack();
              frame.setVisible(true);
              //create StyledEditorKit
              StyledEditorKit editorKit = new StyledEditorKit();
              //set this editorKit as the editor manager [JTextComponent] <-> [EditorKit] <-> [Document]
              editorPane.setEditorKit(editorKit);
              StyledDocument doc = (StyledDocument) editorPane.getDocument();
              //insert string "Hello World"
              //this text is going to be added to the StyledDocument with positions 0 to 10
              editorPane.setText("Hello World");
              //create and attribute set
              MutableAttributeSet atr = new SimpleAttributeSet();
              //set foreground color attribute to RED
              StyleConstants.setForeground(atr,Color.RED);
              //apply attribute to the word "Hello"
              int offset = 0; //we want to start applying this attribute at position 0
              int length = 5; //"Hello" string has a length of 5
              boolean replace = false; //should we override any other attribute not specified in "atr" : anwser "NO"
              doc.setCharacterAttributes(offset,length,atr,replace);
              //set foreground color attribute to BLUE
              StyleConstants.setForeground(atr,Color.BLUE);
              //apply attribute to the word "World"
              offset = 5; //we include the whitespace
              length = 6;
              doc.setCharacterAttributes(offset,length,atr,replace);
    }

  • How can i make a swing frame block?

    Hi,
    I have an application with several frames, before building a frame, I want to query the user about some information. So I build another Jframe, with some radio buttons, etc. and display that first.
    However, the new Jframe does not make the rest of the program block, and thus the other Jframe is still created immediately...is there a way to make the JFrame with the query info block, until it is closed?
    thanks!

    I am still a bit confused....here is what i am trying to do:
    dialogFrame.setVisible(true);
    System.out.println(submit);
    if(!submit)
    return;
    else
    submit = false;
    dialogFrame the JDialog...it is built like this:
    JRadioButton rButtons[] = new JRadioButton[3];
    JPanel rPanel = new JPanel(new GridLayout(0, 1));
    rButtons[0] = new JRadioButton("Use Milliseconds Scale");
    rButtons[0].setSelected(true);
    rButtons[0].setActionCommand("MS");
    rButtons[1] = new JRadioButton("Use Seconds Scale");
    rButtons[1].setActionCommand("SEC");
    rButtons[2] = new JRadioButton("Use Minutes Scale");
    rButtons[2].setActionCommand("MIN");
    for (int i = 0; i < 3; i++) {
    bGroup.add(rButtons);
    rPanel.add(rButtons[i]);
    dialogFrame.getContentPane().setLayout(new BorderLayout(10,10));
    dialogFrame.getContentPane().add(rPanel, BorderLayout.CENTER);
    dialogFrame.getContentPane().add(yes, BorderLayout.SOUTH);
    dialogFrame.pack();
    I put a button "yes" in there, and when the user clicks it, the boolean 'submit' goes true.
    But, as you can see above, when i set the dialog frame as visible, it does not block on that line of code, rather it prints out false...

  • Assistance needed with simple java vocabulary program

    I need to construct a java program that can read in text documents. The program must then display an image and prompt the user to input the word that best-describes the image. If the user is incorrect, however, the program must tell the user how many letters the word has and what the first letter is.

    * @(#)words.java
    * @author
    * @version 1.00 2010/6/8
    import javax.swing.*; //class necessary for GUI
    import java.awt.*; //class necessary for GUI
    import java.awt.event.*; //class necessary for GUI
    import java.util.ArrayList; //import ArrayList class
    public class Words implements ActionListener { //ActionListener is required for the button to function
    //initialize values that will be used in other methods
    int noLetters = 0; //number of letters
    String[] words; //words
    JTextField textNL; //inputs number of letters
    ArrayList<JLabel> list;
    public static void main (String[] args) {
         Word s = new Word(); //this is so you are not referencing non-static methods from a static context (main must be static, but the constructor is not)
         s.go();} //runs following method as a method of the object Words s
    public void go() {
         //build GUI
              JFrame frame = new JFrame(); //intializes frame, this is essentially the GUI
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //sets program to stop when frame is exited
              JTabbedPane pane = new JTabbedPane(); //creates a new tabbed panel
              JPanel panel1 = new JPanel(); //creates input panel
              JPanel panel2 = new JPanel(); //creates output panel
              textNL = new JTextField("", 15); //initializes the text field of the same name from the beginning of the program
              JButton button = new JButton("Enter"); //This button will input the data you have entered into the text fields
              button.addActionListener(this); //tells the button to do stuff when it is clicked (see actionPerformed())
              panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS)); //Sets frame to display labels and text fields arranged vertically
              panel1.add(new JLabel("Number of Letters")); //this label tells you what the text field is prompting for
              panel1.add(textND); //adds text field to input panel
              panel1.add(BorderLayout.SOUTH, button); //adds button to input panel
              pane.add("Enter Data", panel1); //adds input panel to tabbed panel
              pane.add("Words", panel2); //adds output panel to tabbed panel
              frame.getContentPane().add(pane); //adds tabbed panel to frame
              frame.setSize(400, 400); //sets GUI intial dimensions
              frame.setVisible(true); //displays GUI
              //end of GUI build
    }

  • Code example of the day, want your advice

    Update: I have removed the setRunnable method and all the synchronization stuff, which takes care of question a. Now, on part B, can anyone suggest a better name for this class?
    I am posting my class ThreadForMultipleAnytimeRuns, plus my Eyes class which was actually the reason I created it.
    ThreadForMultipleAnytimeRuns offers the following:
    (a) you can run a runnable outside of the GUI thread - important in this case, because if you try to run an animation in the drawing thread you're not going to see anything
    (b) It will queue the blinks so they don't all happen at once.
    Questions:
    1. Is what I've done thread-safe? I added a method to swap the runnable into the class. I have it so that it waits until the job queue (semaphore) is empty before it swaps in the new runnable. Is this safe now? I would love to hear your thoughts
    2. I am unsatisfied with the name of this class. Can anyone think of a better name?
    BTW, unfortunately this code isn't compilable as posted. To get it to compile, you need to remove the references to MathUtils - all this takes is replacing distance with the euclidean distance formula, and angle with java.lang.Math.atan2, and references to WindowUtilities, which means replacing WindowUtilities.visualize and just building a JFrame and sticking the eyes in it
    Thanks for any comments about how I could make this better!
    You are welcome to use and modify this code, but please don't change the package or take credit for it as your own code.
    package tjacobs.thread;
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.concurrent.Semaphore;
    import javax.swing.JFrame;
    import tjacobs.ui.Eyes;
    import tjacobs.ui.WindowUtilities;
    public class ThreadForMultipleAnytimeRuns extends Thread {
         private Runnable mRunnable;
         private Semaphore mSemaphore;
         public ThreadForMultipleAnytimeRuns(Runnable arg0) {
              super();
              init(arg0);
         private void init(Runnable r) {
              mRunnable = r;
              mSemaphore = new Semaphore(0);
              setDaemon(true);
         public ThreadForMultipleAnytimeRuns(Runnable arg0, String arg1) {
              super(arg1);
              init(arg0);
         public ThreadForMultipleAnytimeRuns(ThreadGroup arg0, Runnable arg1, String arg2) {
              super(arg0, arg2);
              init(arg1);
         public void run () {
              try {
                   while (!isInterrupted()) {
                        // make a local copy so if mRunnable changes
                        // we have the fresh one
                        mSemaphore.acquire();
                        if (getSemaphoreCount() == 0) {
                             Runnable r = mRunnable;
                             synchronized (this) {
                                  notifyAll();
                             r.run();
                        mRunnable.run();
              catch (InterruptedException ex) {}
         public void runAgain() {
              mSemaphore.release();
         public void runAgain(int numTimes) {
              mSemaphore.release(numTimes);
         public void stopThread() {
              interrupt();
         public int getSemaphoreCount() {
              return mSemaphore.availablePermits();
         public Runnable getRunnable() {
              return mRunnable;
         public synchronized void setRunnable(Runnable r) {
              if (getSemaphoreCount() > 0) {
                   try {
                        wait();
                   catch (InterruptedException ex) {
                        return;
              mRunnable = r;
         public static void main(String[] args) {
              final Eyes eyes = new Eyes(true);
              //eyes.addMouseMotionListener(eyes);
              Runnable r = new Runnable() {
                   public void run() {
                        eyes.blink();
                        try {
                             Thread.sleep(100);
                        catch(InterruptedException ex) {}
              final ThreadForMultipleAnytimeRuns ar = new ThreadForMultipleAnytimeRuns(r);
              ar.start();
              eyes.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent me) {
                        ar.runAgain();
              eyes.setPreferredSize(new Dimension(60,20));
              WindowUtilities.visualize(eyes);
    //          JFrame jf = new JFrame();
    //          jf.add(eyes);
    //          jf.pack();
    //          jf.setLocation(100,100);
    //          jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //          jf.setVisible(true);
    ================================================
    tjacobs.ui.Eyes
    ============
    package tjacobs.ui;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.util.Timer;
    import java.util.TimerTask;
    import javax.swing.JComponent;
    import javax.swing.SwingUtilities;
    import tjacobs.MathUtils;
    public class Eyes extends JComponent implements MouseMotionListener {
         private int mEyeGap = 0;
         private double mEyeDir1 = Double.NaN, mEyeDir2 = Double.NaN;
         private double mEyeRatio = .6;
         private int mBlinkEyesState = 0;
         private Timer mEyeBlinker;
         private long mTimeBetweenBlinks;
         private long mBlinkAnimationSpeed = 100;
         public Eyes() {
              //setBackground(Color.BLACK);
              this(false);
         public Eyes(boolean watchOnEyes) {
              setBackground(Color.PINK);
              setForeground(Color.BLUE);
              if (watchOnEyes) addMouseMotionListener(this);          
         public void setBatAnimationSpeed(long speed) {
              mBlinkAnimationSpeed = speed;
         public long getBatAnimationSpeed() {
              return mBlinkAnimationSpeed;
         public void mouseMoved(MouseEvent me) {
              Point p = SwingUtilities.convertPoint(me.getComponent(), me.getPoint(), this);
              int height = getHeight();
              mEyeDir1 = MathUtils.angle(height / 2, height / 2, p.x, p.y);
              mEyeDir2 = MathUtils.angle((3 * height) / 2 + mEyeGap, height / 2, p.x, p.y);
              repaint();
         public void mouseDragged(MouseEvent me) {
              mouseMoved(me);
         public int getEyeGap() {
              return mEyeGap;
         public void setEyeGap(int gap) {
              mEyeGap = gap;
         public void setBlinkEyes(long timeBetweenBlinks) {
              mTimeBetweenBlinks = timeBetweenBlinks;
              if (mEyeBlinker != null) {
                   mEyeBlinker.cancel();
                   mEyeBlinker = null;
              if (timeBetweenBlinks < mBlinkAnimationSpeed * 8) {
                   return;
              else {
                   mEyeBlinker = new Timer(true); //allow it to be a daemon thread
                   mEyeBlinker.scheduleAtFixedRate(new BlinkEyesTask(), mTimeBetweenBlinks, mTimeBetweenBlinks);
                   //Thread t = new Thread(mEyeBlinkter);
                   //t.start();
          * makes the eyes blink
          * this method will not function correctly if it is run in the
          * GUI painter thread, as it handles the whole process and calls
          * repaint() sleep() in between steps.
         public void blink() {
              try {
                   //System.out.println("bat");
                   Thread t = Thread.currentThread();
                   mBlinkEyesState = 1;
                   repaint();
                   t.sleep(mBlinkAnimationSpeed);
                   mBlinkEyesState = 2;
                   repaint();
                   t.sleep(mBlinkAnimationSpeed);
                   mBlinkEyesState = 3;
                   repaint();
                   t.sleep(mBlinkAnimationSpeed);
                   mBlinkEyesState = 4;
                   repaint();
                   t.sleep(mBlinkAnimationSpeed);
                   mBlinkEyesState = 3;
                   repaint();
                   t.sleep(mBlinkAnimationSpeed);
                   mBlinkEyesState = 2;
                   repaint();
                   t.sleep(mBlinkAnimationSpeed);
                   mBlinkEyesState = 1;
                   repaint();
                   t.sleep(mBlinkAnimationSpeed);
                   mBlinkEyesState = 0;
                   repaint();
              catch (InterruptedException ex) {
                   if (mBlinkEyesState != 0) {
                        mBlinkEyesState = 0;
                        repaint();
         private class BlinkEyesTask extends TimerTask {
              public void run() {
                   blink();
          * @param angle Either Double.NaN for center, or a value between 0 and 2 PI
         public void setEye1Direction(double angle) {
              mEyeDir1 = angle;
         public double getEye1Direction() {
              return mEyeDir1;
          * @param angle Either Double.NaN for center, or a value between 0 and 2 PI
         public void setEye2Direction(double angle) {
              mEyeDir1 = angle;
         public double getEye2Direction() {
              return mEyeDir2;
         public void paintComponent(Graphics g) {
              int height = getHeight();
              int r = height / 2;
              g.setColor(Color.WHITE);
              g.fillOval(0, 0, height, height);
              g.fillOval(height + mEyeGap + 0, 0, height, height);
              g.setColor(Color.BLACK);
              g.drawOval(0, 0, height, height);
              g.drawOval(height + mEyeGap + 0, 0, height, height);
              g.setColor(getForeground());
              int irisR = (int) (r * mEyeRatio);
              if (Double.isNaN(mEyeDir1)) {
                   int x1 = (r - irisR);
                   int y1 = x1;
                   g.fillOval(x1, y1, irisR * 2, irisR * 2);
              } else {
                   int x1 = (r - irisR);
                   int y1 = x1;
                   x1 -= Math.cos(mEyeDir1) * (r - irisR);
                   y1 -= Math.sin(mEyeDir1) * (r - irisR);
                   g.fillOval(x1, y1, irisR * 2, irisR * 2);
              if (Double.isNaN(mEyeDir2)) {
                   int x1 = (r - irisR) + height + mEyeGap;
                   int y1 = (r - irisR);
                   g.fillOval(x1, y1, irisR * 2 , irisR * 2);               
              } else {
                   int x1 = (r - irisR) + height + mEyeGap;
                   int y1 = r - irisR;
                   x1 -= Math.cos(mEyeDir2) * (r - irisR);
                   y1 -= Math.sin(mEyeDir2) * (r - irisR);
                   g.fillOval(x1, y1, irisR * 2, irisR * 2);
    //          OLD
    //          if (Double.isNaN(mEyeDir1)) {
    //               int x1 = (r - irisR);
    //               int y1 = x1;
    //               g.fillOval(x1, y1, irisR * 2, irisR * 2);
    //               x1 += height + mEyeGap;
    //               g.fillOval(x1, y1, irisR * 2 , irisR * 2);               
    //          } else {
    //               int x1 = (r - irisR);
    //               int y1 = x1;
    //               x1 -= Math.cos(mEyeDir1) * (r - irisR);
    //               y1 -= Math.sin(mEyeDir1) * (r - irisR);
    //               g.fillOval(x1, y1, irisR * 2, irisR * 2);
    //               x1 = (r - irisR) + height + mEyeGap;
    //               y1 = r - irisR;
    //               x1 -= Math.cos(mEyeDir2) * (r - irisR);
    //               y1 -= Math.sin(mEyeDir2) * (r - irisR);
    //               g.fillOval(x1, y1, irisR * 2, irisR * 2);
              //Eye Blinking
              if (mBlinkEyesState != 0) {
                   Rectangle rect = new Rectangle(0,0,getWidth(), getHeight() * mBlinkEyesState / 4);
                   g.setClip(rect);
                   g.setColor(getBackground());
                   g.fillOval(0, 0, height, height);
                   g.fillOval(height + mEyeGap + 0, 0, height, height);
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Eyes eyes = new Eyes(true);
              eyes.setBlinkEyes(10000);
              eyes.setPreferredSize(new Dimension(60,25));
              eyes.setEyeGap(5);
              WindowUtilities.visualize(eyes);
    }Message was edited by:
    tjacobs01

    So, if you shake the panel long enough, do the
    contents disappear? :Dno but they get a big headache

  • Multiple textField and jlabels

    Hi there,
    I have done some work on swing component long time ago. I am trying to work on something new, that is why I was looking for some help.
    I like to build a Jframe/JPanel where I can have the following layout. I am not sure how to place all these texfields and labels and place them propotionately.
    label textfield label texfield
    label textfield label texfield
    label textfield label texfield
    label textfield label texfield
    label textfield label texfield
    GAP here
    label textfield label texfield
    label textfield label texfield
    Radio button
    checkboxes and Graph on this corner.
    I would really appreciate if I can get some pointers in starting this GUI.
    Thanks
    Syed

    I would really appreciate if I can get some pointers in starting this GUI.Read the Swing tutorial. Maybe start with the section on using Layout Managers:
    http://java.sun.com/docs/books/tutorial/uiswing/TOC.html

  • Java GUI question

    The class JFrame comes with several default buttons and a menu. I am wondering if/how you can remove those buttons and the menu options. In particular I am trying to remove the maximize and minimize and restore options from the bar, while leaving the close button.

    No, the JFrame comes with none of these. I suspect your IDE is adding them after you accept the option to 'Make an application from template'. I believe both JBuilder and Forte have these optional starters that provide you with a basic menu bar laden default application. You will have to go into the editor WISIWIG, or the code, and remove what you don't want. Another alternative is to build a JFrame from scratch and only add the menu item you desire. Don't be confused between the library classes and some piece of template script in your IDE ...there are NO default anythings on a JFame ... its just a blank container with a title bar.

  • How do I paint graphics in a JFrame created by netbeans GUI builder?

    I hope it's ok to ask netbeans questions here. Frustrated with Eclipse I'm trying netbeans. I went through the tutorial for the UI builder and I have no trouble laying out the usual swing widgets like JPanels, JButtons, etc. What I haven't figured out is how to mix ordinary graphics like Graphics.draw() with these components.
    Crude example: 2 JPanels in a JFrame. The one on the left has a JSlider bar. The one on the right has a line or something that gets bigger or smaller according to the slider bar.
    If I weren't using the UI builder I'd create a new class that is an extension of JPanel, and override paintComponent() with my draw commands. If I did that to a JPanel I layed out with the UI builder it would get lumped in with the protected code that's created on the fly and probably erased.
    So how do I mix swing components with ordinary graphics without breaking the netbeans UI builder form?
    Thanks,
    Apchar

    This forum is a Java language forum. The NetBeans site has a mailing list. Nabble forums also has NB forums. The contents of both are crossposted. So, you really should post NB use questions to one of them. Post only Java language questions here.
    You can add custom code to the guarded (blue) code blocks. Open a component's property window and select the code button at the top. This allows you to insert code in numerous locations within the guarded blocks and retain the code.
    You can also click a component's property's ellipsis (...) button to bring up the Property Editor dialog box, then select "Custom Code" from the dropdown list at the top of the dialog.
    Note: the above instructions are for NB 6

  • Can not refresh JFrame

    I am new to Java programming however I have undertaken a project to build a serial communication application using J2SE 1.4 w/javax.comm API. I am having a problem in which I detect a button click with action listener and post a JOptionPane message. Once the JOptionPane is closed I execute the desired task however the pane leaves a grey block overlaying the JFrame. I have been unable to figure out how to repaint the JFrame. Can anyone give me suggestions?
    Thanks
    D :-)

    A more active example:
    if (JOptionPane.showConfirmDialog(null, "Are you
    u sure?",
    "Are you sure?", JOptionPane.YES_NO_OPTION) ==
    N) == 0) {
    Thread t = new Thread(new Runnable() {
    public void run() {
    // Do your work in here!
    t.start();
    }This will leave the JFrame completely free to do
    whatever else it wants, so if you want it to do
    nothing, you may want to write a 'disableFrame()'
    method which disables everything, and perhaps stick a
    JProgressBar at the bottom to show that something's
    going on. This needs to be controlled via the 'run()'
    method.
    Let me know if this helps.
    RichardThanks Richard.
    Do I have to stop the thread explicitly. The task looks for a serial event.

  • Problem with setContentPane() in JFrame class

    I recently discovered a problem with the setContentPane method in the JFrame class. When I use setContentPane(Container ..), the previously existing contentPane remains in the stack. I have tried nullifying getContentPane(), and all manner of things, but, each time I use setContentPane, I have another instance of a JPanel in the stack.
    I'm using code similar to setContentPane(new CustomJPanel()); and each time the user changes screens, and a similar call to that is made, the old CustomJPanel instance remains in the stack. Can anyone suggest a way around this? On their own the panels do not take up very much memory, but after several hours of usage, they will build up.

    I tried what you suggested; it only resulted in a huge performance decrease. The problem with memory allocation is still there.
    Here is the method I use to switch screens in my app:
    public static void changeScreen (JPanel panel){
              try{
                   appFrame.setTitle("Wordinary : \""+getTitle()+"\"");
                   appFrame.setContentPane(panel);
                   appFrame.setSize(appFrame.getContentPane().getPreferredSize());     
                   appFrame.getContentPane().setBackground(backColour);
                   for (int i = 0; i < appFrame.getContentPane().getComponents().length; i++)
                        appFrame.getContentPane().getComponents().setForeground(textColour);
                   //System.out.println("Background colour set to "+backColour+" text colour set to "+textColour);
                   appFrame.validate();
              catch (Exception e){
                   //System.out.println("change");
                   e.printStackTrace();
    And it is called like this:
    changeScreen(new AddWordPanel());The instantiation of the new instance is what is causing the memory problems, but I can't think of a way around it.

Maybe you are looking for

  • Kernel panic after time machine migration after clean install of 107.3

    I had the hard drive replaced in in my mid 2009 17" MacBook pro. After the clean install of lion I migrated my data from time machine (lion) to the new clean partition.. Upon completion the machine is unresponsive. The progress wheel turning for 10 m

  • How to change "Save As" view

    I have 2 machines with Adobe reader 8.  When I do a save as they both open up with a view of List.  One PC is sorted by Date and the other by Name.  Can I change the view it starts at to default to detail?  and more important can I have it always sor

  • Preventing JTree updates from uncompleted JTable edits

    Hello there!! I have an applet that displays an xml file in a JTree. Each node of the table represents specific elements of the xml file (some are not displayed by design). Also on the applet is a JTable that updates the displayed information dependi

  • IDS 9.0.4.2, Progress bar and frm-13008

    Hello All, I downloaded and installed the 10g (9.0.4.2) demos as detailed in the installguide.html. When trying to open a canvas (layout editor) that contains my bean for the progress bar, I receive the frm-13008 error. I've searched OTN and Metalink

  • RE: Change Purchasing Group for vendor

    Hi SAP Guru, Can some guide me for the following issue:. When a PO is closed, we do not have the option to choose where we send it.  SAP will route the workflow to buyer of the PO. If someone from purchasing leaving the company and we need everything