Implementing a MousePressListener as a separate class

I've got a MousePressListener inner class (i.e. MouseListener that listens for MousePressed event) within a MouseApplet class. I want to implement this inner class as a class of its own. I suspect that I'm going to need to store a reference to the MouseApplet object in the Listener class and also include a constructor in this Listener that sets the reference to the MouseApplet class.
The logic's coming, but can't think of the syntax. Any ideas?
Thanks.

don't bother - just make your MouseApplet implement MouseListener
it saves you coding, memory, speed and class file size.

Similar Messages

  • Listen for an events for Swing objects in a separate class?

    Hi all, sorry if this is in the wrong section of the forum but since this is a problem I am having with a Swing based project I thought i'd come here for help. Essentially i have nested panels in separate classes for the sake of clarity and to follow the ideas of OO based development. I have JPanels that have buttons and other components that will trigger events. I wish for these events to effect other panels, in the Hierachy of my program:
    MainFrame(MainPanel(LeftPanel, RightPanel, CanvasPanel))
    Sorry I couldnt indent to show the hierarchy. Here LeftPanel, RightPanel and CanvasPanel are objects that are created in the MainPanel. For example i want an event to trigger a method in another class e.g. LeftPanel has a button that will call a method in CanvasPanel. I have tried creating an EventListner in the MainPanel that would determine the source and then send off a method to the relevant class, but the only listeners that respond are the ones relevant to the components of class. Can I have events that will be listened to over the complete scope of the program? or is there another way to have a component that can call a method in the class that as an object, it has been created in.
    Just as an example LeftPanel has a component to select the paint tool (its a simple drawing program) that will change a color attribute in the CanvasPanel object. Of course I realize i could have one massive Class with everything declared in it, but I'd rather learn if it is possible to do it this way!
    Thanks in advance for any help you can offer
    Lawrence
    Edited by: insertjokehere on Apr 15, 2008 12:24 PM

    Thanks for the response, ive added ActionListneres in the class where the component is, and in an external class. The Listeners work inside the class, but not in the external class
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    public class LeftPanel extends JPanel implements ActionListener {  
        /* Constructing JButtons, null until usage of the constructor */
        JButton pencilBut;
        JButton eraserBut;
        JButton textBut;
        JButton copyBut;
        JButton ssincBut;
        JButton ssdecBut;
        ActionListener a = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.print("\nNot supported yet.");
        /* The Top Panel contains the title of program */
        public LeftPanel(Dimension d){
            /* Sets up the layout for the Panel */
            BoxLayout blo = new BoxLayout(this,BoxLayout.Y_AXIS);
            this.setLayout(blo);
            /* Sets Up the Appearance of the Panel */
            this.setMinimumSize(d);
            this.setBackground(Color.RED);
            this.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
            /* Pencil Tool */
            pencilBut = new JButton("Pencil");
            pencilBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            pencilBut.setActionCommand("pencil");
            pencilBut.addActionListener(a);
            this.add(pencilBut);
            /* Eraser Tool */
            eraserBut = new JButton("Eraser");
            eraserBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            eraserBut.addActionListener(a);
            this.add(eraserBut);
            /* Text Tool */
            textBut = new JButton("Text");
            textBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            textBut.addActionListener(a);
            this.add(textBut);
            /* Copy Previous Page */
            copyBut = new JButton("Copy Page");
            copyBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            copyBut.addActionListener(a);
            this.add(copyBut);
            /* Stroke Size Increase */
            ssincBut = new JButton("Inc");
            ssincBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            ssincBut.addActionListener(a);
            this.add(ssincBut);
            /* Stroke Size Decrease */
            ssdecBut = new JButton("Dec");
            ssdecBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            ssdecBut.addActionListener(a);
            this.add(ssdecBut);
            System.out.print("\nLeftPanel Completed");
        public void actionPerformed(ActionEvent e) {
            System.out.print("\nAction Performed");
        }But this is not picked up in my external class here
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    public class MainPanel extends JPanel implements ActionListener {
        /* Creates a new the main JPanel that is used in the FlipBookFrame to contain all of the elements */
        public MainPanel(){
            /* TopPanel constraints*/
            tpcs.gridx = 1;
            tpcs.gridy = 0;
            tpcs.gridwidth = 1;
            tpcs.gridheight = 1;
            tpcs.fill = GridBagConstraints.BOTH;
            tpcs.weightx = 0.0;
            tpcs.weighty = 1.0;
            /* LeftPanel Constraints*/
            lpcs.gridx = 0;
            lpcs.gridy = 0;
            lpcs.gridwidth = 1;
            lpcs.gridheight = 3;
            lpcs.fill = GridBagConstraints.BOTH;
            lpcs.weightx = 1.0;
            lpcs.weighty = 1.0;
            /* CentrePanel Constraints*/
            cpcs.gridx = 1;
            cpcs.gridy = 1;
            cpcs.gridwidth = 1;
            cpcs.gridheight = 1;
            cpcs.fill = GridBagConstraints.NONE;
            cpcs.weightx = 0.0;
            cpcs.weighty = 0.0;
            /* RightPanel Constraints*/
            rpcs.gridx = 2;
            rpcs.gridy = 0;
            rpcs.gridwidth = 1;
            rpcs.gridheight = 3;
            rpcs.fill = GridBagConstraints.BOTH;
            rpcs.weightx = 1.0;
            rpcs.weighty = 1.0;
            /* BottomPanel Constraints*/
            bpcs.gridx = 1;
            bpcs.gridy = 2;
            bpcs.gridwidth = 1;
            bpcs.gridheight = 1;
            bpcs.fill = GridBagConstraints.BOTH;
            bpcs.weightx = 0.0;
            bpcs.weighty = 1.0;   
            this.setLayout(gblo);   //Sets the Layout of the panel to a GridBagLayout
            this.add(tp, tpcs); //Adds the TopPanel to the MainPanel using the TopPanel layout
            this.add(lp, lpcs); //Adds the LeftPanel to the MainPanel using the LeftPanel layout
            this.add(cp, cpcs); //Adds the CanvasPanel to the MainPanel using the CanvasPanel layout
            this.add(rp, rpcs); //Adds the RightPanel to the MainPanel using the RightPanel layout
            this.add(bp, bpcs); //Adds the BottomPanel to the MainPanel using the BottomPanel layout
            gblo.layoutContainer(this); //Lays Out the Container
        public PanelSizes getPanelSizes(){
            return ps;
        public void actionPerformed(ActionEvent e) {
            System.out.print("\nExternal Class finds event!");
            /*String command = e.getActionCommand();
            if (command.equals("pencil")){
                System.out.print("\nYESSSSSSSSSSSSSSSSSSSSS!");
        /* Create of objects using the PanelSizes funtions for defining the */
        PanelSizes ps = new PanelSizes();   //Creates a new PanelSizes object for sizing the panel
        CanvasPanel cp = new CanvasPanel(ps.getCentrePanelDimension()); //Creates a new Canvas Panel
        TopPanel tp = new TopPanel(ps.getHorizontalPanelDimension()); //Creates the TopPanel
        BottomPanel bp = new BottomPanel(ps.getHorizontalPanelDimension()); //Creates the BottomPanel
        LeftPanel lp = new LeftPanel(ps.getVerticalPanelDimension()); //Creates the LeftPanel
        RightPanel rp = new RightPanel(ps.getVerticalPanelDimension());   //Creates the RightPanel
        /* I have chosen to create individual constraints for each panel to allow for adding of all
         components a the end of the constructor. This will use slightly more memory but gives clarity
         in the code */
        GridBagConstraints cpcs = new GridBagConstraints();
        GridBagConstraints tpcs = new GridBagConstraints();
        GridBagConstraints bpcs = new GridBagConstraints();
        GridBagConstraints lpcs = new GridBagConstraints();   
        GridBagConstraints rpcs = new GridBagConstraints();
        GridBagLayout gblo = new GridBagLayout();
    }Any help will be greatly appreciated :-)

  • Executing an actionlistener in separate class

    Hi all,
    This is my first question on the Java forum. Hope I express myself clearly and I hope that someone can help me.
    I have created two classes (i.e. modified files that I found in Java books) - one which creates the user interface using JFrame (a text field and menu structure) and a second class which is basically the action listener for when the "menuFileLoad" button is pressed in the application.
    I would like to move the code for all "actionlisteners" to separate classes to make the code more transparent.
    I've moved the code for the action listener for the "menuFileLoad" button to the separate class "alistener".
    The code compiles well, but the action in the alistener class is not performed. It should put "Another text" in a text field. For test purposes, I've also put
    "System.out.println ("dada");" in the action listener and this is executed well.
    Has it something to do with the accessibility of the "TextField" ?
    This is the class that builds up the GUI
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.Object;
    import java.awt.Container;
    import javax.swing.JFileChooser;
    * Sample application using Frame.
    * @author
    * @version 1.00 08/09/10
    public class Getstring_ArrayFrame extends Frame {
         * The constructor.
         public TextField text = new TextField(20);
         public Getstring_ArrayFrame() {
            MenuBar menuBar = new MenuBar();
            Menu menuFile = new Menu();
            MenuItem menuFileExit = new MenuItem();
            MenuItem menuFileLoad = new MenuItem();
            MenuItem menuFileParse = new MenuItem();
            Menu menuFileTwo = new Menu();
            MenuItem menuFileDo = new MenuItem();
            menuFile.setLabel("File");
            menuFileExit.setLabel("Exit");
            menuFileLoad.setLabel("Load");
            menuFileDo.setLabel("Import Tool");
            menuFileParse.setLabel("Parse");
            menuFileTwo.setLabel("Tools");
            add(text);
            // Add action listener.for the menu button
            menuFileExit.addActionListener
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        Getstring_ArrayFrame.this.windowClosed();
    // DIT IS HEM - DE EERSTE ECHTE ACTION LISTENER
           menuFileLoad.addActionListener (new alistener ());
               // new ActionListener() {
                 //   public void actionPerformed(ActionEvent e) {
                   // text.setText ("Eerste tekstje, joepie. Misschien nu nog den xml erbij krijgen");
                   // text.setBackground(Color.black);
                   // text.setForeground(Color.white);
    menuFileParse.addActionListener
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                    text.setText ("Opnieuw een tekstje, met tevens ook al een nieuwe knop.");
                    //text.setBackground(Color.black);
                    // text.setForeground(Color.white);
            menuFile.add(menuFileExit);
            menuFile.add(menuFileLoad);
            menuFile.add(menuFileParse);
            menuFileTwo.add(menuFileDo);
            menuBar.add(menuFile);
            menuBar.add(menuFileTwo);
            setTitle("Getstring_Array");
            setMenuBar(menuBar);
            setSize(new Dimension(400, 400));
            // Add window listener.
            this.addWindowListener
                new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        Getstring_ArrayFrame.this.windowClosed();
         * Shutdown procedure when run as an application.
        protected void windowClosed() {
             // TODO: Check if it is safe to close the application
            // Exit application.
            System.exit(0);
    }==> This is the alistener class
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.Object;
    import java.awt.Container;
    import javax.swing.JFileChooser;
    public class alistener implements ActionListener {
         TextField text = new TextField(20);
    public alistener () {
    public void actionPerformed(ActionEvent e) {
                  System.out.println ("dada");
                   text.setText ("Another text.");
                   text.setBackground(Color.black);
                   text.setForeground(Color.white);
    }

    I don't know AWT, just Swing, but it appears that your listener needs a reference to the GUI which may be passed perhaps in the Listener's constructor, and the GUI needs public methods to allow the listener to change things -- but to limit this ability so as not to compromise encapsulation. This should work the same with AWT For instance:
    import java.awt.Color;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    import javax.swing.JTextField;
    public class SwingTest
      private JPanel mainPanel = new JPanel();
      private JTextField textfield = new JTextField(20);
      public SwingTest()
        textfield.setEditable(false);
        JButton testListenerBtn = new JButton("Test Listener");
        testListenerBtn.addActionListener(new SwingTestListener(this));
        mainPanel.add(textfield);
        mainPanel.add(testListenerBtn);
      // public methods to allow the listener to change things,
      // but limit this ability to only what we want to let it change
      public void textfieldSetText(String text)
        textfield.setText(text);
      public void textSetBackground(Color color)
        textfield.setBackground(color);
      public void textSetForeGround(Color color)
        textfield.setForeground(color);
      public JComponent getComponent()
        return mainPanel;
      private static void createAndShowUI()
        JFrame frame = new JFrame("SwingTest");
        frame.getContentPane().add(new SwingTest().getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            createAndShowUI();
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class SwingTestListener implements ActionListener
      private SwingTest swingtest;
      public SwingTestListener(SwingTest swingtest)
        this.swingtest = swingtest;
      public void actionPerformed(ActionEvent arg0)
        swingtest.textfieldSetText("This Listener works!");
        swingtest.textSetBackground(Color.black);
        swingtest.textSetForeGround(Color.white);
    }Edited by: Encephalopathic on Nov 5, 2008 12:27 AM

  • Using a Separate Class

    Hey, everybody. I'm learning Java through a text and it instructed me to write a class that contains several methods for generating random numbers and characters. It then instructed me to write a class containing a main method that calls one of the methods in this separate class. I know that you can't write two classes in one file, so I would appreciate it if someone could help by telling me how I'm supposed to make this work. Here are the two separate classes:
    1  public class RandomCharacter {
    2    /** Generate a random character between ch1 and ch2 */
    3    public static char getRandomCharacter(char ch1, char ch2) {
    4      return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
    5    }
    6
    7    /** Generate a random lowercase letter */
    8    public static char getRandomLowerCaseLetter() {
    9      return getRandomCharacter('a', 'z');
    10    }
    11
    12    /** Generate a random uppercase letter */
    13    public static char getRandomUpperCaseLetter() {
    14      return getRandomCharacter('A', 'Z');
    15    }
    16
    17    /** Generate a random digit character */
    18    public static char getRandomDigitCharacter() {
    19      return getRandomCharacter('0', '9');
    20    }
    21
    22    /** Generate a random character */
    23    public static char getRandomCharacter()  {
    24      return getRandomCharacter('\u0000', '\uFFFF');
    25    }
    26  }
    1  public class TestRandomCharacter {
    2    /** Main method */
    3    public static void main(String args[]) {
    4      final int NUMBER_OF_CHARS = 175;
    5      final int CHARS_PER_LINE = 25;
    6
    7      // Print random characters between '!' and '~', 25 chars per line
    8      for (int i = 0; i < NUMBER_OF_CHARS; i++) {
    9        char ch = RandomCharacter.getRandomLowerCaseLetter() ;
    10        if ((i + 1) % CHARS_PER_LINE == 0)
    11          System.out.println(ch);
    12        else
    13          System.out.print(ch);
    14      }
    15    }
    16  }

    So I put both of the files in a package called getrandom, then compiled the public class with the functions and tried to compile the class with the main function. This is what I got from the compiler:
    colton-ogdens-macbook:getrandom coltonogden$ javac TestRandomCharacter.java
    TestRandomCharacter.java:10: cannot find symbol
    symbol : variable RandomCharacter
    location: class getrandom.TestRandomCharacter
         char ch = RandomCharacter.getRandomLowerCaseLetter();
    ^
    1 error
    Here are the two source code files again:
    package getrandom;
    public class RandomCharacter {
         public static char getRandomCharacter(char ch1, char ch2) {
            return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
         public static char getRandomLowerCaseLetter() {
            return getRandomCharacter('a', 'z');
         public static char getRandomUpperCaseLetter() {
            return getRandomCharacter('A', 'Z');
         public static char getRandomDigitCharacter() {
            return getRandomCharacter();
         public static char getRandomCharacter() {
            return getRandomCharacter('\u0000', '\uFFFF');
    package getrandom;
    public class TestRandomCharacter {
         public static void main(String[] args) {
            final int NUMBER_OF_CHARS = 175;
            final int CHARS_PER_LINE = 25;
            for (int i = 0; i < NUMBER_OF_CHARS; i++) {
               char ch = RandomCharacter.getRandomLowerCaseLetter();
               if ((i + 1) % CHARS_PER_LINE == 0)
                  System.out.println(ch);
               else
                  System.out.print(ch);
    }It's exactly how they are given in the text, and with no explanation on packages or anything of the sort, which is strange. I put them both in the same directory, called also getrandom. What I suspect is that TestRandomCharacter isn't getting the class RandomCharacter, or I haven't created an instance of that class in TestRandomCharacter, but then why would the text write them out like this, expecting me to be able to compile them? I find it obscure.

  • How to restructure this code into separate classes?

    I have C# code that initializes a force feedback joystick and plays an effect file(vibrates the joystick). I have turn the console application into library
    code to make a dll so that I can use it in LabVIEW. 
    Right now all the code is written under one class, so went I put the dll in LabVIEW I can only select that one class. labVIEW guy told me that I need to
    restructure my C# code into separate classes. Each class that I want to access from LabVIEW needs to marked as public. Then I can instantiate that class in LabVIEW using a constructor, and call methods and set properties of that class using invoke nodes and
    property nodes.
    How can I do this correctly? I tried changing some of them into classes but doesn't work. Can you guys take a look at the code to see if it is even possible
    to break the code into separate classes? Also, if it is possible can you guide me, suggest some reading/video, etc.
    Thank you
    using System;
    using System.Drawing;
    using System.Collections;
    using System.Windows.Forms;
    using Microsoft.DirectX.DirectInput;
    namespace JoystickProject
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    private System.Windows.Forms.Label label1;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;
    private Device device = null;
    private bool running = true;
    private ArrayList effectList = new ArrayList();
    private string joyState = "";
    public bool InitializeInput()
    // Create our joystick device
    foreach(DeviceInstance di in Manager.GetDevices(DeviceClass.GameControl,
    EnumDevicesFlags.AttachedOnly | EnumDevicesFlags.ForceFeeback))
    // Pick the first attached joystick we see
    device = new Device(di.InstanceGuid);
    break;
    if (device == null) // We couldn't find a joystick
    return false;
    device.SetDataFormat(DeviceDataFormat.Joystick);
    device.SetCooperativeLevel(this, CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Background);
    device.Properties.AxisModeAbsolute = true;
    device.Properties.AutoCenter = false;
    device.Acquire();
    // Enumerate any axes
    foreach(DeviceObjectInstance doi in device.Objects)
    if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
    // We found an axis, set the range to a max of 10,000
    device.Properties.SetRange(ParameterHow.ById,
    doi.ObjectId, new InputRange(-5000, 5000));
    // Load our feedback file
    EffectList effects = null;
    effects = device.GetEffects(@"C:\MyEffectFile.ffe",
    FileEffectsFlags.ModifyIfNeeded);
    foreach(FileEffect fe in effects)
    EffectObject myEffect = new EffectObject(fe.EffectGuid, fe.EffectStruct,
    device);
    myEffect.Download();
    effectList.Add(myEffect);
    while(running)
    UpdateInputState();
    Application.DoEvents();
    return true;
    public void PlayEffects()
    // See if our effects are playing.
    foreach(EffectObject myEffect in effectList)
    //if (button0pressed == true)
    //MessageBox.Show("Button Pressed.");
    // myEffect.Start(1, EffectStartFlags.NoDownload);
    if (!myEffect.EffectStatus.Playing)
    // If not, play them
    myEffect.Start(1, EffectStartFlags.NoDownload);
    //button0pressed = true;
    protected override void OnClosed(EventArgs e)
    running = false;
    private void UpdateInputState()
    PlayEffects();
    // Check the joystick state
    JoystickState state = device.CurrentJoystickState;
    device.Poll();
    joyState = "Using JoystickState: \r\n";
    joyState += device.Properties.ProductName;
    joyState += "\n";
    joyState += device.ForceFeedbackState;
    joyState += "\n";
    joyState += state.ToString();
    byte[] buttons = state.GetButtons();
    for(int i = 0; i < buttons.Length; i++)
    joyState += string.Format("Button {0} {1}\r\n", i, buttons[i] != 0 ? "Pressed" : "Not Pressed");
    label1.Text = joyState;
    //if(buttons[0] != 0)
    //button0pressed = true;
    public Form1()
    // Required for Windows Form Designer support
    InitializeComponent();
    // TODO: Add any constructor code after InitializeComponent call
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    if( disposing )
    if (components != null)
    components.Dispose();
    base.Dispose( disposing );
    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    public void InitializeComponent()
    this.label1 = new System.Windows.Forms.Label();
    this.SuspendLayout();
    // label1
    this.label1.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
    this.label1.Location = new System.Drawing.Point(8, 8);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(272, 488);
    this.label1.TabIndex = 0;
    // Form1
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.BackColor = System.Drawing.SystemColors.ControlText;
    this.ClientSize = new System.Drawing.Size(288, 502);
    this.Controls.AddRange(new System.Windows.Forms.Control[] {
    this.label1});
    this.Name = "Form1";
    this.Text = "Joystick Stuff";
    this.ResumeLayout(false);
    #endregion
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    using (Form1 frm = new Form1())
    frm.Show();
    if (!frm.InitializeInput())
    MessageBox.Show("Couldn't find a joystick.");

    Imho he means the following.
    Your class has performs two tasks:
    Controlling the joystick.
    Managing the joystick with a form.
    So I would recommend, that you separate the WinForm from the joystick code. E.g.
    namespace JoystickCtlLib
    public class JoystickControl
    private Device device = null;
    private bool running = true;
    private ArrayList effectList = new ArrayList();
    private string joyState = "";
    public string State { get { return this.joyState; } }
    public bool InitializeInput() { return true; }
    public void PlayEffects() { }
    private void UpdateInputState() { }
    So that your joystick class does not reference or uses any winform or button.
    btw, there is a thing which is more important than that: Your polling the device in the main thread of your application. This will block your main application. Imho this should be a job for a thread like background worker.

  • How to Call a method from a separate class...?

    Hi there...
    I have a class name HMSCon which has a method named con...
    method con is the one the loads the jdbc driver and establishes the connection....Now!I have a separate class file named TAQueries,this is where i am going to write my SQL Statements...any idea how to use my variables from HMSCon to my TAQueries class???
    here's my code:
    public class HMSCon{
    public static void con(){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url="jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=" +
    "E:/samer/HardwareMonitoringSystem/src/hms/pkg/hmsData.mdb";
    Connection cn = DriverManager.getConnection(url,"Admin", "asian01");
    }catch(Exception s){
    System.err.print(s);}
    here's my seperate class file TAQueries,i put an error message below..
    class TAInfoQueries{
    public void insertNewTA(String TAID,String Fname,String Mname, String Lname,String Age,
    String Bdate,String Haddress,String ContactNo){
    // Statement stmt=cn.createStatement(); ERROR: Cannot find symbol cn.
    // stmt.executeUpdate("INSERT INTO TechnicalAssistants VALUES('sdfas','sdfsdf','sdfdsf','sdfdsf',3,04/13/04,'asdf','asdfsdf')");
    // stmt.close();
    }

    You can try the below code, but it's a bad idea to use staitc member for connection:(
    public class HMSCon{
    static Connection cn;
    static{
    con();
    public static void con(){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url="jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=" +
    "E:/samer/HardwareMonitoringSystem/src/hms/pkg/hmsData.mdb";
    cn = DriverManager.getConnection(url,"Admin", "asian01");
    }catch(Exception s){
    System.err.print(s);}
    here's my seperate class file TAQueries,i put an error message below..
    class TAInfoQueries{
    public void insertNewTA(String TAID,String Fname,String Mname, String Lname,String Age,
    String Bdate,String Haddress,String ContactNo){
    // Statement stmt=HMSCon.cn.createStatement(); ERROR: Cannot find symbol cn.
    // stmt.executeUpdate("INSERT INTO TechnicalAssistants VALUES('sdfas','sdfsdf','sdfdsf','sdfdsf',3,04/13/04,'asdf','asdfsdf')");
    // stmt.close();
    }

  • Implementation of DragManager in extended Panel class

    Hi,
    I'm facing a problem during implementation of DragManager in
    extended Panel class. I've a component which is extending the Panel
    class where I've attached four Images with their corresponding
    dragging features.
    Say, the four images' x positions as these: x1 = 10, x2 = 20,
    x3 = 30, x4 = 40. After adding the DragManger class and
    implementation of dragging feature to those Images, the dragging is
    works fine. But, the problem is, when I'm dragging x1 image, the
    imageProxy associated to x1 starts showing from exactly the x1
    position, but also all the three images' (x2, x3, x4) imageProxy
    starts dragging from x1 position only! When the expected result is,
    the x2 imageProxy shud starts drag from x2 x position itself, and
    for other x3 imageProxy from x3 position and x4 is their also.
    Except the x1 image, all the other three's imageProxy are not
    starts from their respective image x position.
    Anyone can give any idea.. how to overcome this?
    tnks.
    ASB

    What are the:
    DragManager.doDrag(initiator, ds, event, imageProxy, x, y,
    1.0);
    x and y parameters in your drag manager's doDrag method? They
    should be calculated from the point of mouse click that would
    event.localX and event.localY.
    ATTA

  • Implementing UIApplicationDelegate protocol methods in NSObject class not working.

    Hi Everyone,
    I am new bee in iphone developement. I want to implement UIApplicationDelegate protocol methods in one of my NSObject class, how can i implement that help me please.
    I have mentioned the sample code what acutal i want to impelment.
    .h file
    @interface SmaplClass : NSObject <UIApplicationDelegate>
    .m file
    - (void)applicationWillResignActive:(UIApplication *)application
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    -(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
    - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
    Want to implement the above methods is NSObject class to be implemented or used, its not working. Help me can do it.
    Please help me
    Thanks,

    I complete the above discussion with saying that it is better to implement the notification handling methods in your app delegate. If there are good reasons to not to do so, you have to implement the methods in another class, instantiate the class, and call the methods from the actual UIApplicationDelegate protocol methods in the AppDelegate object. This way you can remove the actual notification handling code from AppDelegate class.
    For example, suppose you implemented the methods in the class called Test. This is a sample code in the AppDelegate class:
    @implementation AppDelegate
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
          Test *t = [[Test alloc] init];
         [t application: application didReceiveRemoteNotification: userInfo];
    @end
    Or you can create an association relationship between the AppDelegate and Test, so you do not have to create a new Test instance in each of the remote notification handling methods:
    @interface AppDelegate {
         Test *test;
    @end
    @implementation AppDelegate
    + (id)init {
         if (self = [super init]) {
              test = [[Test alloc] init];
         return self;
    - (void)dealloc {
         [test release];
         [super dealloc];
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
         // No need to create a Test instance. You just forward the call from AppDelegate instance to test      // instance
         [test application: application didReceiveRemoteNotification: userInfo];
    @end

  • Clarification of JAR file and separate classes

    Hi all,
    I wanted to clarify a basic question. When do we club all classes to make a JAR file? For instance, in a web app with servlets, had all the servlet classes been put into a single JAR file, would that work? I know that woudn't but why?
    Is JAR file like a single executable (.exe) file? So, when (which type of applications) do we need single JAR and when separate classes?
    thanks much

    Thanks, I've gone thru it. So, sounds like JAR file can be used for invoking app thru command line or from some other app or even running applet in a browser. It can not be used for a servlet or jsp application. Am I right?

  • Moving buttons and their listeners to separate classes

    Hi
    I am trying to move out buttons and their listeners to separate classes, but when I do so, the program stops working. When I click on the button they dont react, probably the listeners doesent listens as the action performe prints out testprints.
    In other words, I have huge troubles with do my gui object oriented. I doesent seem to be able to move out relevant listener methods and their components to separate classes.
    Here is the code for one add button that I have tried to write in a separate class:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.sql.SQLException;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import se.cs.DB.DBMovie;
    import se.cs.inputvalidation.PatternsMovie;
    import se.cs.main.Main;
    import se.cs.main.MessageArea;
    public class ButtonAddMovie {
         private DBMovie init = new DBMovie();
         private ComboBoxesMovie comboBoxesMovie = new ComboBoxesMovie();
         private TextFieldsMovie textFieldsMovie = new TextFieldsMovie();
         private PatternsMovie patternsMovie = new PatternsMovie();
         private MessageArea messageArea = new MessageArea();
         private Pattern patternYear;
         private Pattern patternSection;
         private Pattern patternExFields;
         private Matcher matcherYear;
         private Matcher matcherSection;
         private Matcher matcherTotalEx;
         private Matcher matcherExIn;
         private Matcher matcherExOut;
         private String genreString;
         // Initializes the button components
         private JButton addButton = new JButton("Add");
         public ButtonAddMovie() {
              listener();
         public void listener() {
              addButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        addButton(e);
         public void addButton(ActionEvent e) {
              genreString = comboBoxesMovie.convertGenreIndex();
              regex();
         public void regex() {
              patternYear = Pattern.compile(patternsMovie.getYEAR_FIELD());
              patternSection = Pattern.compile(patternsMovie.getSECTION_FIELD());
              patternExFields = Pattern.compile(patternsMovie.getExFields());
              matcherYear = patternYear.matcher(textFieldsMovie.getTextYear());
              matcherSection = patternSection.matcher(textFieldsMovie.getTextYear());
              matcherTotalEx = patternExFields.matcher(textFieldsMovie
                        .getTextTotalEx());
              matcherExIn = patternExFields.matcher(textFieldsMovie.getTextExIn());
              matcherExOut = patternExFields.matcher(textFieldsMovie.getTextExOut());
              if (matcherYear.matches() && matcherSection.matches()
                        && matcherTotalEx.matches() && matcherExIn.matches()
                        && matcherExOut.matches()) {
                   messageArea.getMessageArea().setText("");
                   callInsertStatement();
                   JOptionPane.showMessageDialog(null, this.messageDialog(),
                             "Movie added", JOptionPane.INFORMATION_MESSAGE);
              else if (!matcherYear.matches()) {
                   messageArea.getMessageArea().setText(
                             "The input for year field does not match.\n"
                                       + "You have to enter 4 digits.");
              else if (!matcherSection.matches()) {
                   messageArea.getMessageArea().setText(
                             "The input for section field does not match.\n"
                                       + "You have to enter 1-4 digits.");
              else if (!matcherTotalEx.matches()) {
                   messageArea.getMessageArea().setText(
                             "The input for total ex field does not match.\n"
                                       + "You have to enter 1.");
              else if (!matcherExIn.matches()) {
                   messageArea.getMessageArea().setText(
                             "The input for ex in does not match.\n"
                                       + "You have to enter 1 digit.");
              else if (!matcherExOut.matches()) {
                   messageArea.getMessageArea().setText(
                             "The input  for ex out does not match.\n"
                                       + "You have to enter 1 digits.");
         public void callInsertStatement() {
              try {
                   init.insertStatement(textFieldsMovie.getTextTitle(),
                             textFieldsMovie.getTextYear(), genreString, comboBoxesMovie
                                       .convertGradeIndex(), textFieldsMovie
                                       .getTextSection(),
                             textFieldsMovie.getTextTotalEx(), textFieldsMovie
                                       .getTextExIn(), textFieldsMovie.getTextExOut());
              } catch (SQLException ex) {
                   ex.printStackTrace();
         public String messageDialog() {
              int grade = comboBoxesMovie.getGradeBox().getSelectedIndex() + 1;
              String title = textFieldsMovie.getTitleField().getText();
              String year = textFieldsMovie.getYearField().getText();
              String section = textFieldsMovie.getSectionField().getText();
              String totalEx = textFieldsMovie.getTotalExField().getText();
              String exIn = textFieldsMovie.getExInField().getText();
              String exOut = textFieldsMovie.getExOutField().getText();
              return "\n" + "Title: " + title + "\n" + "Year: " + year + "\n"
                        + "Genre: " + comboBoxesMovie.convertGenreIndex() + "\n"
                        + "Grade: " + grade + "\n" + "Section: " + section + "\n"
                        + "Total ex.: " + totalEx + "\n" + "Ex. in: " + exIn + "\n"
                        + "Ex. out: " + exOut + "\n";
          * Gets the addButton
          * @return addButton
         public JButton getAddButton() {
              return addButton;
         }

    I said "don't" cross-post and that the discussion has already been started in the "New To Java" forum.
    If you have two discussions going on then people waste time answering because they don't know what has already been suggested.

  • Implements interface method at the derived class

    Hi all.
    I have a class (Derived) that extends another class (Base).
    In the base class (Base) there is a method f() with its implementation.
    In the interface (C) there is also f() method exactlly like in the base class (Base).
    The derived class (Derived) is implements the interface (C).
    My question is:
    Do i have to implement the method f() in the derived class (Derived) ?

    My guess is that you probably have to, even if it's just to call the parent's method.
    This all sounds pretty sketchy. Why don't you just make the BASE class implement your interface?

  • Implementing DOM Interface with existing Java classes

    I had planned on using some tree-like Java classes as a Document Object Model, which would give me access to all sorts of XML and DOM tools like parsers and XSLT transformers. Initially, I thought all that would be neccessary is to implement all the DOM Interfaces in org.w3c.dom and then I would have a set of classes that conformed to DOM Level 1. It was my understanding that interfaces such as DOMImplementation and Document would interface with various XML tools, allowing creation of a class that implements Document and then Document would have its various factory methods that know how to create the various DOM nodes such as Element, Attr, Text, NamedNodeMap, NodeList, etc.
    The problem I'm seeing now is that the JAXP specification (which is what the latest Xerces and Xalan tools conform to) has something called a DocumentBuilder and DocumentBuilderFactory that appear to be necessary to tell the framework what type of class to instantiate that implements the Document DOM interface. Those appear to have a lot of methods that deal with parsing of XML documents and I didn't really want to write or even subclass any existing Parsers in order to get the functionality of traversing and transforming a set of classes that implement the DOM interface.
    Am I missing something here? Is it possible to plug in any (set of classes for) DOMImplementation and get them to work with the various DOM and XML tools out there?
    Is there an easier way to allow parts of an application access to internal data structures but have the more generic tools or APIs, such as XSL transformers, access that same set of classes as a DOM with the generic DOM interface methods?
    Can someone provide me with some guidance here? I'm in the process of finalizing some design on a system and need to know if this is possible or if I need to alter my design.
    Thanks.

    If I understand you correctly, I think I am working on a similar issue. I am unhappy with the methods given by the DOM for retrieving data from the XML file and for building a file. Our software has a bunch of code that uses these classes and it is extremely ugly. My solution was to create a facade on top of the DOM model. Essentially I have some simple classes that store all the pertinent info (for me) about the XML structure. Essentially that is the element or attribute name, its values and in the case of the element, it's children. This makes it easier for me to build and retreive the data. What I then built was a loader class and a builder class. The loader takes an XML file and parses it in using the DOM classes and builds a structure using my classes and returns the root element. The builder takes a root element and creates a DOM object out of it. This frees me of having to code around the DOM classes all over the place and makes it simple to upgrade our XML code if the DOM changes or a better DOM is released. I am using factories to facilitate this and allow me to have loaders for specific types of XML documents so that I can have a class for each which further simplifies the XML related tasks of other developers on my team.

  • JDWP reference implementation does not return anonymous nested classes?

    Using
    $ java -version
    java version "1.6.0_22"
    Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
    Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)
    it appears that when I connect with JDWP and issue a NestedTypes command, the result does not include anonymous nested types. The only references to this that I could find is a comment in a svn commit at apache (http://mail-archives.apache.org/mod_mbox/harmony-commits/200611.mbox/%[email protected]%3E)
    Is this intentional and desired? Is there a way to get all of the nested types, including the anonymous ones? I could do ClassesBySignature with "package.ClassName$*" as the signature and filter out doubly nested classes, but that seems overly complicated.

    exept, you can NOT have an implementation of an
    abstract class (which foundPlugin) is without an
    implementation of all it's subclasses (such as
    argsObject) You're mistaken in a couple of ways here.
    First, a nested class is not the same as a subclass.
    Second, a concrete class must have implementations for all its methods, but it can still have an abstract nested class.
    Third, you can have an instance of a concrete class that has abstract subclasses. Object is concrete and has many concrete subclasses. Classes don't know anything about their subclasses.
    This compiles.
    public abstract class AbOut {
      public abstract class AbIn {  public abstract void bar(); }
    public class ConcOut extends AbOut {
      public abstract class AbIn2 { public abstract void foo();}
    foundPlugin MUST have an implementation
    of argsObject, according to the rules of java,And you think this because...?
    You read it in the JLS? Citation please.
    You tried to compile and it failed? My sample above demonstrates the countereample. If I'm misunderstanding what you're talking about, please post an example
    Or maybe you just thought it had to be that way because that seemed the most intuitive and when it wasn't, rather than trying to understand or adjust your thinking, you figured it would be more fun to throw a hissy fit and call Java "stupid"?

  • Unable to implement Constructor Overloading in an inherited class. Plz Help

    Please do compile the program in in order to notice the error.
    class EmpDet
    int id,age;
    String name;
    String gender;
      EmpDet(int id1,String name1,int age1,String gender1)
        this.id = id1;
        this.name= name1;
        this.age= age1;
        this.gender = gender1;
       void Id_Name()
       System.out.println("EmpId : "+id+" and Name : "+name);
       void Gender_Age()
        System.out.println("Employee is a "+gender+" and is "+age+" years old.");
      class Employee extends EmpDet
           String locality;
        Employee(int a,String b,int c,String d)
             super(a,b,c,d);
        Employee(String locality1)// Constructor overloading. My problem.
             this.locality = locality1;
      void locality()
        System.out.println("The employee resides at "+locality);
       void DiplayStmt()
            System.out.println("DISPLAYING EMPLOYEE DETAILS..");
            System.out.println("******************************");
       public static void main (String[] args)
        Employee det = new Employee(010,"John",32,"M");
        Employee addr = new Employee("Tambaram");
        addr.DiplayStmt();
        det.Id_Name();
        det.Gender_Age();
        addr.locality();
      }

    Hey Thanks.. I guess what you said makes sense.
    I was fiding it hard to agree that there needs to be a match between the Constructors of the Base Class and the Sub Class. I altered the program by adding a constructor in the Base class and using the super(0 function in the Sub class and that seems to work..
    class EmpDet
    int id,age;
    String name;
    String gender;
    EmpDet(int id1,String name1,int age1,String gender1)
         this.id = id1;
    this.name= name1;
    this.age= age1;
    this.gender = gender1;
    EmpDet(String addr)
         System.out.println("Address is implemented in SubClass");
    void Id_Name()
    System.out.println("EmpId : "+id+" and Name : "+name);
    void Gender_Age()
    System.out.println("Employee is a "+gender+" and is "+age+" years old.");
    class Employee extends EmpDet
         String locality;
    Employee(int a,String b,int c,String d)
         super(a,b,c,d);
    Employee(String locality1) // Constructor Overloading
         super(locality1);
         this.locality = locality1;
    void locality()
    System.out.println("The employee resides at "+locality);
    void DiplayStmt()
         System.out.println("DISPLAYING EMPLOYEE DETAILS..");
         System.out.println("******************************");
    public static void main (String[] args)
    Employee det = new Employee(010,"John",32,"M");
    Employee addr = new Employee("Tambaram");
    addr.DiplayStmt();
    det.Id_Name();
    det.Gender_Age();
    addr.locality();
    Message was edited by:
    3402102

  • Looking for an add in to separate classes in distinct files

    I'm working on a old program. .cs files are used to store multiples classes.
    Do you know a visual studio extension able to split multiple classes .cs files in separate files ?
    Tanks for help
    Laurent

    Hi Laurent,
    Maybe the re-sharper is what you want to get.
    Reference:
    http://stackoverflow.com/questions/2652901/text-manipulation-split-classes-in-a-single-file-into-mulitple-files
    In addition, since it is not the VS IDE usage issue, I am moving your question to the moderator forum ("Where is the forum for..?"). The owner of the forum will direct you to a right forum.
    Best Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

Maybe you are looking for

  • The Path to nowhere - help! swf files not showing in browser

    i need help with getting a swf file to show in the browsers. (it previews in dreamweaver) created a website in dreamweaver cs4. created a simple slideshow in flash 4. on the index.html page inserted the flash file. it previews in dreamweaver BUT when

  • Can't find QT now

    Sorry guys - I should have asked the last question before doing what I did. I dumped the QT icon from the Apps folder in the trash and emptied it - so that I could download 7.2 Now - I can't get 7.2 and I can't find my old QT pro (7.4 I believe)? Wen

  • Variables in BI 7.0

    Dear Friends, I am creating reports in BI 7.0 however, it is opening BW 3.5 screen. In the reports when i am including any variables on any info objects, it throws out the below error and exits from query designer. Run time error 2417417848 (80010108

  • Why does it keep telling me "this app isnt available for ipod touch" even after i search for ipod touch apps????

    i cannot download a LOT of apps to my ipod. but i have updated my ipod, ive been REFERRED to certain apps by blogs that are for ipod touches but i cant get them on my ipod.

  • Thoughts on automation for gradient mesh illustrations....

    So I've been looking around at various tutorials on creating gradient mesh illustrations. The general theme that keeps popping up is how time consuming it is to colourize the mesh, point by point. Some clever programmer out there could surely find so