2 JApplets in One

Hello I want to ask this: I have 1 Japplet working, this JApplet build some parameters that need the 2nd Applet, so my question is how can I pass the parameters to the 2nd applet and start the 2nd applet in the same screen of the first (without closing the first, becouse when the 2nd applet end have to return to the first applet), there is a way to do this?
Thanks very much

let's say you have 2 simple applets (based on panels)
applet1
import java.awt.*;
import javax.swing.*;
public class TestApplet extends JApplet
  public void init()
    setContentPane(new AppletPanel1());
class AppletPanel1 extends JPanel
  public AppletPanel1()
    setPreferredSize(new Dimension(400,300));
    add(new JLabel("Applet 1"));
}applet2
import java.awt.*;
import javax.swing.*;
public class TestApplet extends JApplet
  public void init()
    setContentPane(new AppletPanel2());
class AppletPanel2 extends JPanel
  public AppletPanel2()
    setPreferredSize(new Dimension(400,300));
    add(new JLabel("Applet 2"));
}now put them together as a cardlayout, and switch between 1 and 2
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TestApplet extends JApplet
  public void init()
    JPanel holdingPanel = new JPanel(new BorderLayout());
    final CardLayout cl = new CardLayout();
    final JPanel cardlayoutPanel = new JPanel(cl);
    cardlayoutPanel.add("1",new AppletPanel1());
    cardlayoutPanel.add("2",new AppletPanel2());
    JButton btn = new JButton("Switch Panels");
    btn.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae){
        cl.next(cardlayoutPanel);
    holdingPanel.add(cardlayoutPanel);
    holdingPanel.add(btn,BorderLayout.SOUTH);
    getContentPane().setLayout(new GridBagLayout());
    getContentPane().add(holdingPanel,new GridBagConstraints());
class AppletPanel1 extends JPanel
  public AppletPanel1()
    setPreferredSize(new Dimension(400,300));
    add(new JLabel("Applet 1"));
class AppletPanel2 extends JPanel
  public AppletPanel2()
    setPreferredSize(new Dimension(400,300));
    add(new JLabel("Applet 2"));
}

Similar Messages

  • Swing Applet Repainting during moving window

    Hi,
    I've run into a problem with my swing JApplet. One of the elements of my GUI is a JLabel that contains a single Image. After the GUI is created, a seperate thread changes the image and prompts the JPanel containing the JLabel to repaint().
    Now, this works perfectly with the AppletViewer using java 1.4.2.03. However, when I run the applet through Microsoft's Internet Explorer using Sun's VM 1.4.2.03 plugin, I notice a problem. If I take the window containing the applet and (assuming it is NOT maximized) move it around the screen, the JLabel's image will not always be drawn at the correct place. It will often overlap some of the other GUI elements.
    I read something that Threads and Applets don't mix which suggested using the SwingUtilities.invokeLater() function, but I need this Thread to sleep() and didn't know how to make it do so because I never see the Thread class through the invokeLater() method.
    It solves the problem if rather than have the JLabel repaint itself, I have the entire applet repaint itself, but this is not the ideal solution. Is there any way to determine when the window containing the applet is being moved and then force the applet to repaint itself entirely? Am I going about this wrong? Any help would be greatly appreciated!
    Thanks,
    B. Danny K.

    The content pane of a JApplet is a JPanel. So you need to use the getContentPane() method and cast the Compnent to a JPanel before you can use revalidate(). However, as you have discovered 99% of the time a validate() also works.
    Note, that is you are using a BorderLayout then you should be removing the old component before adding the new component.

  • How to make a Multiple-rows Swing menubar?

    Hello!
    I'd like to le JMenubar to show multi-rows automatically in JFrame or JApplet if one row can not show all menus.
    Does anyone know how to do it? (I've asked several times these days but seems no one knows answer)
    Thank you very much.

    If your design requires that many menubar items that it can't be displayed on a normal window, then perhaps you should reconsider your design. If you really think it is your only option than you can try changing the layout of the menubar.JMenuBar mb = new JMenuBar();
    mb.setLayout(new GridLayout(5, 2));

  • Problem casting an applet to myApplet

    Hi Java Folks,
    I am using 2 JApplets where one applet has to call a method on the other. When I use getAppletContext().getApplet(applet_htmlName) and try to cast it to myApplet, I get a ClassCastException. I would like to know if there is any other way to do this...
    Your immediate attention will be greatly appreciated.
    SK

    If you have 2 Applets ... are you really sure the one extending myApplet is the one you try to cast?
    Rommie.

  • Applet Menu Focus?

    Hi,
    I add some JMenus(with some JMenuItems) to a JMenuBar, and add the JMenuBar to a JApplet.
    One of the JMenuItems has an accelerator key("control H").
    When the applet is shown, the accelerator key doesn't work.
    If I press "any" JMenu/JMenuItems by mouse, then the accelerator key works.
    With the tests, I guess menus need the focus before they do something.
    Then how do menus get the focus when the JApplet is launched?
    When the JApplet is created, it calls method "setFocusable(true)", so the JApplet gets the focus,
    but how about the menus?
    Thanks!
    a cup of Java, cheers!
    Sha Jiang

    I may get something.
    The trouble occurs when I run the Applet by Eclipse,
    but when I run it with a real browser(e.g. FireFox 2, IE 6), the accelerator keys works well.

  • Any one know how to embed a Applet or JApplet into a JFrame?

    Thanks

    No because you put the frame inside the applet.
    Why would someone need to put an applet inside a frame?

  • Can some one help me to execute this program

    Curve is not displayed when this program is executed
    Write an applet to draw a red curve on a blue back ground which follows your mouse pointer. 
    Use anonymous inner classes.
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.*;
    <applet code="Curve" width=200 height=100>
    </applet>
    public class Curve extends Applet {
         int x, y;
         String msg = " ";
         public void init() {
              setBackground(Color.blue);
              setForeground(Color.red);
              addMouseMotionListener(new MouseMotionAdapter(){
                   public void mouseMoved(MouseEvent me) {
                        msg = "*";
                        x = me.getX();
                        y = me.getY();
                        showStatus("x="+x+" "+"y="+y);
                        repaint(x, y, 1, 1);
         public void paint(Graphics g) {
              g.drawString(msg,x, y);
    }     

    I buffered it then it started working but problem is buffer size is
    limited. When the buffer is full then we have to start fresh again.You have made a buffer with two arrays of ints - and that allows you to
    paint the last 300 mouse positions. This is OK if you want the curve to
    have a fixed length: a bit like a snake following the pointer around.
    To avoid losing the whole curve you can initialise the x[] and y[] arrays
    to something "offscreen". For example fill both arrays with -100. Then
    in your paint() method you should draw all 300 positions.
    If you want the complete curve from the start with nothing lost then you
    are going to have to use a different sort of buffer. What you do is to
    create a BufferedImage the same size as your applet. When you create
    it you fill the buffered image with the background colour of your applet.
    In the mouseMoved() method you draw the * at the appropriate place into
    the buffered image. (There are other drawing strategies at this point:
    you could draw a line connecting this point to the previous one.)
    Finally in paint() you simply draw the whole buffered image into the
    applet's window.
    There is a discussion and example of using images as buffers this way
    in Sun's Tutorial here: http://java.sun.com/docs/books/tutorial/2d/images/doublebuffering.html
    repaint (int x, int y, int width, int height) - How this method works.This method says that a part of the applet's window should be
    repainted as soon as possible. repaint() without any arguments is
    used to signal that all of the window should be repainted.
    I would not worry about the 4 argument form at this stage - get
    something working first. Later you might find the 4 argument form is
    more effecient.
    Is there any reason why you're using Applet and not JApplet? If not,
    I would use the newer classes. In that case you'll get the best help in
    the Swing forum.

  • Cannot access file from JApplet

    I have used the swingall.jar file with my JApplet for any
    version of IE. It gives one error
    i.e
    Cannot access file c:\prog\project
    I want to create a directory within c:\prog and also i want
    to write some files there. Pls help me.

    try this my friend!
    1.     Compile the applet
    2.     Create a JAR file
    3.     Generate Keys
    4.     Sign the JAR file
    5.     Export the Public Key Certificate
    6.     Import the Certificate as a Trusted Certificate
    7.     Create the policy file
    8.     Run the applet
    Susan
    Susan bundles the applet executable in a JAR file, signs the JAR file, and exports the public key certificate.
    1.     Compile the Applet
    In her working directory, Susan uses the javac command to compile the SignedAppletDemo.java class. The output from the javac command is the SignedAppletDemo.class.
    javac SignedAppletDemo.java
    2.     Make a JAR File
    Susan then makes the compiled SignedAppletDemo.class file into a JAR file. The -cvf option to the jar command creates a new archive (c), using verbose mode (v), and specifies the archive file name (f). The archive file name is SignedApplet.jar.
    jar cvf SignedApplet.jar SignedAppletDemo.class
    3.     Generate Keys
    Susan creates a keystore database named susanstore that has an entry for a newly generated public and private key pair with the public key in a certificate. A JAR file is signed with the private key of the creator of the JAR file and the signature is verified by the recipient of the JAR file with the public key in the pair. The certificate is a statement from the owner of the private key that the public key in the pair has a particular value so the person using the public key can be assured the public key is authentic. Public and private keys must already exist in the keystore database before jarsigner can be used to sign or verify the signature on a JAR file.
    In her working directory, Susan creates a keystore database and generates the keys:
    keytool -genkey -alias signFiles -keystore susanstore -keypass kpi135 -dname "cn=jones" -storepass ab987c
    This keytool -genkey command invocation generates a key pair that is identified by the alias signFiles. Subsequent keytool command invocations use this alias and the key password (-keypass kpi135) to access the private key in the generated pair.
    The generated key pair is stored in a keystore database called susanstore (-keystore susanstore) in the current directory, and accessed with the susanstore password (-storepass ab987c).
    The -dname "cn=jones" option specifies an X.500 Distinguished Name with a commonName (cn) value. X.500 Distinguished Names identify entities for X.509 certificates.
    You can view all keytool options and parameters by typing:
    keytool -help
    4.     Sign the JAR File
    JAR Signer is a command line tool for signing and verifying the signature on JAR files. In her working directory, Susan uses jarsigner to make a signed copy of the SignedApplet.jar file.
    jarsigner -keystore susanstore -storepass ab987c -keypass kpi135 -signedjar SSignedApplet.jar SignedApplet.jar signFiles
    The -storepass ab987c and -keystore susanstore options specify the keystore database and password where the private key for signing the JAR file is stored. The -keypass kpi135 option is the password to the private key, SSignedApplet.jar is the name of the signed JAR file, and signFiles is the alias to the private key. jarsigner extracts the certificate from the keystore whose entry is signFiles and attaches it to the generated signature of the signed JAR file.
    5.     Export the Public Key Certificate
    The public key certificate is sent with the JAR file to the whoever is going to use the applet. That person uses the certificate to authenticate the signature on the JAR file. To send a certificate, you have to first export it.
    The -storepass ab987c and -keystore susanstore options specify the keystore database and password where the private key for signing the JAR file is stored. The -keypass kpi135 option is the password to the private key, SSignedApplet.jar is the name of the signed JAR file, and signFiles is the alias to the private key. jarsigner extracts the certificate from the keystore whose entry is signFiles and attaches it to the generated signature of the signed JAR file.
    5: Export the Public Key Certificate
    The public key certificate is sent with the JAR file to the whoever is going to use the applet. That person uses the certificate to authenticate the signature on the JAR file. To send a certificate, you have to first export it.
    In her working directory, Susan uses keytool to copy the certificate from susanstore to a file named SusanJones.cer as follows:
    keytool -export -keystore susanstore -storepass ab987c -alias signFiles -file SusanJones.cer
    Ray
    Ray receives the JAR file from Susan, imports the certificate, creates a policy file granting the applet access, and runs the applet.
    6.     Import Certificate as a Trusted Certificate
    Ray has received SSignedApplet.jar and SusanJones.cer from Susan. He puts them in his home directory. Ray must now create a keystore database (raystore) and import the certificate into it. Ray uses keytool in his home directory /home/ray to import the certificate:
    keytool -import -alias susan -file SusanJones.cer -keystore raystore -storepass abcdefgh
    7.     Create the Policy File
    The policy file grants the SSignedApplet.jar file signed by the alias susan permission to create newfile (and no other file) in the user's home directory.
    Ray creates the policy file in his home directory using either policytool or an ASCII editor.
    keystore "/home/ray/raystore";
    // A sample policy file that lets a JavaTM program
    // create newfile in user's home directory
    // Satya N Dodda
    grant SignedBy "susan"
         permission java.security.AllPermission;
    8.     Run the Applet in Applet Viewer
    Applet Viewer connects to the HTML documents and resources specified in the call to appletviewer, and displays the applet in its own window. To run the example, Ray copies the signed JAR file and HTML file to /home/aURL/public_html and invokes Applet viewer from his home directory as follows:
    Html code :
    </body>
    </html>
    <OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    width="600" height="400" align="middle"
    codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,1,2">
    <PARAM NAME="code" VALUE="SignedAppletDemo.class">
    <PARAM NAME="archive" VALUE="SSignedApplet.jar">
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">
    </OBJECT>
    </body>
    </html>
    appletviewer -J-Djava.security.policy=Write.jp
    http://aURL.com/SignedApplet.html
    Note: Type everything on one line and put a space after Write.jp
    The -J-Djava.security.policy=Write.jp option tells Applet Viewer to run the applet referenced in the SignedApplet.html file with the Write.jp policy file.
    Note: The Policy file can be stored on a server and specified in the appletviewer invocation as a URL.
    9.     Run the Applet in Browser
    Download JRE 1.3 from Javasoft
    save this to write.jp
    keystore "/home/ray/raystore";
    // A sample policy file that lets a JavaTM program
    // create newfile in user's home directory
    // Satya N Dodda
    grant {
    permission java.security.AllPermission;
    save this to signedAppletDemo.java
    * File: @(#)SignedAppletDemo.java     1.1
    * Comment:     Signed Applet Demo
    * @(#)author: Satya Dodda
    * @(#)version: 1.1
    * @(#)date: 98/10/01
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.io.*;
    import java.awt.Color;
    * A simple Signed Applet Demo
    public class SignedAppletDemo extends Applet {
    public String test() {
    setBackground(Color.white);
         System.out.println(System.getProperty("user.home"));
         String fileName = System.getProperty("user.home") +
                        System.getProperty("file.separator") +
                        "newfile";
         String msg = "This message was written by a signed applet!!!\n";
         String s ;
         try {
         FileWriter fos = new FileWriter(fileName);
         fos.write(msg, 0, msg.length());
         fos.close();
         s = new String("Successfully created file :" + fileName);
         } catch (Exception e) {
         System.out.println("Exception e = " + e);
         e.printStackTrace();
         s = new String("Unable to create file : " + fileName);
         return s;
    public void paint(Graphics g) {
    g.setColor(Color.blue);
    g.drawString("Signed Applet Demo", 120, 50);
    g.setColor(Color.magenta);
    g.drawString(test(), 50, 100);

  • Problem with Thread in JApplet

    Hi,
    I am working on a project on pseudo random functions, and for that matter I have written a problem. Now I am working on a user interface (JApplet) for my program. Because some heavy calculations can occur, I want to keep track of the progress, and show that in my JApplet. To do so, I start a Thread in which the calculations take place. In my JApplet I want to show every second how far the proces is done. The strange thing is, that the status JLabel only appears when the whole proces is done, and the start button keeps pressed during the proces. If I run this in the applet viewer, I can see the status every second in my command box. You can see the applet here : applet
    The code concerning the start button's actionlistener (entire appletcode: [applet code|http://www.josroseboom.nl/PseudoRandomClusteringApplet.java]) :
              if(e.getSource()==start)
                   int[][] randomFuncties = new int[current+1][5];
                   int puntenHuidige, g, q, y, m, f;
                   boolean done;
                   Kern k;
                   for(int i = 0;i<=current;i++)
                        randomFuncties[i] = functies.getValues();
                   invoer.remove(knopjes);
                   startTijd = System.currentTimeMillis();
                   proces.setBounds(25,(current+4)*25, 2*this.getWidth()/3,75);
                   invoer.add(proces);
                   this.validate();
                   this.repaint();
                   for(int i = 0;i<=current;i++)
                        puntenHuidige = 0;
                        f = randomFuncties[i][0]; // important for instantiation of k, which is cut out here
                        done = false;
                        k.start();     // k is a Thread where heavy calculations are done
                        ((JLabel)(proces.getComponent(2))).setText("points done of current (" + q + ")");
                        this.repaint();
                        while(!done)
                             ((JLabel)(proces.getComponent(1))).setText("" + convertTime(System.currentTimeMillis() - startTijd));
                             ((JLabel)(proces.getComponent(3))).setText("" + k.getPuntenGehad()); // get the point done so far
                             ((JLabel)(proces.getComponent(5))).setText("" + ((100*k.getPuntenGehad())/q) + "%");
                             debug("q: " + q);
                             debug("point done: " + k.getPuntenGehad());
                             if(k.getPuntenGehad()==q)     //if all points are considered
                                  done=true;
                             this.validate();
                             this.repaint();
                             try
                                  Thread.sleep(1000);
                             catch(InterruptedException exception)
                                  debug("foutje met slapen: InterruptedException");
                             catch(IllegalMonitorStateException exception)
                                  debug("foutje met wachten: IllegalMonitorStateException");
                             debug("IN APPLET: yet another loop walk");
                        stringResultaten.add(k.geefResultaat());
                   klaarLabel.setBounds(this.getWidth()/4,(current+8)*25, this.getWidth()/2,25);
                   naarResultaat.setBounds(25+this.getWidth()/4,(current+9)*25, this.getWidth()/4,25);
                   invoer.add(klaarLabel);
                   invoer.add(naarResultaat);
                   this.validate();
                   this.repaint();
    Edited by: Jos on Sep 19, 2007 1:22 AM

    Never do anything that takes more than a fraction of a second in an actionPerformed method or similar GUI callback.
    The GUI stuff is all handled by a single thread called the "AWT Dispatcher" thread. That includes code in such callbacks. While it's executing your callback it can't do any kind of screen updating or response to other user events.
    Instead your actionPerformed should work with a separater "worker" thread, either it should launch a new thread, or release one you create (using wait and notify). Then, it returns without waiting. When the worker thread wants to update the GUI it uses EventQueue.invokeLater() or invokeAndWait() to run some (fast) code on the Dispatcher thread.

  • Avoiding the repaint of all components in an JApplet

    Hello everyone,
    Thannks to all who gave me advices for the two JComboBoxes I had...finally I found two "if" conditions in the actionPerformed of the first JComboo which restricted the list of elements posted in the second one.
    I have a much bigger problem now....The Applet contains an object which is an extension of JPanel, and in this extension there is a "paintComponent()" that creates a certain number of JButtons in a "for" loop. The problem I have is :
    How could I avoid this panel to be repainted every time the page containing the Applet is resized? Is it even possible( because from what I've been reading a "paint()" of the applet always calls for all the components' "repaint()".....I haven't even definned a "paint()" for the applet, .....and then, each button has an action listener that simply won't work after a repaint() of the whole applet. And honestly i'm starting to lose my mind a bit over all this......Oh, I had almost forgotten....the problem after re-sizing is that within the borders of the Panel there are always buttons created by the "for" loop ....and they are smaller and appear high up "north" in the panel...it's horrible!!!!!
    This is my code for the paintComponent() of the extension of the JPanel:
    public void paintComponent(Graphics g){
           g.drawLine (130,50,130,450);
           g.drawLine (129,50,129,450);
           g.drawLine (270,50,270,450);
           g.drawLine (271,50,271,450);
           g.drawString("Plateau no.", 80,40);
           g.setColor(ballon);
           g.fillArc(100,434,200,100,45,-270);
           System.out.println("I've been through paint");
        for(int i=0;i<13;i++)
           System.out.println("buton ok"+i);
           plateaux=new JButton();
    plateaux[i].setEnabled(true);
    plateaux[i].addActionListener(this);
    Color cri=new Color(240-15*i,0,0);
    plateaux[i].setBounds(130,60+30*i,139,15);
    plateaux[i].setBackground(cri);
    add(plateaux[i], null);
    g.drawString(" "+ (13-i),105,70+30*i);
    There's nothing else in the extension....only the paint ...it implements ActionListener.....
    Thankx in advance....I'd really apreciate it if someone could help me.....
    Ruxi

    To clear the background for each repaint add a call to super or use clearRect or fillRect (with the background color set, of course). If you don't do this you will get artifacts in your graphics.
    class GraphicComponent extends JPanel {
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // carry on...
    }Paint code is the place to render graphics and images, not for adding components. Add your components to the GUI in or via init. Generally is is useful to keep your drawing component separate from your other components.
    class GUIClass extends JApplet implements ActionListener {
        public void init() {
            JPanel buttonPanel = getButtonPanel();
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(buttonPanel, "South");
            getContentPane().add(new GraphicComponent());  // default center section
        private JPanel getButtonPanel() {
            JPanel panel = new JPanel(null);
            JButton[] plateaux = nw JButton[13];
            for(int i=0;i<plateaux.length;i++) {
                System.out.println("buton ok"+i);
                plateaux=new JButton("button " + i);
    plateaux[i].setEnabled(true);
    plateaux[i].addActionListener(this);
    Color cri=new Color(240-15*i,0,0);
    plateaux[i].setBounds(130,60+30*i,139,15);
    plateaux[i].setBackground(cri);
    panel.add(plateaux[i]);

  • How to open web pages from japplet??

    Hi
    Does anybody know how to open web pages from java japplet??
    Any help is apreciated!
    zick

    the getAppletContext() method of the Applet class will get you an AppletContext, with which you can call the ShowDocument(URL url) or ShowDocument(URL url, String target) method...
    check it out at http://java.sun.com/j2se/1.4/docs/api/java/applet/AppletContext.html
    have a good one :)
    Jay

  • Keeping a simple server open/listening for more than one connection

    Can someone please help me with a problem I am having. I'm running a server that accepts requests and processes data from a client. This program works FINE for one connection but as soon as I send the info to the server the connection closes and I have to manually restart the server to receive another connection from a client. I want to be able to keep the server open and accept multiple requests from the client without having to restart the server.java. I've looked in the forum and found some useful stuff but I still get this same error:
    Address in use: JVM_Bind
    Error during serialization
    Press any key to continue...
    I have included the code to my server.java file below. Like I said, it works perfectly for one connection but then closes down. Can anyone tell me where I need to add the code to make it stay open or if I even can. Seems unlogical that it wouldn't be able to. I'm just at a dead end on how to do it. Thanks in advance.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Server extends JApplet{
    * Create the serversocket and use its stream to receive serialized objects
    public void init(){
    ServerSocket ser = null;
    Date d = null;
    try {
    ser = new ServerSocket(8020,10);
    * This will wait for a connection to be made to this socket.
    Socket soc = ser.accept();
    InputStream o = soc.getInputStream();
    ObjectInput s = new ObjectInputStream(o);
    String str = (String) s.readObject();
    d = (Date) s.readObject();
    final String nametop = soc.getInetAddress().getHostName();
    name n = new name(nametop,str);
    n.name = soc.getInetAddress().getHostName();
    JOptionPane.showMessageDialog(null,"There is a problem at station " + n.name + ".\n\nProblem:\n" + n.problem + "." ,"Problem",JOptionPane.ERROR_MESSAGE);
    System.out.println(d);
    System.out.println(n.name);
    System.out.println(n.problem);
    s.close();
    catch (Exception e) {
    System.out.println(e.getMessage());
    System.out.println("Error during serialization");
    System.exit(1);
    }//end of server
    // Create a main method
    public static void main( String args[] )
    //String name = soc.getInetAddress().getHostName();
    // create a window in which applet will execute
    JFrame appWindow = new JFrame("Problem Report");
    // create an instance of the applet
    Server app = new Server();
    // set the window size
    appWindow.setSize( 400, 400 );
    // add applet to window
    appWindow.getContentPane().add( app );
    // Simulate the normal startup sequence for an applet
    app.init();
    app.start();
    appWindow.show(); //calls paint()
    // add window close event handler
    appWindow.addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e ) {
    System.exit( 0 );
    }//end of main
    }

    Hi! I suggest you to use different thread to realize a server functionality.
    First one server.java that has a main method and create at least two threads. One thread listens to the incoming connection request and stores the locally generated socket object into an static vector. The second thread will always look into this static vector. If there are sockets object in the vector, the second thread will take it out and process the connection request. These two threads should always be alive. The first thread lives in a endless loop while listening to the incoming connection request. The second thread is either waiting on the static vector or processing incoming connection request.
    If the expected incoming connection request will be too many for only one thread to process, you can create more threads in server.java at the beginning and they will all swith between two status: looking in the static vector or processing incoming connection request!
    Hope this will be help for you!

  • How to create complecated Header for JTable in a JApplet ?

    I have one JTable in a JApplet.
    I need to create a complecated header for the table. For that I have used a downloaded code in the URL http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html (First example).
    Instead of "GroupableHeaderExample.java", I have used my code "StatusReportPopupMenu.java".
    The program runs properly in appletviewer. But, when I try to open the same in IE 5.5, first it shows the message "Loading Java Applet" . Then it goes blank. The status bar shows the message: Start: applet not initialized". At the Java console of the browser, I could see the Exception as given below:
    java.lang.NullPointerException
         at GroupableTableHeaderUI.getHeaderHeight(GroupableTableHeaderUI.java:97)
         at GroupableTableHeaderUI.createHeaderSize(GroupableTableHeaderUI.java:118)
         at GroupableTableHeaderUI.getPreferredSize(GroupableTableHeaderUI.java:128)
         at javax.swing.JComponent.getPreferredSize(Unknown Source)
         at javax.swing.ViewportLayout.preferredLayoutSize(Unknown Source)
         at java.awt.Container.preferredSize(Unknown Source)
         at java.awt.Container.getPreferredSize(Unknown Source)
         at javax.swing.JComponent.getPreferredSize(Unknown Source)
         at javax.swing.ScrollPaneLayout.layoutContainer(Unknown Source)
         at java.awt.Container.layout(Unknown Source)
         at java.awt.Container.doLayout(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validate(Unknown Source)
         at sun.plugin.AppletViewer$AppletEventListener.appletStateChanged(Unknown Source)
         at sun.applet.AppletPanel.dispatchAppletEvent(Unknown Source)
         at sun.applet.AppletPanel.appletResize(Unknown Source)
         at java.applet.Applet.resize(Unknown Source)
         at java.applet.Applet.resize(Unknown Source)
         at java.awt.Component.setSize(Unknown Source)
         at sun.plugin.AppletViewer$AppletEventListener.appletStateChanged(Unknown Source)
         at sun.applet.AppletPanel.dispatchAppletEvent(Unknown Source)
         at sun.applet.AppletPanel.appletResize(Unknown Source)
         at java.applet.Applet.resize(Unknown Source)
         at java.awt.Component.setSize(Unknown Source)
         at StatusReportPopupMenu.init(StatusReportPopupMenu.java:245)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    I'm not able to figureout what should I do to correct the problem.
    Please help. This is very urgent.

    Hi,
    1. For this we have to use the
    authorisation object
    P_ORGIN
    2. It has got the following fields, on which authorisations can be controlled.
    AUTHC Authorization level
    INFTY Infotype
    PERSA Personnel Area
    PERSG Employee Group
    PERSK Employee Subgroup
    SUBTY Subtype
    VDSK1 Organizational Key
    Regards,
    Harish

  • How can I change my JApplet into a JApplication?

    I am working with a JApplet and am finding that some of my code only works in applications.
    So being new to this, I am clueless as to how to change my Applet into an Application. I understand the difference in definition between the two, but when it comes to looking at Applet Code and Application Code, I am not able to see a difference. (Other than an Applet stating "Applet")
    So, that being said how can I change my code so that it runs as an application and not an applet? Here is my current layout code
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    // Creating the main class
    public class test extends JApplet implements ActionListener
         // Defining of format information
         JLabel heading = new JLabel("McBride Financial Services Mortgage Calculator");
         Font newFontOne = new Font("TimesRoman", Font.BOLD, 20);
         Font newFontTwo = new Font("TimesRoman", Font.ITALIC, 16);
         Font newFontThree = new Font("TimesRoman", Font.BOLD, 16);
         Font newFontFour = new Font("TimesRoman", Font.BOLD, 14);
         JButton calculate = new JButton("Calculate");
         JButton exitButton = new JButton("Quit");
         JButton clearButton = new JButton("Clear");
         JLabel instructions = new JLabel("Please Enter the Principal Amount Below");
         JLabel instructions2 = new JLabel("and Select a Loan Type from the Menu");
         // Declaration of variables
         private double principalAmount;
         private JLabel principalLabel = new JLabel("Principal Amount");
         private NumberFormat principalFormat;
         private JTextField enterPrincipal = new JTextField(10);
         private double finalPayment;
         private JLabel monthlyPaymentLabel = new JLabel("  Monthly Payment    \t         Interest Paid    \t \t            Loan Balance");
         private NumberFormat finalPaymentFormat;
         private JTextField displayMonthlyPayment = new JTextField(10);
         private JTextField displayInterestPaid = new JTextField(10);
         private JTextField displayBalance = new JTextField(10);
         // Creation of the String of arrays for the ComboBox
         String [] list = {"7 Years @ 5.35%", "15 Years @ 5.50%", "30 Years @ 5.75%"};
         JComboBox selections = new JComboBox(list);
         // Creation of the textArea that will display the output
         private TextArea txtArea = new TextArea(5, 10);
         StringBuffer buff = null;
         // Initializing the interface
         public void init()
              // Creation of the panel design and fonts
              JPanel upper = new JPanel(new BorderLayout());
              JPanel middle = new JPanel(new BorderLayout());
              JPanel lower = new JPanel(new BorderLayout());
              JPanel areaOne = new JPanel(new BorderLayout());
              JPanel areaTwo = new JPanel(new BorderLayout());
              JPanel areaThree = new JPanel(new BorderLayout());
              JPanel areaFour = new JPanel(new BorderLayout());
              JPanel areaFive = new JPanel(new BorderLayout());
              JPanel areaSix = new JPanel(new BorderLayout());
              Container con = getContentPane();
              getContentPane().add(upper, BorderLayout.NORTH);
              getContentPane().add(middle, BorderLayout.CENTER);
              getContentPane().add(lower, BorderLayout.SOUTH);
              upper.add(areaOne, BorderLayout.NORTH);
              middle.add(areaTwo, BorderLayout.NORTH);
              middle.add(areaThree, BorderLayout.CENTER);
              middle.add(areaFour, BorderLayout.SOUTH);
              lower.add(areaFive, BorderLayout.NORTH);
              lower.add(areaSix, BorderLayout.SOUTH);
              heading.setFont(newFontOne);
              instructions.setFont(newFontTwo);
              instructions2.setFont(newFontTwo);
              principalLabel.setFont(newFontThree);
              monthlyPaymentLabel.setFont(newFontFour);
              displayInterestPaid.setFont(newFontFour);
              displayBalance.setFont(newFontFour);
              areaOne.add(heading, BorderLayout.NORTH);
              areaOne.add(instructions, BorderLayout.CENTER);
              areaOne.add(instructions2, BorderLayout.SOUTH);
              areaTwo.add(principalLabel, BorderLayout.WEST);
              areaTwo.add(enterPrincipal, BorderLayout.EAST);
              areaThree.add(selections, BorderLayout.NORTH);
              areaFour.add(calculate, BorderLayout.CENTER);
              areaFour.add(exitButton, BorderLayout.EAST);
              areaFour.add(clearButton, BorderLayout.WEST);
              areaFive.add(monthlyPaymentLabel, BorderLayout.CENTER);
              areaSix.add(txtArea, BorderLayout.CENTER);
              // Using the ActionListener to determine when each button is clicked
              calculate.addActionListener(this);
              exitButton.addActionListener(this);
              clearButton.addActionListener(this);
              enterPrincipal.requestFocus();
              selections.addActionListener(this);
         }

    baftos wrote:
    Here is one of the sites that explains the procedure:
    [http://leepoint.net/notes-java/deployment/applications_and_applets/70applets.html].
    But maybe you should try to fix the code that does not work as applet?
    Which one is it?
    >Here is one of the sites that explains the procedure:
    [http://leepoint.net/notes-java/deployment/applications_and_applets/70applets.html].
    But maybe you should try to fix the code that does not work as applet?
    Which one is it?
    The code that doesn't work in my applet is the exit button code
    else if (source == exitButton)
                        System.exit(1);
                   }I also can't get my program to properly validate input. When invalid input is entered and the user presses calculate, an error window should pop up. Unfortunately it isn't. I compile and run my applications/applets through TextPad. So when I try to test the error window by entering in invalid info, the applet itself shows nothing but the command prompt window pops up and lists errors from Java. Anyhow, here is the method I was told to use to fix it.
    private static boolean validate(JTextField in)
              String inText = in.getText();
              char[] charInput = inText.toCharArray();
              for(int i = 0; i < charInput.length; i++)
                   int asciiVal = (int)charInput;
              if((asciiVal >= 48 && asciiVal <= 57) || asciiVal == 46)
              else
                   JOptionPane.showMessageDialog(null, "Invalid Character, Please Use Numeric Values Only");
                   return false;
                   return true;
         }My Instructor told me to try the following, but I still can't get it to work.String content = textField.getText();
    if (content.length() != 0) {       
    try {          Integer.parseInt(content);  
    } catch (NumberFormatException nfe) {}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Can any one tell what is the problem in this code?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.util.*;
    public class AppletTest2 extends JApplet implements ActionListener,MouseMotionListener,WindowListener{
    JFrame fr = new JFrame("Visual Tool -- Work Flow Editor");
         JPanel panel1 = new JPanel();
         JPanel panel2 = new JPanel();
         JButton sButton = new JButton("Source");
         JButton rButton = new JButton("Redirection");
         JButton dButton = new JButton("Destination");
         JButton connect = new JButton("Connect");
         BasicStroke stroke = new BasicStroke(2.0f);
         int flag = 1 ;
         Vector lines = new Vector();
         JButton sBut,rBut,dBut;
    int x1 = 0 ;
         int y1 = 0 ;
         int x2 = 0 ;
         int y2 = 0;
         int x3 = 0;
         int y3 = 0;
         int i=0;
         int j=0;
         int k=0;
         int l = 100;
    int b = 50;
    public void init(){
              /*********Frame ******************/
    fr.getContentPane().setLayout(new BorderLayout());
         fr.setSize(700,500);
              fr.getContentPane().add(panel1,BorderLayout.CENTER);
              fr.getContentPane().add(panel2,BorderLayout.SOUTH);
              fr.addWindowListener(this);
              /*****************PANEL 1*********************/
              panel1.setLayout(null);
    panel1.setBounds(new Rectangle(0,0,400,400));
              panel1.setBackground(new Color(105,105,205));
    /************************PANEL 2 *************/
              panel2.setLayout(new FlowLayout());
              panel2.setBackground(new Color(105,205,159));
              panel2.add(sButton);
              panel2.add(rButton);
              panel2.add(dButton);
              panel2.add(connect);
              connect.setToolTipText("Use this button after selecting From and To position to connect");
              /***************************LISTENER********************/
    sButton.addActionListener(this);
              rButton.addActionListener(this);
              dButton.addActionListener(this);
              connect.addActionListener(this);
              fr.setVisible(true);     
              fr.setResizable(false);
         } // init clse
    /************************** START METHOD **********************************************/
              public void start(){                                 
                   System.out.println("inside start");
                   paint(panel1.getGraphics());
    /*******************************APPLET METHODS **************************************************/
              public void stop(){}
              public void destroy(){}
    /******************************MOUSE MOTION LISTENERS METHOD*************************************/
              public void mouseMoved(MouseEvent e){System.out.println("moved");}
              public void mouseDragged(MouseEvent e){System.out.println("dragged");}
    /***************************************ACTION EVENT IMPLEMENTAION *******************************/
         public void actionPerformed(ActionEvent e){
              if (e.getSource().equals(sButton)){          
              sourceObject("Source Object");          
              else if (e.getSource().equals(rButton)){          
              redirectionObject("Redirection");
              i = i+1;
              else if (e.getSource().equals(dButton)){
              destinationObject("Destination");
                   j= j+1;
              else if (e.getSource().equals(connect)){
                   System.out.println("am inside connect");                
                   paint(panel1.getGraphics());               
    else if(e.getSource().equals(sBut)){
                   System.out.println("am s button");                
                   x1 = sBut.getX() + l;
                   y1 = sBut.getY() + (b/2);
              else if(e.getSource().equals(rBut)){
                   System.out.println("am r button");               
                   x2 = rBut.getX() ;
                   y2 = rBut.getY()+ b/2;
                   System.out.println("x2 : " + x2 + "y2 :" +y2 );
              else if(e.getSource().equals(dBut)){
                   System.out.println("am d button");                
                   x3 = dBut.getX();
    y3 = dBut.getY()+ b/2;
    } // action close
    /**********************Main **********************************/     
         public static void main(String args[]){
         JApplet at = new AppletTest2();
              at.init();
              at.start();
    /********************my methods starts here *******************/
         public void sourceObject(String name){     
    sBut = new JButton(name);
         panel1.add(sBut);
         sBut.setBounds(new Rectangle(20,208,l,b));     
         sBut.addActionListener(this);
    System.out.println("am inside the source object") ;
         public void redirectionObject(String name){     
         rBut = new JButton(name);
         panel1.add(rBut);
         rBut.setBounds(new Rectangle(290,208,l,b));     
    rBut.addActionListener(this);
    System.out.println("am inside the redirection :" + j) ;
    public void destinationObject(String name){     
         dBut = new JButton(name);
         panel1.add(dBut);     
    System.out.println("am inside the destination object") ;
    if (j == 0)
                   dBut.setBounds(new Rectangle(566,60,l,b));                    
                   System.out.println("am inside the destination:" + j) ;
                   } else if (j == 2)
                        dBut.setBounds(new Rectangle(566,208,l,b));     
                        System.out.println("am inside the destination :" + j) ;
                   } else if (j == 1)
    dBut.setBounds(new Rectangle(566,350,l,b));     
                        System.out.println("am inside the destination :" + j) ;
    dBut.addActionListener(this);
    /* public void connectObject(Object obj1,Object obj2){
    System.out.println("nothing");
    /************************************* PAINT **************************/
    public void paint(Graphics g){
         System.out.println("inside paint");
         Graphics2D g2 = (Graphics2D) g;
         g2.setStroke(stroke);
    if(flag == 1){
    System.out.println("inside flag");
    int np = lines.size();
                        System.out.println(np);
                             for (int I=0; I < np; I++) {                       
         Rectangle p = (Rectangle)lines.elementAt(I);
                             System.out.println("width" + p.width);
                             g2.setColor(Color.red);
                             g2.drawLine(p.x,p.y,p.width,p.height);
                             System.out.println(p.x +"" +""+ p.y + ""+ ""+ p.width+ "" + ""+ p.height);
    flag = -1;
    }else if(flag == -1){
         if(x1 != 0 && y1 != 0 && x2 != 0 && y2 != 0 ){
    // Graphics2D g2 = (Graphics2D) g;
         // g2.setStroke(stroke);
    g2.setColor(Color.red);
         g2.drawLine(x1,y1,x2,y2);
         lines.addElement(new Rectangle(x1,y1,x2,y2));     
         x1 = 0 ;y1 = 0 ;
         x2 = 0 ;y2 = 0 ;
    //     g2.drawLine(100,100,200,200);
    else if (x2 != 0 && y2 != 0 && x3 != 0 && y3 != 0 )
              // Graphics2D g2 = (Graphics2D) g;
                   // g2.setStroke(stroke);
              g2.setColor(Color.green);
                        g2.drawLine(x2,y2,x3,y3);
                        lines.addElement(new Rectangle(x2,y2,x3,y3));
                        x2 = 0; y2 = 0 ;
                        x3 = 0 ; y3 = 0 ;                    
    else if (x1 != 0 && y1 != 0 && x3 != 0 && y3 != 0)
                   //     Graphics2D g2 = (Graphics2D) g;
                   // g2.setStroke(stroke);
                   g2.setColor(Color.red);
                   g2.drawLine(x1,y1,x3,y3);
                        lines.addElement(new Rectangle(x1,y1,x3,y3));                              
                        x1 = 0; y1 = 0 ;
                        x3 = 0 ; y3 = 0 ;                    
    // repaint();
    /********************************WINDOW LISTENER IMPLEMENTATION *****************************/
    public void windowActivated(WindowEvent we) { 
              flag = 1;
              paint(panel1.getGraphics());
    System.out.println("windowActivated -- event 1");
         //start();               
         public void windowClosed(WindowEvent we) {
                                                                System.out.println("windowClosed -- 2");
         public void windowClosing(WindowEvent we){
                                                                System.out.println("windowClosing -- 3");
    public void windowDeactivated(WindowEvent we) {
                                                                     System.out.println("windowDeactivated -- 4");
    public void windowDeiconified(WindowEvent we) {
                                                                     flag = 1;
                                                                     System.out.println("windowDeiconified -- 5");          
                                                                     paint(panel1.getGraphics());           
    public void windowIconified(WindowEvent we) {           
                                                           System.out.println("windowIconified -- 6");
                                                           //paint(panel1.getGraphics());
    public void windowOpened(WindowEvent we) {             
                                                      //     flag = 1;
                                                      //     paint(panel1.getGraphics());
                                                           System.out.println("windowopened -- 7");     
    The problem am facing here is that when i minimize the frame and maximize , my old lines are getting disappared.
    For avoiding that i am storing the old coordinates and
    try to redraw , when maximize.
    but the lines are coming for flash of second and disappearing once again ?
    can any one help?
    thanks all

    Very interestingly the same code is repainting in
    Linux SUSE,jdk1.3.
    but not in WINNT , jdk 1.3
    Any reason ?
    Is the swing 100 % platform independenet ?????
    Does swing also uses native thread ???

Maybe you are looking for

  • Address Book Entries gone!!

    All my address books entries have disapeared!! In the corner it says: Updated 28/06/2005 which is of course wrong. In my .mac account all entries are there, but also when I try to sync it nothing happens. Thank you for any help!! Powerbook   Mac OS X

  • MIDI, Gargeband, Camera connection kit...

    Current setup: I have a Kawai Digital Piano, with both a plain double MIDI connector, and a USB connector (also for MIDI). I use a normal USB <> USB cable purchased from BB to connect the piano to my MBP, where I use GarageBand to record and edit mus

  • POWERBUILDER 12.5 and ORACLE 12C DBNAME

    Dear all, As mentioned on other threads, PB 12.5.2 works with ORACLE 12C, but not officially supported. ORACLE 12C works with PB 12.6 Nevertheless, when I do try to work with ORACLE 12C and PB 12.5.2, when I created datawindow, on the Column specific

  • Mac to Mac via Ethernet?

    This is such a simple, stupid question that I'm sure that it has been answered many times, but although I have searched these fora diligently, I cannot find an answer; I suspect that the problem is that I'm using the wrong search terms. Here's the pr

  • What Are These Icons? (T510)

    These monstrous icons won't go away - reveal nothing with right or left click.  What are they?  Can I get rid of them?  (They are awful!) URL=http://s91.photobucket.com/albums/k315/HGabbert/?action=view&current=badcons-1.jpg][IMG]http://i91.photobuck