Multithreaded GUI creation

Hi,
I'm working on a project that uses EJB's for business work and Swing for the GUI.
The major problem is that the EJB's calls can be quite long to return.
As I am populating combos and tables from the results of these calls, it is problematic since it slows down the bring up of the GUI.
I have implemented a threaded model of the component loading.
I'd like to have your advise on this, if it's good or not and if there are possible improvements.
Here are the two classes I have build from now :
- this is the initComponents() part of the main class. It creats a PersonneChooser and waits until it has finished to load (in order to avoid NullPointerException due to calls to the paint() method of the main frame)
  private void initComponents() {
    try     {
      java.util.logging.Logger.getLogger("root").info("Creating PersonneChooser");
      PersonneChooser pc = new PersonneChooser();
      java.util.logging.Logger.getLogger("root").info("Done");
      pc.addActionListener(this);
      pc.getThread().join();
      this.getContentPane().add(pc);
      this.pack();
      this.setVisible(true);
    catch(SecurityException e) {
        System.out.println("Op not allowed");
  }- this is the PersonneChooser. It is a combo box populated with the objects returned from a call to an EJB method. It has an embeded renderer for the viewing.
public
  class PersonneChooser
  extends javax.swing.JComboBox
  implements Runnable {
    private Thread _thread = null;
    public Thread getThread() {
      return _thread;
    public void run() {
      java.util.logging.Logger.getLogger("root").config("Assigning PersonneChooserRenderer");
      setRenderer(new PersonneChooserRenderer());
      java.util.logging.Logger.getLogger("root").config("Populating combo");
      try {
     Iterator i = HomeCaching.getInstance().getCalendrier().getAllPersonnes().iterator();
     while(i.hasNext()) {
       addItem(i.next());
      java.util.logging.Logger.getLogger("root").config("Done");
      catch(Exception e) {
     e.printStackTrace();
    public PersonneChooser() {
      _thread = new Thread(this);
      _thread.start();
class PersonneChooserRenderer
  extends javax.swing.JLabel
  implements javax.swing.ListCellRenderer {
    public PersonneChooserRenderer() {
      setOpaque(true);
      setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
      setVerticalAlignment(javax.swing.SwingConstants.CENTER);
    public java.awt.Component getListCellRendererComponent(
      javax.swing.JList list,
      Object value,
      int index,
      boolean isSelected,
      boolean cellHasFocus) {
      if (isSelected) {
     setBackground(list.getSelectionBackground());
     setForeground(list.getSelectionForeground());
      else {
     setBackground(list.getBackground());
     setForeground(list.getForeground());
      PersonneValue pv = (PersonneValue)value;
      setText(pv.getNom() + " " + pv.getPrenom());
      return this;
}thanks,
ionel

Hi,
thanks for your reply.
I have changed my code to
      java.util.logging.Logger.getLogger("root").info("Creating PersonneChooser");
      PersonneChooser pc = new PersonneChooser();
      java.util.logging.Logger.getLogger("root").info("Done");
      pc.addActionListener(this);
      this.getContentPane().add(pc);
      this.pack();
      this.setVisible(true);for the initComponents() part
and
      java.util.logging.Logger.getLogger("root").config("Setting up self Action listening");
      addActionListener(this);
      java.util.logging.Logger.getLogger("root").config("Assigning PersonneChooserRenderer");
      setRenderer(new PersonneChooserRenderer());
      disable();But when I launch the app, i get an NPE
     [java] java.lang.NullPointerException
     [java]     at org.TechAdvantage.intranet.client.gui.PersonneChooserRenderer.getListCellRendererComponent(Unknown Source)
     [java]     at javax.swing.plaf.metal.MetalComboBoxButton.paintComponent(MetalComboBoxButton.java:143)
     [java]     at javax.swing.JComponent.paint(JComponent.java:804)
...I didn't understand what did you mean by "disable JComboBox in the event dispatch thread). Does the disable() method do this ? If so, why do I get the NPE ?
thanks,
ionel

Similar Messages

  • Using JDB in a multithreaded gui environment

    Hi there all I am currently working in a multithreaded gui environment, I would like to use jdb, I manged to launch my project using the jdb in place of the java command ( I did the javac -g thing), I then type run it all launches fine and I am prompted with main[]
    then I type cont abd then it starts I get prompted with > and I am stuck here no code list works I resume try everything but stuck in the treads is there a way of igmoring this and seleting the classes I want to debug I also tried setting breakpoints but htese nere get hit when I type clear I can seee the break point but dont hit thwem even thow those breakpointed sections of code is executed the break point dose not halt the code can anyone help regards Michael

    Hi there all I am currently working in a multithreaded
    gui environment, I would like to use jdb, I manged to
    launch my project using the jdb in place of the java
    command ( I did the javac -g thing), I then type run
    it all launches fine and I am prompted with main[]
    then I type cont abd then it starts I get prompted
    with >At this point your application is running. The ">"
    prompt means jdb has no current thread setting.
    Enter threads to see a list of the threads in
    your application.
    Enter classes to see the classes that are loaded.
    Enter fields className to see the fields of a class.
    Enter suspend to stop the debugee, and then enter where all
    to see the thread stacks, or use the thread command to set
    the current thread, then use the where command.
    A thread must be suspended (or at a breakpoint) and jdb must be set
    to the thread you want to examine (via the thread command,
    or automatically when you hit a breakpoint) before you can display
    the stack, do a list to see the source at that point, or
    use locals to see the local variables for that stack frame.
    Enter resume so the debugee threads will continue.
    and I am stuck here no code list works I resume
    try everything but stuck in the treads is there a way
    of igmoring this and seleting the classes I want to
    debug I also tried setting breakpoints but htese nere
    get hit when I type clear I can seee the break point
    but dont hit thwem even thow those breakpointed
    sections of code is executed the break point dose not
    halt the code can anyone help regards MichaelAre you using the full name of the class (including any
    package names) when setting breakpoints?

  • Dynamic gui creation

    Hi experts,
    I have a question regarding Web Dynpros possibilities to create dynamically gui. In my requirement I know only during runtime how many textboxes / checkboxes i will need.
    Is there a way to approach this in Web Dynpro ? With an jsp and the backend information it would be possible. Now I am asking me how I can make create something like a loop over a collection with the UI elements in Web Dynpro.
    Regards
    Flo

    This is probably more suited for the Web Dynpro forum.
    However, here's a document for Web Dynpro for java which contains a tutorial on Dynamic UI Manipulation:
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/74cda090-0201-0010-6b91-f85b2489f765
    There's some tutorials for Web Dynpro for ABAP as well. A search for Dynamic UI Manipulation should give you enough hits on the topic.

  • Programmatically Creation of Property Group

    Hello
    Can anyone help me to create a property group and then assign properties to it.
    It would be better if you can assist me either with the GUI creation or through programme or with both.
    Thanks
    Raj

    Create a New Group
    Using groups in the SAP Enterprise Portal is another way to easily manage the content that is rolled out to a user.  You can assign multiple roles to a group, and simplify your user management process by assigning a group to a user, instead of assigning multiple roles to a user.
    1.     Choose User Administration ¨ Groups ¨ Select New Group button.
    2.     Enter values for the following fields.
    3.     Choose Save.
    3.2.5     Add User to Group
    1.     Choose User Administration ¨ Groups.
    2.     Select Testers from the Groups menu
    3.     Choose the Assign Users button.
    4.     Choose the Add Users button.
    5.     Enter new
    6.     Choose Search.
    7.     Check the checkbox next to NewUser.
    8.     Choose Select.
    9.     Choose Done.
    3.2.6     Add Role to Group
    1.     Choose User Administration ¨ Roles.
    2.     In the Search parameter, enter the role you want to add to the user (i.e., com.mycompany.myrole).
    3.     In the Search dropdown. select Roles.
    4.     Select the Start button
    A list of matching roles will appear in the table below
    5.     Select the Edit link corresponding to the role you created
    6.     Enter new in the Search parameter
    7.     Select Groups in the dropdown menu
    8.     Choose Start.
    9.     Check the checkbox next to the Group you created
    10.     Choose Add and then Save.

  • Client and GUI concurrently ?????

    hi everybody,
    i got a problem about gui and client. I have created a jframe and i want it to e client which connects to a server and gets the server's message. The problem is; when i created gui first, it starts to listen actions and client can't run, or if i run client class first, it starts to listen server message in a loop on run() method of thread() so action listener can't be catch. The simulation of code is below. Please help me.
    public class GUILogin extends JFrame{
    public static void main(String args[]) {
    new Client("localhost",9999);
              new GUILogin().setVisible(true);
    public class Client implements Runnable{
    public Client(String host, int port) {
                   new Thread(this).start();          
    //LISTENS THE SERVER MESSAGE
         public void run() {
              String str;
              while ((str = readline()) != null) {
                   System.out.println(str);
    I can't decide where to put client creation and gui creation.

    İ think thi solve my problem, thanks much...
    public class GUILogin extends JFrame implements Runnable{
    public GUILogin {
    initializeGUI();
              socket = new Socket(host, port);
              out = new PrintWriter(socket.getOutputStream(), true);
              in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    public static void main(String args[]) {
    new GUILogin().setVisible(true);
    new Thread(this).start();
    public void run() {
    String str;
    while ((str = readline()) != null) {
    System.out.println(str);
    }

  • Making middle teir accessible to all gui class objects.

    I'm designing a user interface at the moment for a
    3 tier application. I've got a good knowledge of Java
    but have never written a complicated gui with Swing.....
    User Interface (GUI) --> Business Logic (JDBC classes) --> MYSQL DB
    As the diagram shows, I want to keep the business logic separate
    from the user interface.
    My problem is that I'm not sure the best way to give all the GUI's action listeners
    access to the business logic object's methods which will call and return information
    from the database to the UI.
    Had there just been one UI class it would be easy to create an instance of the
    business logic class from the UI class, but
    the GUI is made up of many class objects with larger componets being made
    up of several smaller component classes and so on. What I guess I'm unsure of
    is what the standard practice is in this situation. Is a case of getting the GUI creation class
    to create an instance of the business logic object and then pass it down through the many
    GUI class constructors so that each GUI class object can reference it?
    You thoughts are appreciated, many thanks,
    Andrew.

    The commom practice here is to use some design patterns.
    The ones you need are Proxy and DTO (Data Transfer Object).
    The reasons behind using a proxy patters are that your DB could
    change location, and you could have multiple GUI's using the
    same DB
    You will have several DTO's which will contain the data from your
    database. These DTO's are used to group data common to one use
    case, so that in order to complete the use case, you only need to
    remotely access the DB once. These Dto's are regular Java objects
    with just getter and setter methods.
    Your GUI uses a Proxy object to request a DTO.
    someting like... you need some data to fill a form or a table?
    GUIProxy proxy = ProxyServices.getGUIProxy();
    FormDataDto dto = proxy.getFormData();
    JTexField nameField = new JTextField();
    nameField.setText(dto.getCustomerName());
    etc...
    Notice how your GUI has no idea where the data lives,
    how its stored, etc. It just knows how to request it.

  • Java Graphics -- Drawing Strings on JFrame

    Hello and thank you. I'm relatively young and I apologize for asking noob questions. The problem I am having is that I realized after 3 hours of research and then writing this code that when multiple JPanels are added to a JFrame, they overlap (I think) over each other. As a result, the output of this program below is at the bottom right of the frame, the number 841 appears (the last number in my array) and everything else is blank.
    And I could not at all understand how to create graphics objects. It kept giving me an error of not being able to be instantiated. And to be honest, I don't even really understand whats going on when I add the text to my JPanel. I never call paintComponents. And definately I could never even make a graphics object to provide it the parameter required. Anyway, I resolved to use Jpanels because they can be removed using the remove function of the JFrame. And It is vitally important that I can delete the strings off my frame. Here is my code:
    package main;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class VisualFrame extends JFrame{
        ArrayList<JPanel> numbers = new ArrayList<JPanel>();
        public VisualFrame(){
            setSize(1000, 500);
            setTitle("Binary Search");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        public void createPanels(int[] array){
            int x = 10;
            int y = 20;
            int xOffset = 50;
            int yOffset = 50;
            for(int i=0; i<array.length; i++){
                String num = Integer.toString(array);
    numPanel panel = new numPanel(num, x, y);
    numbers.add(panel);
    add(panel);
    x = x+xOffset;
    if(x>this.getWidth()){
    x = 10;
    y = y+yOffset;
    class numPanel extends JPanel{
    String num;
    int x;
    int y;
    public numPanel(String str, int x, int y){
    num = str;
    this.x = x;
    this.y = y;
    public void paintComponent(Graphics g){
    g.setColor(Color.black);
    g.setFont(new Font("Times", Font.BOLD, 12));
    g.drawString(num, x, y);
    My main method is inside of a different class:
        public static void main(String[] args){
            VisualFrame frame = new VisualFrame();
            frame.createPanels(array);
        }Firstly, do I even have the problem I'm having right? If so,
    Is there a way to restrict the size of the panels to the length and width of what it contains?
    Or can someone give me a good, very detailed link to how to use Graphics? Or perhaps someone could prove to me a good method.
    Edited by: 989946 on Mar 8, 2013 6:45 PM

    Why don't you start by learning from the experts?
    The Java Tutorial has sections that show how to use Java functionality.
    http://docs.oracle.com/javase/tutorial/
    The Graphiics section covers GUI and Swing
    http://docs.oracle.com/javase/tutorial/uiswing/index.html
    >
    Creating Graphical User Interfaces
    Creating a GUI with Swing — A comprehensive introduction to GUI creation on the Java platform.
    >
    And that section has links for trails such as how to use ALL of the different swing components including frames and panels
    http://docs.oracle.com/javase/tutorial/uiswing/components/index.html
    >
    Using Swing Components tells you how to use each of the Swing components — buttons, tables, text components, and all the rest. It also tells you how to use borders and icons.

  • Catching unhandled exceptions

    Is there any way to catch all unhandled exceptions from the AWT event dispatch thread? Actually I want to display an error message in a dialog box for unhandled exceptions instead of printing to stderr.
    Although, for user threads this sort of thing can be easily done by extending ThreadGroup and overriding its uncaughtException() method, but this technique seemingly cannot be used with system threads.
    Any ideas will be highly appreciated.
    Thank you

    I checked the article referenced above and found the message listed below. This seems to be the solution that I am looking for. But I am in doubt whether it will work with non-Sun VMs, since the method relies on setting a Sun AWT specific system property. Can anyone confirm this?
    Re: Catching OutOfMemoryError in multithreaded GUI
    Author: wathed Jul 4, 2001 11:35 PM
    Can't find any documentation to back this up, but from the source it appears you can specify an exception handler to be called for Throwables on the AWT event thread:
    1) YourHandler should have a method:
    public void handle(Throwable t) {    ...}
    2) use the following when invoking:
    java -Dsun.awt.exception.handler=package.YourHandler MainClass

  • Applt unresponsive in Mac OS X

    This one is driving me nuts.
    For some obscure (to me at least) reason, my swing applet is totally
    unresponsive in OS X, although it works just fine in Windows. Here's
    the story:
    ~ Original version developed over a year ago, using JBuilder. Original design was not very complicated - little user
    interaction, mainly feedback text, progress bars and a cancel button.
    Since the IDE lacks a GUI-creation feature, opted for GridBagLayout
    mode, manually coding it. Worked perfectly well in both platforms.
    ~ About three weeks ago the client updated specs for the applet, and it
    involved a great deal of additional GUI stuff. Refused to code that
    manually, so I decided to use NetBeans (currently 6.5.1) for the new
    version. Creating the new GUI was a breeze, really, and I had it up and
    running in a couple of days. Everything looked nice and dandy up to
    here.
    ~ Next day, when I tried the applet on a Mac, I hit the
    no-java-1.6-for-OSX wall. Looked it up on the net and found this blog by
    Jim Blackler
    that explains why. Followed the directions, which involve setting
    NetBeans to work with JDK 1.5, and yes, the applet showed, but the GUI
    was completely distorted and it was unresponsive.
    ~ Great idea: download NetBeans for Mac and work from there. Long story short, the resulting applet worked perfectly well in Windows but was still unresponsive in Mac.
    ~ In an attempt to return to "known grounds", I changed the layout
    model back to GridBag, which led to a less-than-perfect result but
    still functional (in Win, that is). Tried again on the Mac and,
    although the GUI looked the intended way, it was still unresponsive.
    ~ Suspecting a bad java install on my Mac, I tried it on another one, with
    the same result. I even downloaded the newer Update 3, but there was no
    change.
    ~ After a bit of exchange at the Apple forums, I reinstalled NetBeans for Mac and debugged the applet
    with it. BTW, I went back to the GridLayout model and fixed it for Mac, and that's the version
    I debugged w/NetBeans. Funny enough, the applet ran like a charm from
    the IDE! In a heart-pounding minute I built/signed the jar and tried it
    in Safari, just to find that the darn thing was again unresponsive. Of course, it shines in Windows.
    Just to make things clear, by "unresponsive" I mean that the GUI
    elements do not respond to user interaction. I know for sure the applet
    is running - since the original version I included an optional Trace
    window, which let me make sure that everything runs well all the way to
    the start() method.
    I would gladly show any code here, but the thing is I don't think
    there's anything wrong with it - it runs well in Windows and the Mac NetBeans IDE. Actually I
    woudn't really know what to show. I guess it must be related to some configuration issue which I'm missing.
    Thanks in advance to anyone with a good idea!

    Good morning to both, and thanks macrules2 for your post.
    macrules2 wrote:
    I haven't read the entire thread (I know, I'm lazy), but there is one other place that stack traces can be dumped, and it's the console located in Applications/Utilities/Console.appChecked all of the logs and no, there's nothing in them. I even re-tested the applet from Safari and checked again (there should've been new entries) and nothing. Weird, I know.
    cotton.m wrote:
    I realize this is an ancient source but there is an example of running a signed applet here http://java.sun.com/developer/onlineTraining/Programming/JDCBook/signed.html#appli I really think you want to run this in appletviewer and see what's going on, this just has to be some sort of traceable error.
    After playing a bit with the settings (thanks for the link, btw) I was finally able to make it run in appletviewer from terminal... only to find out that yes, it works well, meaning no error/stack dump. Back to square one.
    I think I'll follow your idea of adding things to the dumb applet I made yesterday until it fails too... Rather lengthy and boring process, but I see no other way out at this point.
    I'll post whatever I find out. In the meantime, thank you so very much for your help.

  • Problem with CRM Content Management

    Hi all,
    I'm trying to specify a default folder template to use in business transactions, in order to show a default path in "Attachments" tab.
    I have configurated my template folder using the following IMG path:
    CRM-Basic Functions-Content Management-Define Templates for Folders.
    Now I suppose that I have to assign this template to a business object (for example, BUS2000111) in similar way as when I assign a folder path to a business partner role (CRM-Master Data-Business Partner-Basic Settings-Assign Templates for Content Management Folder to BP Roles).
    The problem is that I can't find the exact customizing point to do this.
    It's neccesary for the described configuration use the Document Modeler Workbench (DMWB)?
    It's possible to configure a default folder for business transactions or it's only a business partners or products feature?
    Could anybody help me please?
    Regards

    Hi All
       Content management fucntions are also available in PCUI on the attachmenst tab page.Integration with the archive link functionality.In customizing,you can define which documentation for the approriate business object is linked to the archive link fucntion.In Customizing select web application server >basis services >arachive link additionaly also you can create archive links documents from contentv management.Usage of filter profiles allows you to specify which documents are to be transferred.
    For technical information on content management go to help.sap.com>sap netweaver>web appl.server>basis services/communication interfaces(BC-SRV)>Knowledge provider(BC-SRV-KPR)>Content Management service(BC-SRV-KPR)
    IN GUI
    Creation of personal and general visible notes at document level. IMG>CRM>Basic functions>ContentManagement>Define document templates
    I hope this helps

  • Content Management problem

    Hello all,
    I am working with KM 5.0 SP 5 on two different portal environments, dev and qa. Everything seems to be working fine in qa (we installed there first), but I cannot get content management working in dev. Unfortunately, when we installed in qa, we had lots of problems getting it to work and did not get a good procedure documented for configuring content management.
    The problem that I'm having is when I go to 'Collaboration Admin', I receive an error in 'Initial Role Assignment' that reads:
    Java iView Runtime
    Version : 5.0.200212121529
    (c) 2001 SAP Portals
    The following exception occurred while processing your request:
    com.sapportals.portal.prt.runtime.PortalRuntimeException:  Exception ID 07:51_04/02/05_0014
    I get the same thing when I click on the 'Collaboration Room Administration', 'Initial Role Assignment', and 'Template Builder' iViews in the 'SAP Collaboration Room - Infrastructure: Collaboration Admin' channel.
    I have installed the following business packages in dev:
    BP Collaboration Room - General Template_50_1_1
    BP Collaboration Room - Infrastructure_50_1_1
    SP_FCS_SAP Collaboration Room - Infrastructure_50_1_5
    BP Collaboration Room - Project Template_50_1_1
    Business Package for Portal Users_50_5_1
    BUSINESS PACKAGE FOR COMMUNICATION_50_4_6
    Something interesting that I've noticed is the 'Collaboration Room Administration' iView. There appears to be some differences in the names of the Java attributes for this iView in dev and in qa. In qa, where the iView works, there are attributes called:
    Technical Name of WhoIsWhoMini Java iView
    Technical Names of Room Template Worksets (Separated By Semi-Colons)
    But in dev, the same attributes are called:
    Name of WhoIsWhoMini Java iView
    Names of Room Template Worksets
    Both iViews are based on the com.sapportals.pct.troom.ad.trwizard iView. I'm guessing that indicates some sort of inconsistancy between the instances, but I don't know where to look. I don't know if this is related to the Java error that I'm getting when I try to preview the iView, but I thought I would mention it.
    Can anyone give me some insight on what to do here?
    Thanks!
    -Stephen Spalding
    Graybar
    Web Developer

    Hi All
       Content management fucntions are also available in PCUI on the attachmenst tab page.Integration with the archive link functionality.In customizing,you can define which documentation for the approriate business object is linked to the archive link fucntion.In Customizing select web application server >basis services >arachive link additionaly also you can create archive links documents from contentv management.Usage of filter profiles allows you to specify which documents are to be transferred.
    For technical information on content management go to help.sap.com>sap netweaver>web appl.server>basis services/communication interfaces(BC-SRV)>Knowledge provider(BC-SRV-KPR)>Content Management service(BC-SRV-KPR)
    IN GUI
    Creation of personal and general visible notes at document level. IMG>CRM>Basic functions>ContentManagement>Define document templates
    I hope this helps

  • Create folders and navigate through server folder structure in Linux

    Hello,
    I want to know if there are any examples on how to reate folders and navigate through server folder structure in Linux OS. I currently can navigate trough Windows, but need to be able to do it in Linux, by using a GUI for it.
    Any suggestions? Thanks
    LabVIEW Intermediate I level!

    Hi Bebeto,
    Would you please clarify your question a bit for us? Are you trying to implement something like Windows Explorer in your application? Also, are you looking for a tree-like display structure, or list of folders that you can drill down into (i.e. double click to enter into that that folder). My understanding from your comments is that you have implemented something like this in Windows, but not Linux. It this correct? Also, are you looking for advice on the GUI creation side of things, or the programmatic access/creation of files and folders? The more you can clarify your question for us, the more the community will be able to provide feedback and suggestions to help you get on track qiuckly.
    Have a great afternoon!
    John M
    National Instruments
    Applications Engineer

  • Creating tables ADF/Swing

    Hello
    does anybody know the path to creating tables in ADF? it would have to be those with Headings for column sorting, row selection and the 3 standard buttons for insert, update, delete.
    I am reading and reading and they say they come pre-made, I created a table but it has none of the features I mentioned. I m trying to translate my web app into a desktop. I have separated the 2 projects, the DataModel with the Business Logic and now I am onto the GUI creation, though, ...stuck.
    Thanks a lot
    Message was edited by:
    AlvaroEP
    Message was edited by:
    AlvaroEP

    Hello,
    I think you are looking for a Junavigation bar, Which contains the standard buttons Insert record, Delete record, commit , rollback..
    In Componets... You need to select the "ADF Swing Controls"
    It will show you the different options... In that select the Junavigation bar and place it in your panel.
    Thanks,
    Guruprasad K

  • Some two threaded image prepare and painting applet coordination problem

    hi all,
    i'm sure this multithreaded gui is complex but anyway. a simple producer&consumer type applet. there is one seperate thread preparing an offscreen image, and the main guy draws it on applet. i can not coordinate them, what's wrong i don't know. simply, applet starts a thread, which paints something on an offscreen image, and then tells to applet repaint(). anyway, here is the code, this small png files are a lot, idea is making a view on them, just imagine a big big png file divided into matrices. afterall this is not the important part. what i see on the screen is, if you ask, nothing.
    thanx,
    ozz
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.lang.reflect.Array;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class MapViewer
         extends JFrame
         Image map[][];
         public MapViewer()
              int dimensions[] = { 58, 46 };
              map = (Image[][]) Array.newInstance(Image.class, dimensions);
              try
                   loadImages();
              catch(Exception e)
                   e.printStackTrace();
         public void loadImages()
              throws Exception
              for(int i=0; i<58; i++)
                   for(int j=0; j<46; j++)
                        StringBuffer sb = new StringBuffer();
                        sb.append("C:\\map\\");
                        sb.append(i+1);
                        sb.append("_");
                        sb.append(46-j);
                        sb.append(".png");
                        map[i][j] = Toolkit.getDefaultToolkit().getImage( sb.toString() );
         public void go()
              initComponents();
              show();
         private void initComponents()
              addWindowListener
                   new java.awt.event.WindowAdapter()
                        public void windowClosing(java.awt.event.WindowEvent evt)
                             exitForm(evt);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new MapPanel(), BorderLayout.NORTH);
              pack();
         private void exitForm(java.awt.event.WindowEvent evt)
              System.exit(0);
         public static void main(String args[])
              new MapViewer().go();
         private class MapPanel
              extends JPanel
              implements MouseMotionListener, Runnable
              private int north = 1;
              private int east = 2;
              private int south = 4;
              private int west = 8;
              private int direction;
              private Image model;
              private Boolean refreshModel = Boolean.TRUE;
              private Boolean modelReady = Boolean.FALSE;
              private Point start = new Point(200, 200);
              public MapPanel()
                   addMouseMotionListener(this);
                   new Thread(this).start();
              public synchronized Image requestImage()
                   return createImage(1600, 1600);
              public Dimension getMinimumSize()
                   return new Dimension(400, 400);
              public Dimension getPreferredSize()
                   return new Dimension(400, 400);
              public void paint(Graphics g)
                   synchronized(modelReady)
                        if(modelReady.booleanValue() == true)
                             g.drawImage(model, 0, 0, null);
                   g.setColor(Color.white);
                   g.fillRect(0, 0, 30, 10);
                   g.setColor(Color.black);
                   g.drawString(String.valueOf(direction), 0, 10);
              public void mouseDragged(MouseEvent e)
              public void mouseMoved(MouseEvent e)
                   Point p = e.getPoint();
                   findDirection(p);
              private void findDirection(Point p)
                   direction = 0;
                   if(p.x < 100)
                        direction |= west;
                   else if(p.x > 300)
                        direction |= east;
                   if(p.y < 100)
                        direction |= north;
                   else if(p.y > 300)
                        direction |= south;
              public void moveIt()
                   int px = 20;
                   int py = 20;
                   synchronized(refreshModel)
                        if(refreshModel.booleanValue() == true)
                             model = requestImage();
                             if(model == null || model.getGraphics() == null)
                                  return;
                             Graphics g = model.getGraphics();
                             for(int x=0; x < 4; x++)
                                  for(int y=0; y<4; y++)
                                       g.drawImage(map[px+x][py+y], x*200, y*200, null);
                             refreshModel = Boolean.FALSE;
                             modelReady = Boolean.TRUE;
    //               start.x -= 3;
    //               start.y -= 3;
              public void run()
                   while(true)
                        try
                             moveIt();
                             repaint();
                             Thread.currentThread().sleep(20);
                        catch(InterruptedException ie)

    Hi.
    The Graphics.drawImage method is asynchronyous, that may be the reason of the problem. Set an ImageObserver parameter in drawImage method, when drawing on an offscreen image. Count finished images and when all are done
    draw the big image on the screen.
    Alternatively you can call Toolkit.prepareImage method in a loop, after loadimages and wait until all images are loaded(true returned).

  • Applet won't finish loading

    Please bare with me as I'm new to Java. I'm using Eclipse 3.1.1. I'm working on a cheesy client server project to learn the language. I'm having difficulty with the client. It runs fine through Eclipse. When I compile my jar, sign it and run it from a web page it sits at loading. I do get my security prompt and when looking at the console I can watch my system.out... data run. My GUI just won't load. This is where my knowledge is really lacking. I think it might have to do with my infinite loop and the applet not loading completely but I'm shooting in the dark. A rough variation of my code is below. I didn't include the imports and I left out a lot of logic and objects. If I force the loop to never run (change the var to false for example) the GUI pops right up. I would really appreciate any insight (and a good reference for GUI creation). If possible please keep an answer simple, explain it, or reference something that a newbie can comprehend. I need to crawl before I can run. Thanks again!
    public class Client extends Applet implements ActionListener
         private JTextField txtStatus;
         // more gui objects
         public void init()
              DisplayGUI();
         public void start()
              try
                   Connect();
                   Listen();
              catch ( Exception e )
                   // error handling
         public void DisplayGUI()
              txtStatus = new JTextField( 5 );
              // more objects created
              setLayout( null );
              txtStatus.setBounds( 10, 370, 495, 25 );
              // position other objects
              add( txtStatus );
              // add other objects
              this.validate();
              this.addNotify();
              this.setVisible( true );
              resize( new Dimension( 600, 400 ) );
              repaint();
         public void actionPerformed( ActionEvent evt )
              // logic
         public void Connect() throws IOException
              channel = SocketChannel.open();
              socket = channel.socket();
              socket.setSoTimeout( 3000 );
              channel.connect( new InetSocketAddress( ipa, port ) );
         public void Listen( String sid )
              boolean connected = false;
              IsListening = true;
              while ( IsListening )
                   ByteBuffer buffer = ByteBuffer.allocate( 512 );
                   int bytesread;
                   try
                        bytesread = channel.read( buffer );
                   catch ( IOException e )
                        bytesread = -1;
                   if ( bytesread < 0 )
                        continue;
                   try
                        buffer.flip();
                        // grab buffer data
                        buffer.clear();
                        // process data
                   catch ( IOException e )
                        // error handling
                        IsListening = false;
                        connected = false;
                        break;
    }

    Also in your catch blocks you should print the stack trace of any exception thrown.
    Then you should look at the Applet console of your browser to see if there is any problem.
    Regards

Maybe you are looking for