ActionListener in Java

Hi
I have a performance question on ActionListener
One way to add an actionListener to a button is to do it this way
JButton[] button = new JButton[10];
for(int i=0;i<<10;i++)
     button[i] = new JButton();
     button.addActionListener(new ButtonActionListener());
class ButtonActionListener implements ActionListener
     public void actionPerformed(ActionEvent event)
//some code
is the example above more memory consuming then
this version
ButtonActionListener actionButtonClass = new ButtonActionListener()
JButton[] button = new JButton[10];
for(int i=0;i<<10;i++)
     button[i] = new JButton();
     button.addActionListener(actionButtonClass);
class ButtonActionListener implements ActionListener
     public void actionPerformed(ActionEvent event)
//some code
Markus

Hi there
thanx for your answears but...
In the case above all those buttons are activating different tools so my actionlistener looks like this
class BALhistoryBP implements ActionListener
     public void actionPerformed(ActionEvent event)
          hideWindow(currentWindow);
          if(event.getActionCommand().equals("moveexam"))
               currentWindow = 9;
          else if(event.getActionCommand().equals("newexam"))
               currentWindow = 7;
          else if(event.getActionCommand().equals("import"))
               currentWindow = 12;
          else if(event.getActionCommand().equals("export"))
               currentWindow = 13;
          showWindow(currentWindow);
          back(currentWindow);
}Is it still a good way to create an object of this class and provide it to each button
as in example 2 posted above?
Or should there be a new listener for each button (don't seem right)
Markus
One more question
I have detected that a mouse listener seems slower then an actionlistener is this true?
(Or is it my imagination)

Similar Messages

  • Java.awt.Dialog in Java 1.6 has a memory leak

    When a modal Dialog opens a modal sub-dialog, the Dialog stays in memory after both the sub-dialog and the Dialog itself is disposed.
    The field that contains the leaked object is Dialog.modalDialogs (static). The methods which causes the leak are Dialog.modalHide and Dialog.modalShow.
    Whenever a modal Dialog is opened, Dialog.modalShow is called, and adds itself to Dialog.modalDialogs.
    When it closes, Dialog.modalHide is called and removes one copy of itself from Dialog.modalDialogs. Then Dialog.modalShow is called on all previously blocked modal dialogs. When the sub-dialog is opened and closed, Dialog.modalDialogs contains two references to the main Dialog, and only one of them is removed when Dialog.modalHide for that Dialog is called.
    To detect the leak, just put a break point in Dialog.modalHide, after modalDialogs.remove(this);. When opening a Dialog and closing it without opening a sub-dialog, the Dialog.modalDialogs field should be empty. When a sub-dialog was opened and closed before the main Dialog is closed, the Dialog.modalDialogs field contains a reference to the disposed main Dialog.
    This leak does not exist in 1.5.0_10 (no Dialog.modalDialogs field). I have searched the bug database, but I have not found this bug there. Could anyone confirm this?
    A simple code to reproduce the leak:
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    public class Test {
       public static void main(String[] args) {
          final JFrame frame = new JFrame() {
             protected void processWindowEvent(WindowEvent e) {
                super.processWindowEvent(e);
                if (e.getID() == WindowEvent.WINDOW_CLOSING) {
                   System.exit(0);
          JButton button = new JButton("Dialog");
          button.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent aE) {
                JButton subButton = new JButton("SubDialog");
                subButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent aE) {
                      JOptionPane.showMessageDialog(frame, "SubDialog");
                JOptionPane.showMessageDialog(frame, subButton);
          frame.getContentPane().add(button);
          frame.pack();
          // Center the window
          Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          Dimension frameSize = frame.getSize();
          if (frameSize.height > screenSize.height) {
             frameSize.height = screenSize.height;
          if (frameSize.width > screenSize.width) {
             frameSize.width = screenSize.width;
          frame.setLocation((screenSize.width - frameSize.width) / 2,
                (screenSize.height - frameSize.height) / 2);
          frame.setVisible(true);
    }

    Sorry, I just found the bug in the bugdatabase (with google of course,):
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6497929]

  • Socket example using Java 5

    Last year I posted 4 programs that provided a simple client server using both stream sockets and NIO. I decided as an exercise in using Java 5 to port that code and try to use as many of the new features as possible. The following code is very long and does what all the previous example programs did. In replies do not repost the whole of this message.
    It provides a simple chat like client and server. The user can request either a stream connection or a NIO connection or provide one of their own.
    //========================== MsgSwitch.java ===========================//
    package pkwnet.msgswitch;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    import java.util.logging.Handler;
    * main class for message switch
    * command line arguments are
    * -p port number for server
    * -s run server
    * -a server ip address including port for client
    * -i idle timer in seconds
    * -n use NIO
    * -c specify connection class
    public class MsgSwitch {
        static private int errors = 0;
        static private String address = "127.0.0.1:6060";
        static private String connectionClass = "pkwnet.msgswitch.StreamConnection";
        static public void main(String [] args) {
            int port = 6060;
            int idleTime = 600;
            boolean server = false;
            boolean nio = false;
            Logger logger = Logger.getLogger("msgswitch");
            for(String arg : args) {
                if(arg.startsWith("-a")) {
                    address = arg.substring(2);
                } else if(arg.startsWith("-p")) {
                    port = argToInt(arg);
                    server = true;
                } else if(arg.startsWith("-i")) {
                    idleTime = argToInt(arg);
                } else if (arg.startsWith("-s")) {
                    server = true;
                } else if (arg.startsWith("-c")) {
                    connectionClass = arg.substring(2);
                } else if (arg.startsWith("-n")) {
                    connectionClass = "pkwnet.msgswitch.NIOConnection";
                } else {
                    String err = "unknown argument=" + arg;
                    logger.severe(err);
                    System.err.println(err);
                    errors++;
            if (errors == 0) {
                if (server) {
                    new Server().listen(port,idleTime, nio);
                } else {
                    new Client().start(address, nio);
            } else {
                fail(errors + " errors encountered", null);
        static private int argToInt(String arg) {
            int val = 0;
            try {
                val = Integer.parseInt(arg.substring(2));
            } catch (NumberFormatException e) {
                String err = "invalid argument format: " + arg;
                Logger.getLogger("msgswitch").severe(err);
                System.err.println(err);
                errors++;
            return val;
        static public void fail(String err, Throwable e) {
            String msg = "Operation terminated: " + err;
            Logger.getLogger("msgswitch").log(Level.SEVERE, msg, e);
            System.err.println(msg);
            System.exit(12);
        static public Connection getConnection() {
            Connection conn = null;
            try {
                conn = (Connection) Class.forName(connectionClass).newInstance();
            } catch (Exception e) {
                fail ("connection class error", e);
            return conn;
        static public void logCaller(Logger logger, Level level) {
            String text = "CALLED";
            if (logger.isLoggable(level)) {
                try {
                    throw new Exception("logging stack");
                } catch (Exception e) {
                    StackTraceElement [] st = e.getStackTrace();
                    if (st.length > 1) {
                        text += formatElement(st[1]);
                    if (st.length >2) {
                        text += formatElement(st[2]);
                logger.log(level, text);
        static private String formatElement(StackTraceElement ste) {
            return "\n    " + ste.getClassName() + "." + ste.getMethodName()
                + "(" + ste.getFileName() + ":" + ste.getLineNumber() + ")";
    //================= Client.java =============================================//
    package pkwnet.msgswitch;
    * a simple Swing chat GUI using Java 5 and sockets.
    * @author PKWooster
    * @version 1.0 August 31,2005
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JDialog;
    import javax.swing.SwingUtilities;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.BorderLayout;
    import static java.awt.BorderLayout.*;
    client GUI class
    public class Client extends JFrame implements ConnectionListener {
         // swing GUI components
         private JTextField userText = new JTextField(40);
         private JTextArea sessionLog = new JTextArea(24,40);
         private JTextField statusText = new JTextField(40);
         private JPanel outPanel = new JPanel();
         private JScrollPane sessionLogScroll = new JScrollPane(sessionLog);
         private JMenuBar menuBar = new JMenuBar();
         private JMenuItem startItem = new JMenuItem("Start");
         private JMenuItem hostItem = new JMenuItem("Host");
         private JMenuItem aboutItem = new JMenuItem("About");
         private JMenuItem abortItem = new JMenuItem("Abort");
         private JMenuItem exitItem = new JMenuItem("Exit");
         private JMenu fileMenu = new JMenu("File");
         private JMenu helpMenu = new JMenu("Help");
         private Container cp;
         private String address;
        private Connection connection;
        private boolean sendReady = false;
        private boolean nio = false;
         Client() {
        public void start(String address, boolean nio) {
            this.address = address;
            this.nio = nio;
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    runClient();
        private void runClient() {   
            connection = MsgSwitch.getConnection();
            connection.addConnectionListener(this);
              buildMenu();
              cp = getContentPane();
              sessionLog.setEditable(false);
              outPanel.add(new JLabel("Send: "));
              outPanel.add(userText);
              // enter on userText causes transmit
              userText.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){userTyped(evt);}
              cp.setLayout(new BorderLayout());
              cp.add(outPanel,NORTH);
              cp.add(sessionLogScroll,CENTER);
              cp.add(statusText,SOUTH);
              setStatus("Closed");
              addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    mnuExit();
              pack();
            setVisible(true);
    * attempt to send the contents of the user text field
        private void userTyped(ActionEvent evt) {
            if (sendReady) {
                String txt = evt.getActionCommand()+"\n";
                userText.setText("");
                toSessionLog("> ", txt);
                sendReady = false;
                connection.send(txt);
    * append text to the session log
         private void toSessionLog(String prefix, String txt) {
              sessionLog.append(prefix + txt);
              sessionLog.setCaretPosition(sessionLog.getDocument().getLength() ); // force last line visible
    * build the standard menu bar
         private void buildMenu()
              JMenuItem item;
              // file menu
              startItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuStart();}});
              fileMenu.add(startItem);
              hostItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuHost();}});
              fileMenu.add(hostItem);
              exitItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuExit();}});
              fileMenu.add(exitItem);
              menuBar.add(fileMenu);
              helpMenu.add(aboutItem);
              aboutItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuAbout();}});
              menuBar.add(helpMenu);
              setJMenuBar(menuBar);
    * start and stop communications from start menu
         private void mnuStart() {
            if(connection.getState() ==  Connection.State.CLOSED) {
                connection.connect(address);
            } else {
                connection.disconnect();
    *  prompt user for host in form address:port
        private void mnuHost() {
              String txt = JOptionPane.showInputDialog("Enter host address:port", connection.getAddress());
              if (txt == null)return;
            address = txt;
         private void mnuAbout() {
              JDialog dialog = new JDialog(this, "About Client");
              JTextField text = new JTextField("Simple character client");
            dialog.getContentPane().add(text);
            dialog.pack();
            dialog.setVisible(true);
         // exit menu
         private void mnuExit() {
            exit();
        private void exit() {
              connection.disconnect();
              System.exit(0);
         private void setStatus(String st) {
            statusText.setText(st);
         private void setStatus(Connection.State state) {
            switch(state) {
                case OPENED:
                    startItem.setText("Stop");
                    setStatus("Connected to "+address);
                    break;
                case CLOSED:
                    startItem.setText("Start");
                    setStatus("Disconnected");
                    break;
                case OPENING:
                    setStatus("Connecting to "+address);
                    startItem.setText("Abort");
                    break;
                case CLOSING:
                    setStatus("Disconnecting from "+address);
                    startItem.setText("Abort");
                    break;
        public void stateChanged(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
        public void dataAvailable(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
                    String txt = event.getData();
                    if (txt == null) {
                        txt = "$null$";
                    toSessionLog("< ", txt + "\n");   
        public void sendAllowed(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
                    sendReady = true;
        public void accept(ConnectionEvent event) {
    //========================== Server.java ===============================//
    package pkwnet.msgswitch;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    * a simple message switch using stream based socket i/o
    * a very simple text message switching program
    * user commands start with $ and consist of blank seperated arguments
    * other lines sent by the user are forwarded
    * $on nickname targets
    *    sign on as nickname, sending to targets
    * $to targets
    *    change target list, reports current value
    * $list nicknames
    *    list status of specified nicknames
    * $list
    *    list all connected users
    * $off
    *    sign off
    * @author PKWooster
    * @version 1.0 September 1, 2005
    public class Server {
        private ConcurrentHashMap<String, User> perUser = new ConcurrentHashMap<String,User>();
        private Timer idleTimer;
        private Connection conn;
        public void listen(int port, final int idleTime, boolean nio) {
            idleTimer = new Timer();
            idleTimer.scheduleAtFixedRate(new TimerTask(){public void run(){oneSec();}},0,1000);
            conn = MsgSwitch.getConnection();
            conn.addConnectionListener(new ConnectionListener() {
                public void stateChanged(ConnectionEvent event) {
                public void dataAvailable(ConnectionEvent event) {
                public void sendAllowed(ConnectionEvent event) {
                public void accept(ConnectionEvent event) {
                    Connection uconn = event.getConnection();
                    new User(uconn, perUser, idleTime);
            conn.listen(port);
            idleTimer.cancel();
        private void oneSec() {
            Collection<User> uc = perUser.values();
            for(User u : uc) {
                u.oneSec();
    //================= User.java  ==============================================//
    package pkwnet.msgswitch;
    import java.io.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.atomic.AtomicInteger;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    * defines the processing for a message switch user
    * @author PKWooster
    * @version 1.0 June 15,2004
    public class User implements ConnectionListener {
        private ConcurrentHashMap<String, User> perUser;
        private String name;
        private String address;
        private boolean signedOn = false;
        private String[] targets;
        private AtomicInteger remainingTime;
        private int idleTime;
        Connection conn;
        Logger logger;
      * construct a user, link it to its connection and put it in the perUser table
        User(Connection conn, ConcurrentHashMap<String,User>p, int idle) {
            this.conn = conn;
            logger = Logger.getLogger("msgswitch.user");
            conn.addConnectionListener(this);
            address = conn.getAddress();
            logger.info("creating user " + address);
            perUser = p;
            idleTime = idle;
            remainingTime = new AtomicInteger(idleTime);
            rename(address);
            targets = new String[0];
    * process state changes
        public void stateChanged(ConnectionEvent event) {
            if(event.getState() == Connection.State.CLOSED) {
                close(false);
    * data is available, process commands and forward other data.
        public void dataAvailable(ConnectionEvent event) {
            String msg = event.getData();
            if (msg.startsWith("$")) {
                doCommand(msg);
            } else {
                forward(msg);
            remainingTime.set(idleTime);
    * do nothing for sendAllowed events
        public void sendAllowed(ConnectionEvent event) {
    * do nothing for accept events
        public void accept(ConnectionEvent event) {
    * called once per second by the server main thread.
        public void oneSec() {
            if(idleTime != 0 && 1 > remainingTime.decrementAndGet()) {
                close(true);
    * send a message
        private void send(String msg) {
            conn.send(msg);
            remainingTime.set(idleTime);
    * forward data messages to other users
    * @param txt the message to send
        private void forward(String txt) {
            txt = name+": "+txt + "\n";
            if(0 < targets.length) {
                for(String target :targets) {
                    User user = perUser.get(target);
                    if(user != null) {
                        user.send(txt);
            } else {
                for (User user : perUser.values()) {
                    if (user != this) {
                        user.send(txt);
    * execute command messages, commands start with a $
    * and contain arguments delimited by white space.
    * @param command the command string
        private void doCommand(String command) {
            boolean good = false;
            command = command.substring(1).trim();
            if(command.length() > 0) {
                String [] args = command.split("\\s+");
                if(args[0].equals("on")) {
                    good = signOn(args);
                } else if(args[0].equals("off")) {
                    good = signOff(args);
                } else if(args[0].equals("list")) {
                    good = listUsers(args);
                } else if(args[0].equals("to")) {
                    good = setTargets(args,1);
                } else if(args[0].equals("idle")) {
                    good = setIdle(args);
                if(!good) {
                    send("invalid command=" + command + "\n");
    * sign on command
        private boolean signOn(String [] args) {
            boolean good = false;
            if(args.length >1) {
                String nm = args[1];
                logger.info("signing on as: " + nm);
                if(rename(nm)) {
                    conn.setName(name);
                    send("Signed on as " + name + "\n");
                    signedOn = true;
                    good = true;
                    setTargets(args,2);
                } else {
                    send("name="+nm+" already signed on\n");
            return good;
    * set forwarding targets
        private boolean setTargets(String [] args, int start) {
            if(start < args.length) {
                targets = new String[args.length-start];
                System.arraycopy(args, start, targets, 0, targets.length);
            String str = "to=";
            for(String target : targets) {
                str += (target + " ");
            send(str+"\n");
            return true;
    * set idle timeout
        private boolean setIdle(String[] args) {
            try {
                idleTime = new Integer(args[1]).intValue();
                remainingTime.set(idleTime);
                send("idle time set to "+idleTime+"\r\n");
                return true;
            } catch(NumberFormatException exc) {
                return false;
    * sign off
        private boolean signOff(String [] args) {
            close(true);
            return true;
    * list connected users
        private boolean listUsers(String [] args) {
            TreeSet<String> allUsers = new TreeSet<String>(perUser.keySet());
            HashSet<String> t = new HashSet<String>(Arrays.asList(targets));
            LinkedList<String> users;
            String response = "On,Target,Nickname\n";
            if(args.length < 2) {
                users = new LinkedList<String>(allUsers);
            } else {
                users = new LinkedList<String>();
                for (int i = 1; i < args.length; i++) {
                    users.add(args);
    for(String username : users) {
    if(username.equals(name)) {
    response += "*,";
    } else {
    response += (allUsers.contains(username) ? "y," : "n,");
    response += (t.contains(username) ? "y," : "n,");
    response += (username + "\n");
    send(response);
    return true;
    * rename this user, first we attempt to add the new name then we remove
    * the old one. Both names will be registered for a short while.
    * @param newname the new name for this user
    * @return true if the rename was successful
    private boolean rename(String newname) {
    boolean b = false;
    logger.info("rename name="+name+" newname="+newname);
    if (name != null && name.equals(newname)) {
    b = true;
    } else if (null == perUser.putIfAbsent(newname, this)) {
    if (name != null) {
    perUser.remove(name);
    name = newname;
    b = true;
    return b;
    * delete from perUser and close our connection
    private void close(boolean disconnect) {
    logger.info("closing user "+name);
    perUser.remove(name);
    if (disconnect) {
    conn.disconnect();
    //====================== Connection.java ===============================//
    package pkwnet.msgswitch;
    import java.util.HashSet;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    public abstract class Connection {
    public enum State {CLOSED, OPENING, OPENED, CLOSING}
    private HashSet<ConnectionListener> listeners = new HashSet<ConnectionListener>();
    private State state = State.CLOSED;
    private String host = "127.0.0.1";
    private int port = 6060;
    private String name = "unconnected";
    public Connection() {
    public abstract void listen(int port);
    public abstract void connect(String address);
    public abstract void disconnect();
    public abstract void send(String message);
    public void addConnectionListener(ConnectionListener listener) {
    listeners.add(listener);
    public void removeConnectionListener(ConnectionListener listener) {
    listeners.remove(listener);
    protected void fireDataAvailable(String data) {
    for (ConnectionListener listener : listeners) {
    listener.dataAvailable(new ConnectionEvent(this, state, data));
    private void fireStateChanged() {
    for (ConnectionListener listener : listeners) {
    listener.stateChanged(new ConnectionEvent(this, state));
    protected void fireSendAllowed() {
    for (ConnectionListener listener : listeners) {
    listener.sendAllowed(new ConnectionEvent(this, state));
    protected void fireAccept(Connection conn) {
    for (ConnectionListener listener : listeners) {
    listener.accept(new ConnectionEvent(this, conn));
    protected void setState(State state) {
    if (this.state != state) {
    this.state = state;
    fireStateChanged();
    public State getState() {
    return state;
    protected void setAddress(String address) {
              int n = address.indexOf(':');
              String pt = null;
    setName(address);
    if(n == 0) {
                   host = "127.0.0.1";
                   pt = address.substring(1);
              else if(n < 0) {
                   host = address;
                   port = 5050;
              } else {
    host = address.substring(0,n);
                   pt = address.substring(n+1);
    if (pt != null) {
    try {
    port = Integer.parseInt(pt);
    } catch (NumberFormatException e) {
    port = -1;
    public String getName() {
    return name;
    public void setName(String value) {
    name = value;
    public String getAddress() {
    return host + ":" + port;
    public String getHost() {
    return host;
    public void setPort(int value) {
    port = value;
    public int getPort() {
    return port;
    //=================== ConnectionEvent.java ================================//
    package pkwnet.msgswitch;
    public class ConnectionEvent extends java.util.EventObject {
    private final String data;
    private final Connection.State state;
    private final Connection conn;
    public ConnectionEvent(Object source, Connection.State state, String data, Connection conn) {
    super(source);
    this.state = state;
    this.data = data;
    this.conn = conn;
    public ConnectionEvent(Object source, Connection.State state, String data) {
    this(source, state, data, null);
    public ConnectionEvent(Object source, Connection.State state) {
    this(source, state, null, null);
    public ConnectionEvent(Object source, Connection conn) {
    this(source, conn.getState(), null, conn);
    public Connection.State getState() {
    return state;
    public String getData() {
    return data;
    public Connection getConnection() {
    return conn;
    //============================ ConnectionListener.java ===================//
    package pkwnet.msgswitch;
    public interface ConnectionListener extends java.util.EventListener {
    public void stateChanged(ConnectionEvent event);
    public void dataAvailable(ConnectionEvent event);
    public void sendAllowed(ConnectionEvent event);
    public void accept(ConnectionEvent event);
    //============================ StreamConnection.java ===================//
    package pkwnet.msgswitch;
    import java.net.Socket;
    import java.net.ServerSocket;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.IOException;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    * provides stream socket i/o of character strings
    * @author PKWooster
    * @version 1.0 September 1, 2005
    public class StreamConnection extends Connection {
    private Socket sock;
    private BufferedReader in;
    private BufferedWriter out;
    private Thread recvThread = null;
    private Thread sendThread = null;
    protected LinkedBlockingQueue<String> sendQ;
    Logger logger;
    public StreamConnection() {
    super();
    logger = Logger.getLogger("msgswitch.stream");
    sendQ = new LinkedBlockingQueue<String>();
    * open a socket and start i/o threads
    public void connect(String ipAddress) {
    setAddress(ipAddress);
    try {
    sock = new Socket(getHost(), getPort());
    connect(sock);
    } catch (IOException e) {
    logger.log(Level.SEVERE, "Connection failed to=" + ipAddress, e);
    private void connect(Socket sock) {
    this.sock = sock;
    String ipAddress = getAddress();
    try {
    in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
    recvThread = new Thread(new Runnable() {
    public void run() {
    doRecv();
    },"Recv." + getName());
    sendThread = new Thread(new Runnable() {
    public void run() {
    doSend();
    },"Send."+getName());
    sendThread.start();
    recvThread.start();
    setState(State.OPENED);
    } catch(IOException e) {
    logger.log(Level.SEVERE, "Connection failed to="+ipAddress, e);
    public void listen(int port) {       
    StreamConnection sconn;
    setPort(port);
    try {
    ServerSocket ss = new ServerSocket(port);
    while(true) {
    Socket us = ss.accept();
    sconn = new StreamConnection();
    String ipAddress = us.getInetAddress() + ":" + us.getPort();
    sconn.setAddress(ipAddress);
    sconn.connect(us);
    fireAccept(sconn);
    } catch(Exception e) {
    logger.log(Level.SEVERE, "listen failed", e);
    * close the socket connection
    public void disconnect() {
    logger.fine("disconnect sock=" + sock + " state="+ getState());
    if(getState() == State.OPENED) {
    setState(State.CLOSING);
    try {
    sock.shutdownOutput();
    } catch(IOException ie) {
    logger.log(Level.SEVERE, "showdown failed", ie);
    } else if(getState() != State.CLOSED) {
    try {
    sock.close();
    } catch(Exception e) {
    logger.log(Level.SEVERE, "close failed", e);
    if (sendThread.isAlive()) {
    sendThread.interrupt();
    sendQ.clear();
    setState(State.CLOSED);
    public void send(String message) {
    if (getState() == State.OPENED) {
    try {
    sendQ.put(message);
    } catch(InterruptedException e) {
    logger.log(Level.SEVERE, "sendQ put interrupted", e);
    setState(State.CLOSING);
    disconnect();
    * sets the public name of this connection
    public void setName(String name) {
    super.setName(name);
    if (sendThread != null) {
    try {
    recvThread.setName("recv." + name);
    sendThread.setName("send." + name);
    } catch(Exception e) {
    logger.log(Level.SEVERE, "nameing threads failed", e);
    * the main loop for the send thread
    private void doSend() {
    String msg;
    boolean running = true;
    while (running) {
    if (sendQ.size() == 0) {
    fireSendAllowed();
    try {
    msg = sendQ.take();
    out.write(msg);
    out.flush();
    } catch(Exception e) {
    if (getState() == State.OPENED) {
    logger.log(Level.SEVERE, "write failed", e);
    setState(State.CLOSING);
    disconnect();
    running = false;
    * the main loop for the receive thread
    private void doRecv() {
    String inbuf;
    while (getState() == State.OPENED) {
    try {
    inbuf = in.readLine();
    } catch(Exception e) {
    if (getState() == State.OPENED) {
    logger.log(Level.SEVERE, "readline failed", e);
    inbuf = null;
    if(inbuf == null) {
    logger.fine("null received on: " + getAdd

    Here are three of them:
    NIO server
    NIO client
    Multithreaded server
    The stream based client example seems to have been deleted, probably lost in the troll wars. I also posted a new Simple multithreaded server that uses the same protocol. As the client is missing, I'll repost it.

  • How to use another java program to stop this running prpgram???

    Dear Sir:
    I have following code and I run it success,
    import java.util.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    public class CertainAndRepeatTime{
      public static void main(String[] args) throws IOException{
        int delay = 1;
        Timer timer = new Timer();
        ActionListener actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
              System.out.println("Hello World Timer");
        System.out.println("What do you want (Certain time or Repeat time)?");
        System.out.print("Please enter \'C\' or \'R\' for that: ");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String ans = in.readLine();
        System.out.print("Please enter  ans=" + ans  + " IsTrue=  " + (ans.equals("R") || ans.equals("r")) +"\n");
        if (ans.equals("C") || ans.equals("c")){
          //System.out.println("This line is printed only once start...");
          timer.schedule(new TimerTask(){
            public void run(){
              System.out.println("This line is printed only once.");
          },delay,1);
        else if(ans.equals("r") || ans.equals("R")){
            timer.scheduleAtFixedRate(new TimerTask(){
              public void run(){
                System.out.println("This line is printed repeatedly.");
            },delay, 1000);
          while(true){
               //System.out.println("Charles print This line is printed repeatedly.");          
          } //This will make your main thread hang.
        else{
          System.out.println("Invalid Entry.");
          System.exit(0);
        System.exit(0);
    }But I hope to use another java program to stop it when it is running instead of pressing CRTL + C to stop it.
    How to do it??
    Any example??
    Thanks a lot!!

    Sorry, I think i did not express cearly. It is my fault.
    I re-write my requirements again:
    I have
    Class AAA1.java,
    Class AAA2.java,
    Class AAA3.java,
    Class AAA20.java...
    etc
    they all look like the program I posted first time,, once executed, they will run for ever, and they will be stopped until I press CRTL + C;
    Now I hope to use another java class StopProgram.java to stop them 1 by 1 or at once instead of pressing CRTL + C;
    In this case, how to code this StopProgram.java ??
    Thanks

  • Clickable/Linked Text in Java Applet

    Hi,
    I have always liked this tool http://link-verify.sourceforge.net/index.en.html and have always wanted to modify it to make the "referer" clickable so that I could easily click to link to the page that had the broken link more easily.
    The source code is available and well with the hard economic times I have time to finally modify this to work how I would like.
    Can anyone tell me how I would go about accomplishing this? I am a seasoned ASP.NET programmer and understand the overall logic, etc... It is just the Java syntax that I am missing.
    Basically I can discern that in source code, LinkFrame.java to be exact on line 308 the "referreeP" panel is being populated with a refL=new List(), where refL is a List that is populated as each link is processed as the applet runs.
    How can I make each of those items in the refL list clickable is my primary question for you all. Do I have to use some sort of listener on each item in the list, is that even the right approach to take.
    Any and all thoughts appreciated!
    PS - I want to shout out to Ralf Wiebicke for creating this wonderful tool, it has been a wonderful developer tool for me over the years.

    >
    Basically I can discern that in source code, LinkFrame.java to be exact on line 308 the "referreeP" panel is being populated with a refL=new List(), where refL is a List that is populated as each link is processed as the applet runs.
    How can I make each of those items in the refL list clickable is my primary question for you all. >Questions usually end with a question mark. Where is yours?
    If you check the JavaDocs for List, you will notice it has methods [addActionListener(ActionListener|http://java.sun.com/javase/6/docs/api/java/awt/List.html#addActionListener(java.awt.event.ActionListener)] ) and [addItemListener(ItemListener)|http://java.sun.com/javase/6/docs/api/java/awt/List.html#addItemListener(java.awt.event.ItemListener)]. Either of those listeners will detect actions/selections on the List.
    As for showing the links, look to [AppletContext.showDocument(URL)|http://java.sun.com/javase/6/docs/api/java/applet/AppletContext.html#showDocument(java.net.URL)].
    As an aside, the AWT widgets such as List are very old-hat. If you wanted to take on a bigger upgrade, you might convert the app. to use Swing.

  • Creating login screens in java

    hello.
    this is james mcfadden. i am trying to create a login screen in java. the problem i have is this: i am completely new to GUI programming. i know that i have to use strings. the code shown below is incomplete and when i try to compile it i get the following errors. how do i go about fixing these errors?
    ----jGRASP exec: javac -g X:\CP4B Project\LogOn.java
    LogOn.java:11: ']' expected
    username[0]="Administrator";
    ^
    LogOn.java:11: <identifier> expected
    username[0]="Administrator";
    ^
    LogOn.java:12: ']' expected
    username[1]="Ann Smyth";
    ^
    LogOn.java:12: <identifier> expected
    username[1]="Ann Smyth";
    ^
    LogOn.java:13: ']' expected
    username[2]="John Murphy";
    ^
    LogOn.java:13: <identifier> expected
    username[2]="John Murphy";
    ^
    LogOn.java:14: ']' expected
    username[3]="James McFadden";
    ^
    LogOn.java:14: <identifier> expected
    username[3]="James McFadden";
    ^
    LogOn.java:15: ']' expected
    username[4]="Frankie Ferry";
    ^
    LogOn.java:15: <identifier> expected
    username[4]="Frankie Ferry";
    ^
    LogOn.java:16: ']' expected
    username[5]="Daniel McKimm";
    ^
    LogOn.java:16: <identifier> expected
    username[5]="Daniel McKimm";
    ^
    LogOn.java:17: ']' expected
    username[6]="Stephen Doohan";
    ^
    LogOn.java:17: <identifier> expected
    username[6]="Stephen Doohan";
    ^
    LogOn.java:18: ']' expected
    username[7]="James Ferry";
    ^
    LogOn.java:18: <identifier> expected
    username[7]="James Ferry";
    ^
    LogOn.java:19: ']' expected
    username[8]="Liam Cannon";
    ^
    LogOn.java:19: <identifier> expected
    username[8]="Liam Cannon";
    ^
    LogOn.java:20: ']' expected
    username[9]="Ciaran Ferry";
    ^
    LogOn.java:20: <identifier> expected
    username[9]="Ciaran Ferry";
    ^
    LogOn.java:21: ']' expected
    username[10]="Ciaran McGee";
    ^
    LogOn.java:21: <identifier> expected
    username[10]="Ciaran McGee";
    ^
    LogOn.java:23: ']' expected
    password[0]="0";
    ^
    LogOn.java:23: <identifier> expected
    password[0]="0";
    ^
    LogOn.java:24: ']' expected
    password[1]="1";
    ^
    LogOn.java:24: <identifier> expected
    password[1]="1";
    ^
    LogOn.java:25: ']' expected
    password[2]="2";
    ^
    LogOn.java:25: <identifier> expected
    password[2]="2";
    ^
    LogOn.java:26: ']' expected
    password[3]="3";
    ^
    LogOn.java:26: <identifier> expected
    password[3]="3";
    ^
    LogOn.java:27: ']' expected
    password[4]="4";
    ^
    LogOn.java:27: <identifier> expected
    password[4]="4";
    ^
    LogOn.java:28: ']' expected
    password[5]="5";
    ^
    LogOn.java:28: <identifier> expected
    password[5]="5";
    ^
    LogOn.java:29: ']' expected
    password[6]="6";
    ^
    LogOn.java:29: <identifier> expected
    password[6]="6";
    ^
    LogOn.java:30: ']' expected
    password[7]="7";
    ^
    LogOn.java:30: <identifier> expected
    password[7]="7";
    ^
    LogOn.java:31: ']' expected
    password[8]="8";
    ^
    LogOn.java:31: <identifier> expected
    password[8]="8";
    ^
    LogOn.java:32: ']' expected
    password[9]="9";
    ^
    LogOn.java:32: <identifier> expected
    password[9]="9";
    ^
    LogOn.java:33: ']' expected
    password[10]="10";
    ^
    LogOn.java:33: <identifier> expected
    password[10]="10";
    ^
    LogOn.java:57: <identifier> expected
         button1.addActionListener(new ActionListener(){
    ^
    LogOn.java:72: ';' expected
    ^
    46 errors
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class LogOn extends JPanel{
         private static JTextField username=null;
         private static JPasswordField password=null;
         private static JButton button1=null;
       private static JButton button2=null;
         String[] username=new String[11];
       username[0]="Administrator";
       username[1]="Ann Smyth";
       username[2]="John Murphy";
       username[3]="James McFadden";
       username[4]="Frankie Ferry";
       username[5]="Daniel McKimm";
       username[6]="Stephen Doohan";
       username[7]="James Ferry";
       username[8]="Liam Cannon";
       username[9]="Ciaran Ferry";
       username[10]="Ciaran McGee";
       String[] password=new String[11];
       password[0]="0";
       password[1]="1";
       password[2]="2";
       password[3]="3";
       password[4]="4";
       password[5]="5";
       password[6]="6";
       password[7]="7";
       password[8]="8";
       password[9]="9";
       password[10]="10";
       public LogOn(){
              setSize(260,160);
              username=new JTextField(15);
            password=new JPasswordField(15);
              JLabel usernameLabel=new JLabel("Username: ");
              JLabel passwordLabel=new JLabel("Password: ");
              add(usernameLabel);
              add(username);
              add(passwordLabel);
              add(password);
              setVisible(true);
              button1=new JButton("Ok");
              add(button1);
            button2=new JButton("Cancel");
              add(button2);
              JFrame frame=new JFrame("Welcome to Home Entertainment");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(this);
            frame.pack();
            frame.setVisible(true);
         button1.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
                 try{
                        Demo d = new Demo();
                        d.getChoice();
                   catch(Exception ex){}
         button2.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
                 System.exit(0);
    }

    1. You initialize your array before your constructor.
    2. You have the same names for your arrays as for your TextFields
    3. You did not close your anon Listeners.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MyLogOnScreen extends JPanel{
         private static JTextField username=null;
         private static JPasswordField password=null;
         private static JButton button1=null;
        private static JButton button2=null;
         String[] usernameArray=new String[11];
        String[] passwordArray=new String[11];
       public MyLogOnScreen(){
            usernameArray[0]="Administrator";
            usernameArray[1]="Ann Smyth";
            usernameArray[2]="John Murphy";
            usernameArray[3]="James McFadden";
            usernameArray[4]="Frankie Ferry";
            usernameArray[5]="Daniel McKimm";
            usernameArray[6]="Stephen Doohan";
            usernameArray[7]="James Ferry";
            usernameArray[8]="Liam Cannon";
            usernameArray[9]="Ciaran Ferry";
            usernameArray[10]="Ciaran McGee";
            passwordArray[0]="0";
            passwordArray[1]="1";
            passwordArray[2]="2";
            passwordArray[3]="3";
            passwordArray[4]="4";
            passwordArray[5]="5";
            passwordArray[6]="6";
            passwordArray[7]="7";
            passwordArray[8]="8";
            passwordArray[9]="9";
            passwordArray[10]="10";
              setSize(260,160);
              username=new JTextField(15);
            password=new JPasswordField(15);
              JLabel usernameLabel=new JLabel("Username: ");
              JLabel passwordLabel=new JLabel("Password: ");
              add(usernameLabel);
              add(username);
              add(passwordLabel);
              add(password);
              setVisible(true);
              button1=new JButton("Ok");
              add(button1);
            button2=new JButton("Cancel");
              add(button2);
              JFrame frame=new JFrame("Welcome to Home Entertainment");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(this);
            frame.pack();
            frame.setVisible(true);
         button1.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
                 try{
                        Demo d = new Demo();
                        d.getChoice();
                   catch(Exception ex){}
         button2.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
                 System.exit(0);
    }

  • My java code doesn't work the way it should

    Hello can someone tell me why this code isn't printing on my linux computer?
    I found something about a bug in java for printing with linux see link.
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6181488
    I hope someone can help me.
    import javax.print.*;
    import javax.print.attribute.*;
    import java.io.*;
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.geom.CubicCurve2D;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.DocPrintJob;
    import javax.print.PrintException;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import javax.print.SimpleDoc;
    import javax.print.attribute.DocAttributeSet;
    import javax.print.attribute.HashDocAttributeSet;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class PrintingOneTwoFour {
       static class MyComponent extends JPanel implements Printable {
         public void paint(Graphics g) {
           Graphics2D g2d = (Graphics2D) g;
           g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
               RenderingHints.VALUE_ANTIALIAS_ON);
           g2d.setPaint(Color.BLUE);
           g2d.setStroke(new BasicStroke(3));
           CubicCurve2D cubic = new CubicCurve2D.Float(10, 80, 60, 30, 110, 130, 160, 80);
           g2d.draw(cubic);
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
           if (pageIndex == 0) {
             paint(g);
             return Printable.PAGE_EXISTS;
           } else {
             return Printable.NO_SUCH_PAGE;
       public static void main(String args[]) throws Exception {
         final JFrame frame = new JFrame();
         Container contentPane = frame.getContentPane();
         final Component printIt = new MyComponent();
         contentPane.add(printIt, BorderLayout.CENTER);
         JButton button = new JButton("Print");
         contentPane.add(button, BorderLayout.SOUTH);
         ActionListener listener = new ActionListener() {
           public void actionPerformed(ActionEvent e) {
             DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
          //      PrintService printService = PrintServiceLookup
             //     .lookupDefaultPrintService();
          PrintService[] services  = null;
             PrintService   myPrinter = null;
          //   DocFlavor myFlavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
             PrintRequestAttributeSet jobAttrs = new HashPrintRequestAttributeSet();
             services = PrintServiceLookup.lookupPrintServices( flavor, jobAttrs );
    if ( System.getProperty( "os.name" ).startsWith( "Windows" ) )
        myPrinter = PrintServiceLookup.lookupDefaultPrintService();
      else {
        try { 
            Process child = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "echo ${PRINTER:-$LPDEST}" });
            BufferedReader rdr = new BufferedReader(new InputStreamReader( child.getInputStream() ));
            String envPrinter = rdr.readLine().trim();
            System.out.println("Printer "+envPrinter+rdr.readLine());
         child.destroy();
            for ( int i=0; myPrinter == null && i<services.length; i++ )
                if ( services.getName().equals( envPrinter ) )
    myPrinter = services[i];
              System.out.println("myPrinter "+myPrinter);
    catch ( Exception ignore )
    System.out.println("Exception "+ignore);
    if(myPrinter==null)     
    myPrinter = services[0];
    System.out.println("myPrinter == null "+myPrinter);
         DocPrintJob job = myPrinter.createPrintJob();
    DocAttributeSet das = new HashDocAttributeSet();
    Doc doc = new SimpleDoc(printIt, flavor, das);
    try {
    job.print(doc, jobAttrs);
    } catch (PrintException pe) {
    pe.printStackTrace();
    button.addActionListener(listener);
    frame.setSize(350, 350);
    frame.show();

    Nobody????????????

  • Java Calendar Help Needed :)

    Hi,
    I am trying to develop a Java Event Calendar which is able to display the calendar weekly. So the JPanel will be setup with 7 JLists for the days of the week. Buttons will allow switching of the days of the week, months and year.
    Each JList corresponding to the day of the week will have its data obtained from the database using JDBC and loaded upon 're-drawing' of the lists.
    However i am having trouble with the GUI side in understanding how to implement this, i am confident with the JList and database side of things, i have just used a similar example using the Calendar API for monthly displays, however i am unsure how to convert this to a weekly calendar.
    Ideally 7 JLists will always be available in the panel in order M,T,W,T,F,S,S but some will be set to inactive (for example in the first and last weeks of the month).
    If anyone has any suggestions please could you help me out :)
    Sorry if what im trying to do is a bit confusing.
    I've included the code i've been using for the monthly calendar
    THANKS!!
    public class CalendarPanel extends JPanel implements ActionListener {
      private Calendar panelDate;
      private Label monthLabel;
      private Label yearLabel;
      private Panel daysPanel;
      private Vector calendarListeners;
      private static final String days[] = {"S","M","T","W","T","F","S"};
      public CalendarPanel(){
        super(new BorderLayout());
        panelDate = Calendar.getInstance();
        buildUI();
      public CalendarPanel(Calendar date){
        super(new BorderLayout());
        panelDate = (date != null) ? (Calendar)date.clone() : Calendar.getInstance();
        buildUI();
      public CalendarPanel(Date date){
        super(new BorderLayout());
        panelDate = Calendar.getInstance();
        if(date != null) panelDate.setTime(date);
        buildUI();
      public Calendar getCalendar(){ return panelDate;}
      public void setCalendar(Calendar date){
        if(date != null){
          panelDate = (Calendar)date.clone();
          redrawPanel();
      public void setCalendar(Date date){
        if(date != null){
          panelDate.setTime(date);
          redrawPanel();
      public int getYear(){ return panelDate.get(Calendar.YEAR);}
      public String getMonthName(){
        switch(panelDate.get(Calendar.MONTH)){
        case Calendar.JANUARY: return "January";
        case Calendar.FEBRUARY: return "February";
        case Calendar.MARCH: return "March";
        case Calendar.APRIL: return "April";
        case Calendar.MAY: return "May";
        case Calendar.JUNE: return "June";
        case Calendar.JULY: return "July";
        case Calendar.AUGUST: return "August";
        case Calendar.SEPTEMBER: return "September";
        case Calendar.OCTOBER: return "October";
        case Calendar.NOVEMBER: return "November";
        case Calendar.DECEMBER: return "December";
        case Calendar.UNDECIMBER: return "Undecimber";
        default: return "Unknown";
      private void buildUI(){
        this.add(buildHeaderPanel(), BorderLayout.NORTH);
        daysPanel = new Panel(new GridBagLayout());
        redrawPanel();
        this.add(daysPanel, BorderLayout.CENTER);
      // build the part of the gui that contains the month and year
      // labels with their incrementors / decrementors
      private Panel buildHeaderPanel(){
        monthLabel = new Label(getMonthName(), Label.CENTER);
        yearLabel = new Label(Integer.toString(panelDate.get(Calendar.YEAR)),
                     Label.CENTER);
        GridBagConstraints gbc = new GridBagConstraints();
        Panel headerPanel = new Panel(new GridBagLayout());
        // month label and buttons
        Panel panel = new Panel(new GridBagLayout());
        Button button = new Button("-");
        button.setActionCommand("decrease month");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.EAST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(monthLabel, gbc);
        button = new Button("+");
        button.setActionCommand("increase month");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.weightx = 1;
        headerPanel.add(panel, gbc);
        // year label and buttons
        panel = new Panel(new GridBagLayout());
        button = new Button("-");
        button.setActionCommand("decrease year");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.EAST;
        gbc.weightx = 0;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(yearLabel, gbc);
        button = new Button("+");
        button.setActionCommand("increase year");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.weightx = 1;
        headerPanel.add(panel, gbc);
        return headerPanel;
      // redraws the entire panel, including relaying out of
      // the days buttons
      private void redrawPanel(){
        monthLabel.setText(getMonthName());
        yearLabel.setText(Integer.toString(getYear()));
        // redraw days panel
        GridBagConstraints gbc = new GridBagConstraints();
        // clear current days panel
        daysPanel.removeAll();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1;
        gbc.weighty = 1;
        // add days of week
        for(int i = 0; i < days.length; i++, gbc.gridx++)
          daysPanel.add(new Label(days, Label.CENTER), gbc);
    gbc.gridx = 0;
    gbc.gridy++;
    // days of month
    Button button; // day buttons
    JTable day = new JTable();
    Calendar today = Calendar.getInstance();
    Calendar cellDay = (Calendar)today.clone();
    int month = panelDate.get(Calendar.MONTH);
    int year = panelDate.get(Calendar.YEAR);
    // start with first of panels month
    cellDay.set(year, month, 1);
    gbc.gridx = cellDay.get(Calendar.DAY_OF_WEEK) - 1;
    while( cellDay.get(Calendar.MONTH) == month ){
    if(gbc.gridx > 6){
         gbc.gridy++;
         gbc.gridx = 0;
    button = new Button(Integer.toString(cellDay.get(Calendar.DATE)));
    button.addActionListener(this);
    if( cellDay.equals(today)){
         button.setForeground(Color.red);
    daysPanel.add(button, gbc);
    gbc.gridx++;
    cellDay.add(Calendar.DAY_OF_MONTH, 1);
    // re validate entire panel
    validate();
    // implementation of ActionListener interface
    // currently no real need to create subclassed action
    // events for calendar. All actions generated by this
    // are action events (generated from the buttons).
    // the action command will be one of the four below
    // or a number (the label of the day button!).
    public void actionPerformed(ActionEvent ae){
    String command = ae.getActionCommand();
    if(command.equals("increase month")){
    panelDate.add(Calendar.MONTH, 1);
    redrawPanel();
    } else if(command.equals("decrease month")){
    panelDate.add(Calendar.MONTH, -1);
    redrawPanel();
    } else if(command.equals("increase year")){
    panelDate.add(Calendar.YEAR, 1);
    redrawPanel();
    } else if(command.equals("decrease year")){
    panelDate.add(Calendar.YEAR, -1);
    redrawPanel();
    notifyCalendarListeners(ae);
    // methods for keeping track of interested listeners
    public void addCalendarActionListener(ActionListener al){
    if(al != null){
    if(calendarListeners == null) calendarListeners = new Vector();
    calendarListeners.addElement(al);
    public void removeCalendarActionListener(ActionListener al){
    if((calendarListeners != null) && (al != null)){
    calendarListeners.removeElement(al);
    private void notifyCalendarListeners(ActionEvent ae){
    if((calendarListeners != null) && (!calendarListeners.isEmpty())){
    java.util.Enumeration e = calendarListeners.elements();
    while(e.hasMoreElements())
         ((ActionListener)e.nextElement()).actionPerformed(ae);

    Hi,
    Sorry for the change of screen name, i'm having trouble with my old account.
    I have now got most of the system working. However I am having trouble working out how to stop the last days of the previous month appearing in the first week of the next month. For example on 'July 2008' , days 29 and 30 of June are present in the first week of July. How can i get rid of this? And also for the last week of the month, how to get rid of the first days of the next month?
    import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Label;
    import java.awt.Panel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Vector;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.EtchedBorder;
    * @category CalendarSystem
    * @author Daniel Barrett
    public class CalendarSystem extends JPanel implements ActionListener, MouseListener, KeyListener   {
         JPanel events = new JPanel();
         JPanel action = new JPanel();
              //Events Panel
         DateComboBox eventDateChooser = new DateComboBox();
         JTextField ref = new JTextField(10);
         JTextArea eventDetails = new JTextArea();
         JScrollPane scrollingArea = new JScrollPane(eventDetails);
         JTextField dateF = new JTextField(15);
         JTextField timeF = new JTextField(15);
         String[] minutes = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
         String[] hours = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
         JComboBox minsComb = new JComboBox(minutes);
         JComboBox hourComb = new JComboBox(hours);
              //Actions Panel
         JButton delete = new JButton("Delete");
         JButton purge = new JButton("Purge");
         JButton add = new JButton("Add");
         JButton edit = new JButton("Edit");
         JButton mview = new JButton("Month View");
         protected JLabel monthLabel;
         protected JLabel weekLabel;
         protected JLabel lmonday = new JLabel("");
         protected JLabel ltuesday = new JLabel("");
         protected JLabel lwednesday = new JLabel("");
         protected JLabel lthursday = new JLabel("");
         protected JLabel lfriday = new JLabel("");
         protected JLabel lsaturday = new JLabel("");
         protected JLabel lsunday = new JLabel("");
         protected Calendar calendar;
         protected SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");
         protected SimpleDateFormat dayFormat = new SimpleDateFormat("MMM");
         JPanel monthCont = new JPanel();
         JPanel weekCont = new JPanel();
         JPanel yearCont = new JPanel();
         JPanel daysOfWeek = new JPanel();
         JPanel monday = new JPanel();
         JPanel tuesday = new JPanel();
         JPanel wednesday = new JPanel();
         JPanel thursday = new JPanel();
         JPanel friday = new JPanel();
         JPanel saturday = new JPanel();
         JPanel sunday = new JPanel();
         JList mondayEvents = new JList();
         JScrollPane mondayEventsScroll = new JScrollPane(mondayEvents);
         JList tuesdayEvents = new JList();
         JScrollPane tuesdayEventsScroll = new JScrollPane(tuesdayEvents);
         JList wednesdayEvents = new JList();
         JScrollPane wednesdayEventsScroll = new JScrollPane(wednesdayEvents);
         JList thursdayEvents = new JList();
         JScrollPane thursdayEventsScroll = new JScrollPane(thursdayEvents);
         JList fridayEvents = new JList();
         JScrollPane fridayEventsScroll = new JScrollPane(fridayEvents);
         JList saturdayEvents = new JList();
         JScrollPane saturdayEventsScroll = new JScrollPane(saturdayEvents);
         JList sundayEvents = new JList();
         JScrollPane sundayEventsScroll = new JScrollPane(sundayEvents);
         protected Color selectedBackground;
         protected Color selectedForeground;
         protected Color background;
         protected Color foreground;
         public CalendarSystem(){
              setupDays();
              setupHeaders();
              setupEvents();
              setupActions();
              this.calendar = Calendar.getInstance();
              this.calendar.setFirstDayOfWeek(Calendar.SUNDAY);
              this.add(this.monthCont);
              this.add(this.daysOfWeek);
              this.add(this.weekCont);
              this.add(this.events);
              this.add(this.action);
              this.setLayout(new BoxLayout(this,1));
              this.setMaximumSize(new Dimension(400,30));
              this.updateCalendar();
         private void setupActions() {
              this.action.setBorder(BorderFactory.createTitledBorder("Actions"));
              this.action.add(this.add);
              this.action.add(this.edit);
              this.action.add(this.delete);
              this.action.add(this.purge);
              this.action.add(this.mview);
         private void setupEvents() {
              this.events.setBorder(BorderFactory.createTitledBorder("Event Details"));
              this.events.setLayout(new BoxLayout(this.events,1));
              JPanel row1 = new JPanel();
              JPanel row2 = new JPanel();
              JPanel row3 = new JPanel();
              JLabel la = new JLabel("Reference");
              JLabel da = new JLabel("Date");
              JLabel time = new JLabel("Time");
              JLabel det = new JLabel("Details");
              this.ref.setEditable(false);
              this.dateF.setEditable(false);
              this.timeF.setEditable(false);
              this.eventDetails.setEditable(false);
              row1.add(la);
              row1.add(this.ref);
              row1.add(da);
              row1.add(this.dateF);
              row1.add(time);
              row1.add(this.timeF);
              row2.add(det);
              scrollingArea.setPreferredSize(new Dimension(600,50));
              row3.add(this.scrollingArea);
              this.events.add(row1);
              this.events.add(row2);
              this.events.add(row3);
         protected JLabel createUpdateButton(final int field, final int amount, final boolean month) {
             final JLabel label = new JLabel();
             final Border selectedBorder = new EtchedBorder();
             final Border unselectedBorder = new EmptyBorder(selectedBorder.getBorderInsets(new JLabel()));
             label.setBorder(unselectedBorder);
             label.setForeground(foreground);
             label.addMouseListener(new MouseAdapter() {
                  public void mouseReleased(MouseEvent e) {
                   calendar.add(field, amount);
                   if(month){
                   updateMCalendar();}
                   else{
                        updateCalendar();
                   public void mouseEntered(MouseEvent e) {
                   label.setBorder(selectedBorder);
                  public void mouseExited(MouseEvent e) {
                   label.setBorder(unselectedBorder);
             return label;
         private void updateMCalendar() {
              this.calendar.set(Calendar.DAY_OF_MONTH, 1);
              updateCalendar();     
         private void setupHeaders() {
              //MONTH CONTROLS
             monthCont.setLayout(new BoxLayout(monthCont, BoxLayout.X_AXIS));
             monthCont.setBackground(background);
             monthCont.setOpaque(true);
             JLabel label;
             label = createUpdateButton(Calendar.YEAR, -1,false);
             label.setText("<<");
             label.setToolTipText("Previous Year");
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(label);
             monthCont.add(Box.createHorizontalStrut(12));
             label = createUpdateButton(Calendar.MONTH, -1,true);
             label.setText("< ");
             label.setToolTipText("Previous Month");
             monthCont.add(label);
             monthLabel =new JLabel("", JLabel.CENTER);
             monthLabel.setForeground(foreground);
             //monthCont.add(Box.createHorizontalGlue());
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(monthLabel);
             monthCont.add(Box.createHorizontalStrut(12));
             //monthCont.add(Box.createHorizontalGlue());
             label =createUpdateButton(Calendar.MONTH, 1,true);
             label.setText(" >");
             label.setToolTipText("Next Month");
             monthCont.add(label);
             label = createUpdateButton(Calendar.YEAR, 1,false);
             label.setText(">>");
             label.setToolTipText("Next Year");
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(label);
             monthCont.add(Box.createHorizontalStrut(12));
             //WEEK CONTROLS
             weekCont.setLayout(new BoxLayout(weekCont, BoxLayout.X_AXIS));
             weekCont.setBackground(background);
             weekCont.setOpaque(true);
             JLabel label1;
             label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, -1,false);
             label1.setText("<<");
             label1.setToolTipText("Previous Week");
             weekCont.add(label1);
             weekLabel =new JLabel("", JLabel.CENTER);
             weekLabel.setForeground(foreground);
             JLabel lweek =new JLabel("Week:  ", JLabel.CENTER);
             lweek.setForeground(foreground);
             //monthCont.add(Box.createHorizontalGlue());
             weekCont.add(Box.createHorizontalStrut(12));
             weekCont.add(lweek);
             weekCont.add(weekLabel);
             weekCont.add(Box.createHorizontalStrut(12));
             //monthCont.add(Box.createHorizontalGlue());
             label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, 1,false);
             label1.setText(">>");
             label1.setToolTipText("Next Week");
             weekCont.add(label1);
         public void setupDays(){
              monday.setLayout(new BoxLayout(monday,1));
              tuesday.setLayout(new BoxLayout(tuesday,1));
              wednesday.setLayout(new BoxLayout(wednesday,1));
              thursday.setLayout(new BoxLayout(thursday,1));
              friday.setLayout(new BoxLayout(friday,1));
              saturday.setLayout(new BoxLayout(saturday,1));
              sunday.setLayout(new BoxLayout(sunday,1));
              monday.add(this.lmonday);
              monday.add(this.mondayEventsScroll);
              monday.setBorder(BorderFactory.createTitledBorder("Monday"));
              tuesday.add(this.ltuesday);
              tuesday.add(this.tuesdayEventsScroll);
              tuesday.setBorder(BorderFactory.createTitledBorder("Tuesday"));
              wednesday.add(this.lwednesday);
              wednesday.add(this.wednesdayEventsScroll);
              wednesday.setBorder(BorderFactory.createTitledBorder("Wednesday"));
              thursday.add(this.lthursday);
              thursday.add(this.thursdayEventsScroll);
              thursday.setBorder(BorderFactory.createTitledBorder("Thursday"));
              friday.add(this.lfriday);
              friday.add(this.fridayEventsScroll);
              friday.setBorder(BorderFactory.createTitledBorder("Friday"));
              saturday.add(this.lsaturday);
              saturday.add(this.saturdayEventsScroll);
              saturday.setBorder(BorderFactory.createTitledBorder("Saturday"));
              sunday.add(this.lsunday);
              sunday.add(this.sundayEventsScroll);
              sunday.setBorder(BorderFactory.createTitledBorder("Sunday"));
              this.mondayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.monday.setPreferredSize(new Dimension(145,300));
              this.tuesdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.tuesday.setPreferredSize(new Dimension(145,300));
              this.wednesdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.wednesday.setPreferredSize(new Dimension(145,300));
              this.thursdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.thursday.setPreferredSize(new Dimension(145,300));
              this.fridayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.friday.setPreferredSize(new Dimension(145,300));
              this.saturdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.saturday.setPreferredSize(new Dimension(145,300));
              this.sundayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.sunday.setPreferredSize(new Dimension(145,300));
              daysOfWeek.add(this.sunday);
              daysOfWeek.add(this.monday);
              daysOfWeek.add(this.tuesday);
              daysOfWeek.add(this.wednesday);
              daysOfWeek.add(this.thursday);
              daysOfWeek.add(this.friday);
              daysOfWeek.add(this.saturday);
        private void updateCalendar() {
             monthLabel.setText(monthFormat.format(calendar.getTime()) );
             weekLabel.setText(String.valueOf(this.calendar.get(calendar.WEEK_OF_MONTH)));
             //Blank out / empty strings for first elements that do not start on sunday
             Calendar setupCalendar = (Calendar) calendar.clone();
             setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
           // while(setupCalendar.get(Calendar.DAY_OF_WEEK) < calendar.getActualMaximum(Calendar.DAY_OF_WEEK)) {
                //System.out.println("day of month: " + setupCalendar.get(Calendar.DAY_OF_MONTH));
                //System.out.println("day of week: " + (setupCalendar.get(Calendar.DAY_OF_WEEK)));
                //System.out.println("week of month: " + calendar.get(Calendar.WEEK_OF_MONTH) + "\n");
                  setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
        public void setDayLabels(int day, int dayOfWeek){
             if(dayOfWeek == 1){
                  this.lsunday.setText(String.valueOf(day));
             if(dayOfWeek == 2){
                  this.lmonday.setText(String.valueOf(day));
             if(dayOfWeek == 3){
                  this.ltuesday.setText(String.valueOf(day));
             if(dayOfWeek == 4){
                  this.lwednesday.setText(String.valueOf(day));
             if(dayOfWeek == 5){
                  this.lthursday.setText(String.valueOf(day));
             if(dayOfWeek == 6){
                  this.lfriday.setText(String.valueOf(day));
             if(dayOfWeek == 7){
                  this.lsaturday.setText(String.valueOf(day));
         @Override
         public void actionPerformed(ActionEvent arg0) {
         @Override
         public void mouseClicked(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyPressed(KeyEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyReleased(KeyEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyTyped(KeyEvent arg0) {
              // TODO Auto-generated method stub
         public static void main(String args[]){
              JFrame frame = new JFrame();
              frame.setSize(1100, 670);
              frame.add(new CalendarSystem());
              frame.setVisible(true);
    }Thanks
    Dan

  • Facing problem inside the implementation of ActionListener

    Hi, I don't understand what the problem is. Please go through the following code. The explanation of the problem is documented.
    Any kind of help is appreciated.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JOptionPane;
    * Class Test is intended for receiving a String input from the user and
    * manipulating the input string later in some other methods. So the input
    * string has to be stored for later use.
    * Whenever an action takes place in JTextField or JButton (OK button) component,
    * the corresponding ActionListener's actionPerformed() method assigns the
    * user input to 'userInput' referene variable. This was assured when I placed
    *              JOptionPane.showMessageDialog(frame, userInput);
    * right after the assignment statement. But when I cut and pasted the above
    * statement right after the getUserInput() method call (in constructor's body)
    * it showed null string.
    * WHY & HOW this happens?
    * I could have implemented this application with the help of JOptionPane's
    * showInputDialog() method. But I just want to know what the problem is if
    * I have tried in this way.
    public class Test {
         * String that the user types
        private String userInput;
         * Text field that contains the user input.
        private JTextField inputTextField;
         * Frame that contains all other components
        private JFrame frame;
        public Test() {
            prepareFrame();
            getUserInput();
            // shows null, why?????
            JOptionPane.showMessageDialog(frame, userInput);
            // some other methods goes here that uses the input string....
            // methodA();
            // methodB();
         * Creates the frame and sets some of its properties.
        private void prepareFrame() {
            frame = new JFrame("Experiment with ActionListener");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(500, 300);
            frame.setVisible(false);
         * Receives user input and stores the reference to user input in userInput.
        private void getUserInput() {
            // Create sub-components
            JLabel promptLabel = new JLabel("Enter a string: ");
            inputTextField = new JTextField(20);
            JButton okButton = new JButton("OK");
            JButton cancelButton = new JButton("Cancel");
            // Add listeners
            inputTextField.addActionListener(new TextFieldHandler());
            okButton.addActionListener(new OkButtonHandler());
            cancelButton.addActionListener(new CancelButtonHandler());
            // Create a panel to contain the sub-components
            JPanel panel = new JPanel();
            // Add the sub-components to the panel
            panel.add(promptLabel);
            panel.add(inputTextField);
            panel.add(okButton);
            panel.add(cancelButton);
            frame.add(panel, BorderLayout.NORTH);
            frame.validate();
            frame.setVisible(true);
         * Event handler for text field that contains user input.
        private class TextFieldHandler
                implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                userInput = event.getActionCommand();
                // works fine if the user input is shown here.
                // JOptionPane.showMessageDialog(frame, userInput);
         * Event handler for OK button
        private class OkButtonHandler
                implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                userInput = inputTextField.getText();
                // works fine if the user input is shown here.
                // JOptionPane.showMessageDialog(frame, userInput);
         * Event handler for Cancel button
        private class CancelButtonHandler
                implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
        public static void main(String[] args) {
            new Test();
    }

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JOptionPane;
    public class T {
        private String userInput;
        private JTextField inputTextField;
        private JFrame frame;
        public T() {
            prepareFrame();
            getUserInput();
            // shows null, why?????
            // userInput is null because it has not been given a value
            // you can give it a value in the declaration as a member
            // variable above or here in your class constructor
            System.out.println("userInput = " + userInput);
            JOptionPane.showMessageDialog(frame, userInput);
            // some other methods goes here that uses the input string....
            // methodA();
            // methodB();
        private void prepareFrame() {
            frame = new JFrame("Experiment with ActionListener");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(500, 300);
            frame.setVisible(false);
        private void getUserInput() {
            // Create sub-components
            JLabel promptLabel = new JLabel("Enter a string: ");
            inputTextField = new JTextField(20);
            JButton okButton = new JButton("OK");
            JButton cancelButton = new JButton("Cancel");
            // Add listeners
            inputTextField.addActionListener(new TextFieldHandler());
            okButton.addActionListener(new OkButtonHandler());
            cancelButton.addActionListener(new CancelButtonHandler());
            // Create a panel to contain the sub-components
            JPanel panel = new JPanel();
            // Add the sub-components to the panel
            panel.add(promptLabel);
            panel.add(inputTextField);
            panel.add(okButton);
            panel.add(cancelButton);
            frame.add(panel, BorderLayout.NORTH);
            frame.validate();
            frame.setVisible(true);
        private class TextFieldHandler implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                // userInput is given a value here so it is no longer null
                userInput = event.getActionCommand();
                // works fine if the user input is shown here.
                System.out.println("userInput = " + userInput);
                JOptionPane.showMessageDialog(frame, userInput);
        private class OkButtonHandler implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                // userInput is given a value here so it is no longer null
                userInput = inputTextField.getText();
                // works fine if the user input is shown here.
                System.out.println("userInput = " + userInput);
                JOptionPane.showMessageDialog(frame, userInput);
        private class CancelButtonHandler implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
        public static void main(String[] args) {
            new T();
    }

  • Add more fuctionality to my java program

    hi i have this program which is a simple game to find the prize, but i need to add more to it so that the user only gets ten go's at guessing the button where the prize is any help?
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    public class MyGame extends JPanel{
    private Random rand ;
    private int rows;
    private int cols;
    private int prizeX;
    private int prizeY;
    public MyGame(int rows, int cols){
    //super(new GridLayout(rows, cols));
    super(new BorderLayout());
    this.rows = rows;
    this.cols = cols;
    JPanel p = new JPanel(new GridLayout(rows, cols));
    for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
    JButton b = new JButton(" Button [x="+i+", y="+j+"]");
    b.addActionListener(new MyActionListener(i, j));
    p.add(b);
    this.add(p, BorderLayout.CENTER);
    this.add(new MyReStartButton(), BorderLayout.SOUTH);
    rand = new Random(System.currentTimeMillis());
    prizeX = rand.nextInt(rows);
    prizeY = rand.nextInt(cols);
    System.out.println(prizeX+", "+prizeY);
    class MyActionListener implements ActionListener{
    private int x;
    private int y;
    public MyActionListener(int x, int y){
    this.x=x;
    this.y=y;
    public void actionPerformed(ActionEvent e) {
    if(x==prizeX&&y==prizeY){
    JOptionPane.showMessageDialog(MyGame.this, " Winner !! ");
    }else{
    JOptionPane.showMessageDialog(MyGame.this, " Try again ");
    class MyReStartButton extends JButton{
    public MyReStartButton(){
    super("Start new Game");
    addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
    MyGame.this.prizeX = rand.nextInt(rows);
    MyGame.this.prizeY = rand.nextInt(cols);
    System.out.println(prizeX+", "+prizeY);
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("MyGame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new MyGame(3, 5);
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setLayout(new BorderLayout());
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }

    You want to have 10 try attempts for a user to guess your number?
    If so, check this out. I've added you a variable to count guesses of users.
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    public class MyGame extends JPanel {
         private Random rand;
         private int rows;
         private int cols;
         private int prizeX;
         private int prizeY;
         private int attempts;
         public MyGame(int rows, int cols) {
              // super(new GridLayout(rows, cols));
              super(new BorderLayout());
              this.rows = rows;
              this.cols = cols;
              JPanel p = new JPanel(new GridLayout(rows, cols));
              for (int i = 0; i < rows; i++) {
                   for (int j = 0; j < cols; j++) {
                        JButton b = new JButton(" Button [x=" + i + ", y=" + j + "]");
                        b.addActionListener(new MyActionListener(i, j));
                        p.add(b);
              this.add(p, BorderLayout.CENTER);
              this.add(new MyReStartButton(), BorderLayout.SOUTH);
              rand = new Random(System.currentTimeMillis());
              prizeX = rand.nextInt(rows);
              prizeY = rand.nextInt(cols);
              attempts = 9;
              System.out.println(prizeX + ", " + prizeY);
         class MyActionListener implements ActionListener {
              private int x;
              private int y;
              public MyActionListener(int x, int y) {
                   this.x = x;
                   this.y = y;
              public void actionPerformed(ActionEvent e) {
                   if (attempts == 0) {
                        JOptionPane.showMessageDialog(MyGame.this, "You lost, 10 attempts reached. ");
                   } else {
                        if (x == prizeX && y == prizeY) {
                             JOptionPane.showMessageDialog(MyGame.this, " Winner !! ");
                        } else {
                             JOptionPane.showMessageDialog(MyGame.this,
                                       " Try again, you have " + attempts
                                                 + " more attempts");
                             attempts--;
         class MyReStartButton extends JButton {
              public MyReStartButton() {
                   super("Start new Game");
                   addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             MyGame.this.prizeX = rand.nextInt(rows);
                             MyGame.this.prizeY = rand.nextInt(cols);
                             MyGame.this.attempts = 9;
                             System.out.println(prizeX + ", " + prizeY);
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("MyGame");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              JComponent newContentPane = new MyGame(3, 5);
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setLayout(new BorderLayout());
              frame.setContentPane(newContentPane);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
    }

  • Java 1.4.2 swing (setBounds) performance problem

    Hi,
    We were having performance problems with swing ever since we moved to java 1.4.2 and we finally switched back to 1.4.1. However, we have now traced the problem to JVM and the following simple code demonstrates it.
    I would like to hear from others who faced or solved this.
    When the setBounds is called, there is visible delay in checking/unchecking boxes.
    Without it, the performance is good. The performance is good with 1.4.1 as well.
    Code sample for JComponentTest :
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class JComponentTest extends JFrame {
    public final static int MAX_JLBL = 50;
    private static double _clicked = 0.0;
    // pop up window
    private JPanel _configPanel = new JPanel();
    private JCheckBox[] _configArray = new JCheckBox[MAX_JLBL];
    private JButton _toggle = new JButton("update");
    public JComponentTest() {
    setTitle("JLabelTest");
    // setBounds causes performance problems
    setBounds(1278, 4, 203, 361);
    getContentPane().add(_configPanel);
    for(int i=0; i<_configArray.length; i++){
    _configArray[i] = new JCheckBox("cb"+i);
    configPanel.add(configArray);
    _configArray[i].addActionListener(new ConfigListener());
    configPanel.add(toggle);
    _toggle.addActionListener(new ConfigListener());
    setVisible(true);
    // listenres
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(1);
    } // end constructor
    public static void main(String[] args) {
    new JComponentTest();
    /** This class implements the ActionListener and being used for configuration
    * fields.
    private class ConfigListener implements ActionListener {
    public void actionPerformed(ActionEvent ae) {
    boolean selected = (_clicked%2 ==0);
    if (selected)
    for(int i=0; i<_configArray.length; i++)
    ((JCheckBox)_configArray[i]).setSelected(true);
    else
    for(int i=0; i<_configArray.length; i++)
    ((JCheckBox)_configArray[i]).setSelected(false);
    _clicked++;

    weebib
    We are using Windows XP , Nvidia graphics card, with Multiview. I hope the problem is not specific to the platform.
    It is reproducible with 1.4.2 and absent in 1.4.1
    camickr
    I am new to this forum. didn't know about code blocks.

  • Java.security.AccessControlException: access denied when loading from a jar

    Hello!
    I am trying to deploy an applet into a browser but I have encountered a security problem.
    The name of the applet is SWTInBrowser(not exactly mine, it's an example from the web).
    package my.applet;
    import org.eclipse.swt.awt.SWT_AWT;
    import java.applet.Applet;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Canvas;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.widgets.Listener;
    import org.eclipse.swt.widgets.Event;
    import org.eclipse.swt.graphics.Point;
    import org.eclipse.swt.layout.FillLayout;
    public class SWTInBrowser extends Applet implements Runnable{
         public void init () {
               /* Create Example AWT and Swing widgets */
               java.awt.Button awtButton = new java.awt.Button("AWT Button");
               add(awtButton);
               awtButton.addActionListener(new ActionListener () {
                public void actionPerformed (ActionEvent event) {
                 showStatus ("AWT Button Selected");
               javax.swing.JButton jButton = new javax.swing.JButton("Swing Button");
               add(jButton);
               jButton.addActionListener(new ActionListener () {
                public void actionPerformed (ActionEvent event) {
                 showStatus ("Swing Button Selected");
               Thread swtUIThread = new Thread (this);
               swtUIThread.start ();
              public void run() {
               /* Create an SWT Composite from an AWT canvas to be the parent of the SWT
              widgets.
                * The AWT Canvas will be layed out by the Applet layout manager.  The
              layout of the
                * SWT widgets is handled by the application (see below).
               Canvas awtParent = new Canvas();
               add(awtParent);
               Display display = new Display();
               Shell swtParent = SWT_AWT.new_Shell(display, awtParent);
    //           Display display = swtParent.getDisplay();
               swtParent.setLayout(new FillLayout());
               /* Create SWT widget */
               org.eclipse.swt.widgets.Button swtButton = new
              org.eclipse.swt.widgets.Button(swtParent, SWT.PUSH);
               swtButton.setText("SWT Button");
               swtButton.addListener(SWT.Selection, new Listener() {
                public void handleEvent(Event event){
                 showStatus("SWT Button selected.");
               swtButton.addListener(SWT.Dispose, new Listener() {
                public void handleEvent(Event event){
                 System.out.println("Button was disposed.");
               // Size AWT Panel so that it is big enough to hold the SWT widgets
               Point size = swtParent.computeSize (SWT.DEFAULT, SWT.DEFAULT);
               awtParent.setSize(size.x + 2, size.y + 2);
               // Need to invoke the AWT layout manager or AWT and Swing
               // widgets will not be visible
               validate();
               // The SWT widget(s) require an event loop
               while (!swtParent.isDisposed()) {
                if (!display.readAndDispatch()) display.sleep ();
    }It works perfectly in the Applet Viewer, but not in the browser. In the browser, I only get two buttons working, the SWT button doesn't appear, because of this error:
    Exception in thread "Thread-21" java.lang.ExceptionInInitializerError
         at org.eclipse.swt.widgets.Display.<clinit>(Display.java:130)
         at my.applet.SWTInBrowser.run(SWTInBrowser.java:52)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.security.AccessControlException: access denied (java.util.PropertyPermission sun.arch.data.model read)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
         at java.lang.System.getProperty(Unknown Source)
         at org.eclipse.swt.internal.Library.loadLibrary(Library.java:167)
         at org.eclipse.swt.internal.Library.loadLibrary(Library.java:151)
         at org.eclipse.swt.internal.C.<clinit>(C.java:21)
         ... 3 moreI have exported the application in a jar, and in that jar I have put the swt.jar that the application need for the displaying of the third button, swt button.
    Here is also the HTML file:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=Cp1252"/>
        <title>
          Test
        </title>
      </head>
      <body>
        <p>
              <applet code="my.applet.SWTInBrowser"
                        archive="Test.jar"
                        width="1400" height="800">
              </applet>
        </p>
      </body>
    </html>Could anyone please help me solve this problem?

    This is in reply to the first post. I don't know what happened after.
    Caused by: java.security.AccessControlException: access denied (java.util.PropertyPermission sun.arch.data.model read)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
         at java.lang.System.getProperty(Unknown Source)
         at org.eclipse.swt.internal.Library.loadLibrary(Library.java:167)
         at org.eclipse.swt.internal.Library.loadLibrary(Library.java:151)
         at org.eclipse.swt.internal.C.<clinit>(C.java:21)
    If you read the above trace from bottom to top, it shows none of you classes, only classes from that Eclipse library, which seems to loadLibrary() a native DLL. In order to do this, it needs to call System.getProperty( "sun.arch.data.model" ). This call is not allowed from un unsigned applet. So I guess you need to sign the applet and this problem will go away. Many other problems may follow. Just read very very carefully all the related documentation, which I did not.

  • Javax.ejb.EJBException: nested exception is: java.rmi.RemoteException:

    package library.client;
    import javax.naming.InitialContext;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.reflect.Method;
    import java.sql.ResultSet;
    import javax.ejb.*;
    import javax.naming.*;
    import javax.swing.*;
    import library.common.*;
    @SuppressWarnings("serial")
    public class LibraryClient extends JFrame implements ActionListener {
      private static LibraryInterface li;
      private JTextField book_author = new JTextField(10);
      private JTextField book_title = new JTextField(10);
      private JTextField book_isbn = new JTextField(10);
      private JLabel author_label = new JLabel("Podaj autora:");
      private JLabel book_title_label = new JLabel("Podaj tytul ksiazki");
      private JLabel isbn_label = new JLabel("Podaj ISBN");
      private JTextArea display_books = new JTextArea(20,50);
      private JButton search = new JButton("Search");
      private ResultSet resultset;
      public LibraryClient() {
        this("DEFAULT_CONTEXT");
    private JPanel createPanel1(){
          JPanel panel = new JPanel();
          panel.add(author_label);
          panel.add(book_author);
          panel.add(book_title_label);
          panel.add(book_title);
          panel.add(isbn_label);
          panel.add(book_isbn);
          panel.add(search);
          ////search.setActionCommand("ISBN");
          search.addActionListener(this);
          return panel;
    private JPanel createPanel2(){
          JPanel panel = new JPanel();
          panel.add(display_books);
          return panel;
    private JPanel createPanels(){
         JPanel panel = new JPanel();
        //Use default FlowLayout.
        panel.setLayout(new BorderLayout());
        panel.add(createPanel1(), BorderLayout.NORTH);
        panel.add(createPanel2(), BorderLayout.SOUTH);
        return panel;
      public  LibraryClient(String appType) {
        init(appType);
        JFrame frame = new JFrame("Library");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //    /final Table table = new Table();
        frame.setContentPane(createPanels());
        frame.pack();
    //    /f.setLocationRelativeTo(null);
        frame.setVisible(true);
      public void actionPerformed(ActionEvent e) {
             try {
                  display_books.setText("");
                  display_books.setText("Wyszukane Ksiazki\n");
                  if(!book_author.getText().equals("")){
                       resultset=li.getBookByAuthor(book_author.getText());
                  }else if(!book_title.getText().equals("")){
                       resultset=li.getBookByName(book_title.getText());
                  }else if(!book_isbn.getText().equals("")){
                       resultset=li.getBookByISBN(book_isbn.getText());
                  }else {
                       System.out.println("Before->resultset=li.getAllBooks()");
                       resultset=li.getAllBooks();
                       System.out.println("After->resultset=li.getAllBooks()");
                  while(resultset.next()){
                       System.out.println("in while resultset.next()"); 
                       String name = resultset.getString("name");
                         String author =resultset.getString("author");
                         String isbn = resultset.getString("ISBN");
                         display_books.append("\n"+ name + " " + author +" "+ isbn);
             } catch(Exception exc) { exc.printStackTrace(); }
      private void init(String type) {
        if (type.equals("JAVA_APP")) li = new library.ejb.LibraryBean();
        else if (type.equals("JAVA_CLIENT")) {
          try {
            InitialContext ic = new InitialContext();
            li = (LibraryInterface) ic.lookup("library.common.LibraryInterface");
          } catch (NamingException e) {
            e.printStackTrace();
      public static void main(String[] args) {
        if (args.length >= 1) new LibraryClient(args[0]);
        else new LibraryClient();
    }it throws the exception when it gets to
    any of the functions
    resultset=li.getBookByAuthor(book_author.getText());
    resultset=li.getBookByName(book_title.getText());
    resultset=li.getBookByISBN(book_isbn.getText());
    resultset=li.getAllBooks();
    Please help
    Thank You

    Hi,
    I also get the same error.have you got the solution,fi so explain me how to rectify the error
    Regards
    SamyMohan

  • Problems with basic Java JPanel animation using paintcomponent

    okay so I am trying to animate a sprite moving across a background using a for loop within the paintComponent method of a JPanel extension
    public void paintComponent(Graphics g){
    Image simpleBG = new ImageIcon("Images/Backgrounds/Simple path.jpg").getImage();
    Image mMan = new ImageIcon("Images/Sprites/hMan.gif").getImage();
    if (!backgroundIsDrawn){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, xi, y, this);
    backgroundIsDrawn=true;
    else
    for (int i=xi; i<500; i++){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, i, y, this);
    try{
    Thread.sleep(10);
    } catch(Exception ex){System.out.println("damn");}
    The problem is that no matter what I set my thread to, it will not show the animation, it will just jump to the last location, even if the thread sleep is set high enough that it takes several minutes to calculate,, it still does not paint the intemediary steps.
    any solution, including using a different method of animation all together would be greatly appreciated. I am learning java on my own so i need all the help I can get.

    fysicsandpholds1014 wrote:
    even when I placed the thread sleep outside of the actual paintComponent in a for loop that called repaint(), it still did not work? Nope. Doing this will likely put the Event Dispatch Thread or EDT to sleep. Since this is the main thread that is responsible for Swing's painting and user interaction, you'll put your app to sleep with this. Again, use a Swing Timer
    and is there any easy animation method that doesnt require painting and repainting every time becasue it is very hard to change what I want to animate with a single paintComponent method? I don't get this.
    I find the internet tutorials either way too complicated or not nearly in depth enough. Maybe its just that I am new to programming but there doesn't seem to be a happy medium between dumbed down Swing tutorials and very complicated and sophisticated animation algorithmns.I can only advise that you practice, practice, practice. The more you use the tutorials, the easier they'll be to use.
    Here's another small demo or animation. It is not optimized (repaint is called on the whole JPanel), but demonstrates some points:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    @SuppressWarnings("serial")
    public class AnimationDemo2 extends JPanel {
      // use a publicly available sprite for this example
      private static final String SPRITE_PATH = "http://upload.wikimedia.org/" +
                "wikipedia/commons/2/2e/FreeCol_flyingDutchman.png";
      private static final int SIDE = 600;
      private static final Dimension APP_SIZE = new Dimension(SIDE, SIDE);
      // timer delay: equivalent to the Thread.sleep time
      private static final int TIMER_DELAY = 20;
      // how far to move in x dimension with each loop of timer
      public static final int DELTA_X = 1;
      // holds our sprite image
      private BufferedImage img = null;
      // the images x & y locations
      private int imageX = 0;
      private int imageY = SIDE/2;
      public AnimationDemo2() {
        setPreferredSize(APP_SIZE);
        try {
          // first get our image
          URL url = new URL(SPRITE_PATH);
          img = ImageIO.read(url);
          imageY -= 3*img.getHeight()/4;
        } catch (Exception e) { // shame on me for combining exceptions :(
          e.printStackTrace();
          System.exit(1); // exit if fails
        // create and start the Swing Timer
        new Timer(TIMER_DELAY, new TimerListener()).start();
      // all paintComponent does is paint -- nothing else
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.blue);
        int w = getWidth();
        int h = getHeight();
        g.fillRect(0, h/2, w, h);
        if (img != null) {
          g.drawImage(img, imageX, imageY, this);
      private class TimerListener implements ActionListener {
        // is called every TIMER_DELAY ms
        public void actionPerformed(ActionEvent e) {
          imageX += DELTA_X;
          if (imageX > getWidth()) {
            imageX = 0;
          // ask JVM to paint this JPanel
          AnimationDemo2.this.repaint();
      // code to place our JPanel into a JFrame and show it
      private static void createAndShowUI() {
        JFrame frame = new JFrame("Animation Demo");
        frame.getContentPane().add(new AnimationDemo2());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      // call Swing code in a thread-safe manner
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
    }

  • Query to connect Java Applet to Oracle 10g.

    I am developing an Applet in Java 1.5.0.7.My database is Oracle 10g.Now when i connect Oracle to Java I get the Error : java.lang.ExceptionInInitializerError
    and it does not get connected.Please help me anyone.
    Below is the code which i have written.
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.sql.*;
    import java.util.ArrayList;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    public class tt7 extends JApplet
         implements ActionListener, PropertyChangeListener
    private int m_uniqueID = 0;
         JLabel m_lblRadius;
         // A button the user can click to display the Add Theme wizard.
         JButton m_btnAddTheme;
         static String m_mapxtremeURL = null;
         // TODO: Specify a map file name such as "uk.mdf" (if the mdf file is in
         // in same directory that the applet was loaded from),
         // or an URL to a map file, such as "http://host.com/maps/uk.mdf".
         // Or, instead of specifying this URL explicitly here, you can specify it
         // in the HTML page that loads the applet (using the 'filetoload' param).
    ResultSet rs=null ;
    ArrayList arrlist=null;
    ArrayList arrlist1=null;
    ArrayList arrlist2=null;
    //Connection con=null;
    Statement st=null;
         public void start()
         } // start method
         public void init()
    try{
    // System.out.println("helloooooooo");
    Class.forName("oracle.jdbc.driver.OracleDriver");
    //Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con= DriverManager.getConnection("Jdbc:oracle:thin:@asl005:1521:geo","system","1234567");//"jdbc:oracle:thin:@asl005:1521:geo","system","1234567");
    System.out.println("helloooooooo");
    System.out.println("CON:"+con.toString());
    st = con.createStatement();
    System.out.println("St:"+st);
    catch(Exception e2){System.out.println("Exception :"+e2);}
    catch(ExceptionInInitializerError s)
    System.out.println("Exception2 :"+s);
    }// If the HTML page specified parameters, use them to
              // override our default values.
              // See if a MapDef file was specified in the HTML file.
         }     // propertyChange method
         // Respond to the user actions, such as clicking
         // the Add Theme button.
    public void actionPerformed(ActionEvent e)
    // LocalDataProviderRef localDPRef = null;
    // a static label displayed in the applet
    public void propertyChange(PropertyChangeEvent evt) {
    This is the HTML CODE...
    <HTML>
    <HEAD>
    <TITLE>SimpleMap applet demonstration</TITLE>
    </HEAD>
    <BODY>
    <OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    WIDTH = 600 HEIGHT = 440
    codebase="http://java.sun.com/products/plugin/1.3.1/jinstall-131-win32.cab#Version=1,3,1,0">
    <PARAM NAME = CODE VALUE = "tt7.class" >
    <PARAM NAME=archive VALUE="classes12.jar">
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.5">
    <COMMENT>
    <EMBED type="application/x-java-applet;version=1.5"
    CODE = "tt7.class"
    WIDTH = 600 HEIGHT = 440
    archive="classes12.jar"
    pluginspage="http://java.sun.com/products/plugin/1.3.1/plugin-install.html">
    <NOEMBED></COMMENT>
    alt="Your browser understands the &lt;APPLET&gt; tag but isn't running the applet, for some reason."
    Your browser is completely ignoring the &lt;APPLET&gt; tag!
    </NOEMBED></EMBED>
    </OBJECT>
    </BODY>
    </HTML>

    My dear colleague, You better consider asking this question in Jdeveloper forum.
    I have a simple code for Windows application. You can easily convert it into Applet application..
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import oracle.jdbc.*;
    import oracle.sql.*;
    public class QueryFrame extends Frame {
    TextField inputText;
    public QueryFrame() {
    super("Query Interface");
    setSize(450, 250);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    ActionListener printListener = new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    ConnectAndRun(inputText.getText());
    Panel toolbar = new Panel();
    toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));
    Button queryButton = new Button("Run Query");
    queryButton.addActionListener(printListener);
    toolbar.add(queryButton);
    inputText = new TextField(14);
    toolbar.add(inputText);          
    // The "preferred" BorderLayout add call
    add(toolbar, BorderLayout.NORTH);
    public static void main(String args[]) {
    QueryFrame tf1 = new QueryFrame();
    tf1.setVisible(true);
         public void ConnectAndRun(String s)
              String sqlquery;
              if (s.equals(""))
              sqlquery ="select * from DEPT where LOC is null";
              else
              sqlquery ="select * from DEPT where LOC like '" + s + "'";
              System.out.println(sqlquery);
              try
              DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
         Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:HELLO","scott","tiger");
         Statement stmt = conn.createStatement ();
              ResultSet rset = stmt.executeQuery (sqlquery);
              while (rset.next ())
                   System.out.println( rset.getInt("DEPTNO"));
                   System.out.println( rset.getString("DNAME"));
                   System.out.println (rset.getString("LOC"));
              rset.close();
         stmt.close();          
              catch (SQLException se)
                   System.out.println(se);
    Make sure you have appropriate libraries in classpath...

Maybe you are looking for