Implementation of static methods in Custom Controls

I'm using Custom Java Controls to implement business objects in a workshop web application.
I've designed a number of static methods into the object model for logically static operations (i.e. operations related to the Business object but not requiring an instance).
Since workshop generates the control interface as a java interface, it is not possible to declare static methods on the control interface. I have tested implementing the interface as an abstract class and setting @editor-info:code-gen control-interface="false" on the control. This seems to work, but then we lose code generation.
Other options include:
- Put the static method on the Impl and call directly (don't like this, breaks encapsulation)
- Make it non-static (don't like this, prevents compiler checks for refs to non-static members)
Has anyone found an elegant way to do this in workshop without losing code gen features? Any ideas welcome...
TIA
Jim

Please guys someone tell me the answer for this question. I guess its a valid question, though I feel that the answer to this question must be quiet easy since somewhere the methods must have been getting implemented.
Please let me know who does that and how and when!!!
Hoping for an explanation to this now

Similar Messages

  • Apply static method requirements on class (Static interface methods)?

    I have a set of classes where is class is identified with a unique ID number. So each class has a public static int getId() method. Each class also has either a constructor that takes a byte array or a static factory method that takes a byte array.
    I would like to maintain a hashmap of these classes keyed to the ID's however I am not sure how to have some interface of abstract parent class that requires each of these classes to implement these static methods.
    What I was hoping to do was something like this>>>
         public interface MyClasses{
              static MyClasses createInstance(byte[] data);
         HashMap<Integer, MyClasses> map;
         public void init() {
              map = new HashMap<Integer, MyClasses>();
              map.put(Class1.getId(), Class1.class);
              map.put(Class2.getId(), Class2.class);
         public void createInstance (int id, byte[] data) {
              map.get(id).createInstance(data);
         }Is there some way I could do this?

    What about something like this?
    public interface Initializable
         public void initialize(byte[] data);
    public class Factory
         private final Map<Integer, Initializable> map = new HashMap<Integer, Initializable>();
            public void registerClass(int id, Class klass)
                    if (! Initializable.class.isAssignableFrom(klass))
                             // you may also want to ensure the class declares a parameterless constructor
                             throw new IllegalArgumentException("duff class");
                    if (this.map.keySet().contains(id))
                             throw new IllegalArgumentException("duff id");
              this.map.put(id, klass);
         public Initializable createInstance(int id, byte[] data)
                    // need some exception handling of course
              Initializable i = map.get(id).newInstance();
                    i.initialize(data);
                    return i;
    }

  • Force Derived Class to Implement Static Method C#

    So the situation is like, I have few classes, all of which have a standard CRUD methods but static. I want to create a base class which will be inherited so that it can force to implement this CRUD methods. But the problem is, the CRUD methods are static. So
    I'm unable to create virtual methods with static (for obvious reasons). Is there anyway I can implement this without compromising on static.
    Also, the signature of these CRUD methods are similar.
    E.g. ClassA will have CRUD methods with these type of Signatures
    public static List<ClassA> Get()
    public static ClassA Get(int ID)
    public static bool Insert(ClassA objA)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    ClassB will have CRUD signatures like
    public static List<ClassB> Get()
    public static ClassB Get(int ID)
    public static bool Insert(ClassB objB)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    So I want to create a base class with exact similar signature, so that inherited derived methods will implement their own version.
    For E.g. BaseClass will have CRUD methods like
    public virtual static List<BaseClass> Get()
    public virtual static BaseClassGet(int ID)
    public virtual static bool Insert(BaseClass objBase)
    public virtual static bool Update(int ID)
    public virtual static bool Delete(int ID)
    But the problem is I can't use virtual and static due to it's ovbious logic which will fail and have no meaning.
    So is there any way out?
    Also, I have few common variables (constants) which I want to declare in that base class so that I don't need to declare them on each derived class. That's why i can't go with interface also.
    Anything that can be done with Abstract class?

    Hi,
    With static methods, this is absolutely useless.
    Instead, you could use the "Singleton" pattern which restrict a class to have only one instance at a time.
    To implement a class which has the singleton pattern principle, you make a sealed class with a private constructor, and the main instance which is to be accessed is a readonly static member.
    For example :
    sealed class Singleton
    //Some methods
    void Method1() { }
    int Method2() { return 5; }
    //The private constructor
    private Singleton() { }
    //And, most importantly, the only instance to be accessed
    private static readonly _instance = new Singleton();
    //The corresponding property for public access
    public static Instance { get { return _instance; } }
    And then you can access it this way :
    Singleton.Instance.Method1();
    Now, to have a "mold" for this, you could make an interface with the methods you want, and then implement it in a singleton class :
    interface ICRUD<BaseClass>
    List<BaseClass> GetList();
    BaseClass Get(int ID);
    bool Insert(BaseClass objB);
    bool Update(int ID);
    bool Delete(int ID);
    And then an example of singleton class :
    sealed class CRUDClassA : ICRUD<ClassA>
    public List<ClassA> GetList()
    //Make your own impl.
    throw new NotImplementedException();
    public ClassA Get(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Insert(ClassA objA)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Update(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Delete(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    private CRUDClassA() { }
    private static readonly _instance = new CRUDClassA();
    public static Instance { get { return _instance; } }
    That should solve your problem, I think...
    Philippe

  • Forcing implementation of an inherited static method/field?

    Suppose I have some classes - BlueAction, RedAction etc - extending an abstract base class called BaseAction. I put an abstract method called getColour() in BaseAction, and implement it in all the classes that extend it, so BlueAction returns blue, and so on. Fine.
    I now want to use a class loader to get their colour, but crucially, I don't want to instantiate them, so instance methods are out.
    If you could declare abstract static methods, I'd do that, and be assured that every implementation of BaseAction contained the necessary info. Obviously you can't do this.
    I think I could just put a static method or field in each one, and access that via something like Class.getField("COLOUR")but then there's nothing to force me to put that code into each implementation.
    Is there anything clever I can do?
    Cheers,
    Rob
    Edited by: arewenotmen on Jun 20, 2008 3:51 AM

    baftos wrote:
    I guess it should be possible. Me, I did play with runtime annotations, but I am scared like hell
    of compile time annotation. My reasons, but maybe I am wrong:All good reasons.
    - Modify the build process to use APT instead of javacYou could use in -nocompile mode and add a task to the build script.
    - Writing annotation processors, big overheadI had a play, was not too hard to get started with, but then it started to get wierd and data I expected was not being returned.
    - Using com.sun classes in the processors instead of java/javax classes (subject to change?)Java 6 has the javax.annotations package (also works with javac rather than a different tool), but this seams less powerful than apt.
    A fair few things now mean the "don't touch the com.sun package" rule is being eroded. The httpd is in it as well.

  • Implementing interface with static method?

    Hi,
    I need to implement an interface with a static method. I tried to do it both with the interface method static and non-static, but it don't seam to work! Does it work?
    How can I make a work around?
    Thanks!

    Interfaces are designed to provide a contract that a particular object instance guarantees for it's Clients.
    Since a static method does not relate to any particular object instance there is no contract to define...hence you can't have an interface for static methods...
    What you could do however is return an object via a static method that does provide the implementation of the interface...
    i.e.public class MyClass
        static private String myInterfaceImpl = "<some class>";
        static public MyInterface getInterface ()
             return (MyInterface) MyClass.class.forName (MyClass.myInterfaceImpl).newInstance ();
    }That would return an object that provides the interface. I would presume you need the static method so that you don't have to pass around references to a particular object...this method gets around that...you could also create a single object at start up time and return a reference to that eveytime...
    Also, in a way static methods do define an interface...

  • Choosing custom control implementation

    Hello,
    Is there a way to specify the custom controls' implementation to be used (eg. specifying which jar to use, at server startup)?
    Since the controls variables point to an interface, I was wondering if there is any mechanism to specify which control implementation to use. So I could plug the control's - dummy, test or production - implementation without changing the clients of my controls.
    Thanks for help,
    Yves

    Hi,
    For report,, include the following statement
    CALL SCREEN 100.
    Double click on number 100 , Then CLick on Layout ..and follow the same steps as Dialog programming i.e. Drag & drop the Custom Control, assign a name to it & activate
    Best regards,
    Prashant

  • How to have custom control in DataGridView display object's value?

    I have a sample project located
    here
    The project has a main form `Form1` where the user can enter customers in a datagridview. The `CustomerType` column is a custom control and when the user clicks the button, a search form `Form2` pops up.
    The search form is populated with a list of type `CustomerType`. The user can select a record by double-clicking on the row, and this object should be set in the custom control. The `DataGridView` should then display the `Description` property but in the background
    each cell should hold the value (ie. the `CustomerType` instance).
    The relevant code is located in the following classes:
    The column class:
    public class DataGridViewCustomerTypeColumn : DataGridViewColumn
    public DataGridViewCustomerTypeColumn()
    : base(new CustomerTypeCell())
    public override DataGridViewCell CellTemplate
    get { return base.CellTemplate; }
    set
    if (value != null && !value.GetType().IsAssignableFrom(typeof(CustomerTypeCell)))
    throw new InvalidCastException("Should be CustomerTypeCell.");
    base.CellTemplate = value;
    The cell class:
    public class CustomerTypeCell : DataGridViewTextBoxCell
    public CustomerTypeCell()
    : base()
    public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
    base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
    CustomerTypeSearch ctl = DataGridView.EditingControl as CustomerTypeSearch;
    if (this.Value == null)
    ctl.Value = (CustomerType)this.DefaultNewRowValue;
    else
    ctl.Value = (CustomerType)this.Value;
    public override Type EditType
    get { return typeof(CustomerTypeSearch); }
    public override Type ValueType
    get { return typeof(CustomerType); }
    public override object DefaultNewRowValue
    get { return null; }
    And the custom control:
    public partial class CustomerTypeSearch : UserControl, IDataGridViewEditingControl
    private DataGridView dataGridView;
    private int rowIndex;
    private bool valueChanged = false;
    private CustomerType value;
    public CustomerTypeSearch()
    InitializeComponent();
    public CustomerType Value
    get { return this.value; }
    set
    this.value = value;
    if (value != null)
    textBoxSearch.Text = value.Description;
    else
    textBoxSearch.Clear();
    private void buttonSearch_Click(object sender, EventArgs e)
    Form2 f = new Form2();
    DialogResult dr = f.ShowDialog(this);
    if (dr == DialogResult.OK)
    Value = f.SelectedValue;
    #region IDataGridViewEditingControl implementation
    public object EditingControlFormattedValue
    get
    if (this.value != null)
    return this.value.Description;
    else
    return null;
    set
    if (this.value != null)
    this.value.Description = (string)value;
    public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
    return EditingControlFormattedValue;
    public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
    this.BorderStyle = BorderStyle.None;
    this.Font = dataGridViewCellStyle.Font;
    public int EditingControlRowIndex
    get { return rowIndex; }
    set { rowIndex = value; }
    public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
    return false;
    public void PrepareEditingControlForEdit(bool selectAll)
    //No preparation needs to be done
    public bool RepositionEditingControlOnValueChange
    get { return false; }
    public DataGridView EditingControlDataGridView
    get { return dataGridView; }
    set { dataGridView = value; }
    public bool EditingControlValueChanged
    get { return valueChanged; }
    set { valueChanged = value; }
    public Cursor EditingPanelCursor
    get { return base.Cursor; }
    #endregion
    private void CustomerTypeSearch_Resize(object sender, EventArgs e)
    buttonSearch.Left = this.Width - buttonSearch.Width;
    textBoxSearch.Width = buttonSearch.Left;
    However, the `DataGridView` is not displaying the text and it also is not keeping the `CustomerType` value for each cell.
    What am I missing?
    Marketplace: [url=http://tinyurl.com/75gc58b]Itza[/url] - Review: [url=http://tinyurl.com/ctdz422]Itza Update[/url]

    Hello,
    1. To display the text, we need to override the ToString method for CustomerType
    public class CustomerType
    public int Id { get; set; }
    public string Description { get; set; }
    public CustomerType(int id, string description)
    this.Id = id;
    this.Description = description;
    public override string ToString()
    return this.Description.ToString();
    2. To get the cell's value changed, we could pass the cell instance to that editing control and get its value changed with the following way.
    public partial class CustomerTypeSearch : UserControl, IDataGridViewEditingControl
    private DataGridView dataGridView;
    private int rowIndex;
    private bool valueChanged = false;
    private CustomerTypeCell currentCell = null;
    public CustomerTypeCell OwnerCell
    get { return currentCell; }
    set
    currentCell = null;
    currentCell = value;
    public CustomerTypeSearch()
    InitializeComponent();
    private void buttonSearch_Click(object sender, EventArgs e)
    Form2 f = new Form2();
    DialogResult dr = f.ShowDialog(this);
    if (dr == DialogResult.OK)
    currentCell.Value = f.SelectedValue;
    this.textBoxSearch.Text = f.SelectedValue.Description;
    #region IDataGridViewEditingControl implementation
    public object EditingControlFormattedValue
    get
    if (this.currentCell.Value != null)
    return (this.currentCell.Value as CustomerType).Description;
    else
    return null;
    set
    if (this.currentCell != null)
    (this.currentCell.Value as CustomerType).Description = (string)value;
    public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
    return EditingControlFormattedValue;
    public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
    this.BorderStyle = BorderStyle.None;
    this.Font = dataGridViewCellStyle.Font;
    public int EditingControlRowIndex
    get { return rowIndex; }
    set { rowIndex = value; }
    public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
    return false;
    public void PrepareEditingControlForEdit(bool selectAll)
    //No preparation needs to be done
    public bool RepositionEditingControlOnValueChange
    get { return false; }
    public DataGridView EditingControlDataGridView
    get { return dataGridView; }
    set { dataGridView = value; }
    public bool EditingControlValueChanged
    get { return valueChanged; }
    set { valueChanged = value; }
    public Cursor EditingPanelCursor
    get { return base.Cursor; }
    #endregion
    private void CustomerTypeSearch_Resize(object sender, EventArgs e)
    buttonSearch.Left = this.Width - buttonSearch.Width;
    textBoxSearch.Width = buttonSearch.Left;
    Cell:
    public class CustomerTypeCell : DataGridViewTextBoxCell
    public CustomerTypeCell()
    : base()
    public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
    base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
    CustomerTypeSearch ctl = DataGridView.EditingControl as CustomerTypeSearch;
    ctl.OwnerCell = this;
    public override Type EditType
    get { return typeof(CustomerTypeSearch); }
    public override Type ValueType
    get { return typeof(CustomerType); }
    public override object DefaultNewRowValue
    get { return null; }
    Result:
    Regards,
    Carl
    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.

  • Problem with custom control and focus

    I've a problem with the focus in a custom control that contains a TextField and some custom nodes.
    If i create a form with some of these custom controls i'm not able to navigate through these fields by using the TAB key.
    I've implemented a KeyEvent listener on the custom control and was able to grab the focus and forward it to the embedded TextField by calling requestFocus() on the TextField but the problem is that the TextField won't get rid of the focus anymore. Means if i press TAB the first embedded TextField will get the focus, after pressing TAB again the embedded TextField in the next custom control will get the focus AND the former focused TextField still got the focus!?
    So i'm not able to remove the focus from an embeded TextField.
    Any idea how to do this ?

    Here you go, it contains the control, skin and behavior of the custom control, the css file and a test file that shows the problem...
    control:
    import javafx.scene.control.Control;
    import javafx.scene.control.TextField;
    public class TestInput extends Control {
        private static final String DEFAULT_STYLE_CLASS = "test-input";
        private TextField           textField;
        private int                 id;
        public TestInput(final int ID) {
            super();
            id = ID;
            textField = new TextField();
            init();
        private void init() {
            getStyleClass().add(DEFAULT_STYLE_CLASS);
        public TextField getTextField() {
            return textField;
        @Override protected String getUserAgentStylesheet() {
                return getClass().getResource("testinput.css").toExternalForm();
        @Override public String toString() {
            return "TestInput" + id + ": " + super.toString();
    }skin:
    import com.sun.javafx.scene.control.skin.SkinBase;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.event.EventHandler;
    import javafx.scene.control.TextField;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyEvent;
    public class TestInputSkin extends SkinBase<TestInput, TestInputBehavior> {
        private TestInput control;
        private TextField textField;
        private boolean   initialized;
        public TestInputSkin(final TestInput CONTROL) {
            super(CONTROL, new TestInputBehavior(CONTROL));
            control     = CONTROL;
            textField   = control.getTextField();
            initialized = false;
            init();
        private void init() {
            initialized = true;
            paint();
        public final void paint() {
            if (!initialized) {
                init();
            getChildren().clear();
            getChildren().addAll(textField);
        @Override public final TestInput getSkinnable() {
            return control;
        @Override public final void dispose() {
            control = null;
    }behavior:
    import com.sun.javafx.scene.control.behavior.BehaviorBase;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.event.EventHandler;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyEvent;
    public class TestInputBehavior extends BehaviorBase<TestInput> {
        private TestInput control;
        public TestInputBehavior(final TestInput CONTROL) {
            super(CONTROL);
            control = CONTROL;
            control.getTextField().addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
                @Override public void handle(final KeyEvent EVENT) {
                    if (KeyEvent.KEY_PRESSED.equals(EVENT.getEventType())) {
                        keyPressed(EVENT);
            control.focusedProperty().addListener(new ChangeListener<Boolean>() {
                @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean wasFocused, Boolean isFocused) {
                    if (isFocused) { isFocused(); } else { lostFocus(); }
        public void isFocused() {
            System.out.println(control.toString() + " got focus");
            control.getTextField().requestFocus();
        public void lostFocus() {
            System.out.println(control.toString() + " lost focus");
        public void keyPressed(KeyEvent EVENT) {
            if (KeyCode.TAB.equals(EVENT.getCode())) {
                control.getScene().getFocusOwner().requestFocus();
    }the css file:
    .test-input {
        -fx-skin: "TestInputSkin";
    }and finally the test app:
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.GridPane;
    import javafx.stage.Stage;
    public class Test extends Application {
        TestInput input1;
        TestInput input2;
        TestInput input3;
        TextField input4;
        TextField input5;
        TextField input6;
        Scene     scene;
        @Override public void start(final Stage STAGE) {
            setupStage(STAGE, setupScene());
        private Scene setupScene() {
            input1 = new TestInput(1);
            input2 = new TestInput(2);
            input3 = new TestInput(3);
            input4 = new TextField();
            input5 = new TextField();
            input6 = new TextField();
            GridPane pane = new GridPane();
            pane.add(input1, 1, 1);
            pane.add(input2, 1, 2);
            pane.add(input3, 1, 3);
            pane.add(input4, 2, 1);
            pane.add(input5, 2, 2);
            pane.add(input6, 2, 3);
            scene = new Scene(pane);
            return scene;
        private void setupStage(final Stage STAGE, final Scene SCENE) {
            STAGE.setTitle("Test");
            STAGE.setScene(SCENE);
            STAGE.show();
        public static void main(String[] args) {
            launch(args);
    The test app shows three custom controls on the left column and three standard textfields on the right column. If you press TAB you will see what i mean...

  • Non-static method close() cannot be referenced from a static context

    Friends,
    I am having a little help with some static and not static issues.
    I created a JMenuBar, it's in the file: SlideViewMenu.java
    One of the operations is File->Close and another is File->Exit.
    The listener is in the SlideViewMenu.java file. The listener needs to reference two non-static methods within SlideView.java.
    Here's some of the code:
    SlideViewMenu.java
    public class SlideViewMenu {
        public JMenuBar createMenuBar() {
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
         // All the menu stuff works fine and is taken care of here.
       // Listener for Menu
       class MenuActionListener implements ActionListener {
         public void actionPerformed (ActionEvent actionEvent) {
              String selection = (String)actionEvent.getActionCommand();
             if (selection.equals("Close"))
              SlideViewFrame.close();
             else  SlideViewFrame.exit();
    }SlideView.java
    // Driver class
    public class SlideView {
         public static void main(String[] args) {
              ExitableJFrame f = new SlideViewFrame("SlideView");
                    // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame {
            // some things here, work fine.
         private SlideViewMenu menuBar = new SlideViewMenu();
         public SlideViewFrame(String title) {
         // Set title, layout, and background color
         super(title);
         setJMenuBar(menuBar.createMenuBar());
            // Stuff here works fine.
         // Handles doing stuff once the file has been selected
         public void setFileName(File fullFileName, String simpleName) {
            // Stuff here works fine.     
         // File->Close. clean up everything.
         public void close() {
              setTitle("SlideView");
              textArea.setText("");
              scrollBar.setVisible(false);
              textArea.setVisible(false);
              statsPanel.setVisible(false);
         // File->Exit.     
         public void exit() {
              System.exit(0);
    }The error I'm getting is:
    SlideViewMenu.java:50: non-static method close() cannot be referenced from a static context
    I don't get it?
    Thanks for all help.

    Making close() and exit() static would not solve the problem because close() requires access to nonstatic member variables/functions.
    Fortunately, that is not necessary. The real reason you are having a problem is that you don't have any way in your listener to access the main frame window, which is what the listener trying to control. You made a stab at gaining access by prefixing the function with the class name, but, as the compiler has informed you, that is only valid for static methods. If you think about it, you should see the sense in that, because, what if you had a number of frames and you executed className.close()? Which one would you close? All of them?
    Fortunately, there is an easy way out that ties the listener to the frame.
    SlideViewMenu.java:public class SlideViewMenu
      // Here's where we keep the link to the parent.
      private SlideViewFrame parentFrame;
      // Here's where we link to the parent.
      public JMenuBar createMenuBar(SlideViewFrame linkParentFrame)
        parentFrame = linkParentFrame;
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
        // All the menu stuff works fine and is taken care of here.
      // Listener for Menu --- It is assumed that this is a non-static nested
      // class in SlideViewMenu. All SlideViewMenu variables are accessible from
      // here. If this is not the case, simply add a similar member variable
      //  to this class, initialize it with a constructor parameter, and
      // pass the SlideViewMenu parentFrame when the listener is
      // constructed.
      class MenuActionListener implements ActionListener
        public void actionPerformed (ActionEvent actionEvent)
          String selection = (String)actionEvent.getActionCommand();
          // Use parentFrame instead of class name.
          if (selection.equals("Close"))
              parentFrame.close();
            else
              parentFrame.exit();
    }SlideView.java// Driver class
    public class SlideView
      public static void main(String[] args)
        ExitableJFrame f = new SlideViewFrame("SlideView");
        // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame
      // some things here, work fine.
      private SlideViewMenu menuBar = new SlideViewMenu();
      public SlideViewFrame(String title)
        // Set title, layout, and background color
        super(title);
        //Here's where we set up the link.
        setJMenuBar(menuBar.createMenuBar(this));
      // Stuff here works fine.
      // Handles doing stuff once the file has been selected
      public void setFileName(File fullFileName, String simpleName)
        // Stuff here works fine.     
      // File->Close. clean up everything.
      public void close()
        setTitle("SlideView");
        textArea.setText("");
        scrollBar.setVisible(false);
        textArea.setVisible(false);
        statsPanel.setVisible(false);
      // File->Exit.
      public void exit()
        System.exit(0);
    }

  • JUnit : How to Mock Static Method

    Hi,
    I was using EasyMock to write Junit for the methods of the class.
    The Limitation of this library is that only Interfaces can be mocked without any much effort and behavior can be set according to our needs.
    Since, now we need to mock even normal classes, I got mocuer library from net and this too is easy to implement. The problem / limitation is that, I cant mock static methods of a class.
    Is there is any workaround / library so that even static methods can be mocked??.
    Advance thanks.

    Since you would like to mock the static method, it is not part of the class you'd like to test, I assume. The class you do want to test is supposedly under your control and contains the static invocation. I'd suggest to refactor the use of the static invocation in the class being tested.
    I see two approaches:
    1. wrap the static method call in an instance of newly created service class.
       public class ServiceMethodWrapperImpl implements ServiceMethodWrapper {
           public int serviceCall(String arg) {
             return OtherClass.staticMethod(arg);
       }and then mock the ServiceMethoWrapper interface for testing
    2. wrap the static call in a protected method of the class under test. In you test case, test a derived class in which you override the method that calls the service to use a mock:
       public class TestedClass {
         protected int callStaticMethod(String arg) {
             return OtherClass.staticMethod(arg);
         public void something() {
             // replaced OtherClass.staticMethod by
             if (callStaticMethod("Sun") == 3) {
       public void testSomethingForTheClass() {
          TestedClass instance = new TestedClass() {
               protected int callStaticMethod(String arg) {
                    return 3; // mocked answer
       }

  • TOP of PAGE  using ABAP oo with single CUSTOM CONTROL

    Can anybody please tell me how to handle TOP_OF_PAGE using ABAP OBJECTS with a SINGLE CUSTOM CONTROL and not with  SPLIT CONTAINER(i.e. using single CL_GUI_CUSTOM_CONTAINER and single grid CL_GUI_ALV_GRID  ). Is it possible if so Please help me out?

    Hi Ravi,
    Here is my code. i didn't handle the top_of_page event yet but created a method to handle.
    REPORT  ZSATEESH_ALV_CONTAINER MESSAGE-ID ZZ
                      LINE-SIZE 150 NO STANDARD PAGE HEADING.
    PROGRAM id        :  ZSATEESH_ALV_CONTAINER                         *
    Title             : Sales document report                           *
    Author            : Sateesh                                         *
    Date              :                                                 *
    CR#               :                                                 *
    Dev Initiative    :
    Description       :ALV GRID/LIST Report which displays the sales
                          document header data using ABAP Objects.
                              Modification Log
    Corr. no        date       programmer        description
                    TYPES Declaration
    *--Type for the Header Sales data
    TYPES: BEGIN OF TY_VBAK ,
            INDICAT LIKE ICON-ID,               " Icon
            VBELN   LIKE VBAK-VBELN,            " Sales Document
            AUDAT   LIKE VBAK-AUDAT,            " Document date
            VBTYP   LIKE VBAK-VBTYP,            " SD document category
            AUART   LIKE VBAK-AUART,            " Sales Document Type
            AUGRU   LIKE VBAK-AUGRU,            " Order reason
            NETWR   LIKE VBAK-NETWR,            " Net Value
            WAERK   LIKE VBAK-WAERK,            " SD document currency
         END OF TY_VBAK.
                    DATA Declaration
    *--Tableto hold the header sales data
    DATA: TB_VBAK  TYPE  STANDARD TABLE OF TY_VBAK.
    *--Table to hold the Icons
    DATA: BEGIN OF TB_ICON OCCURS 0,
            ID   TYPE ICON-ID,                  " Icon
            NAME TYPE ICON-NAME,                " Name of an Icon
          END OF TB_ICON.
    *--Declaration of ALV Grid Tables
    DATA: TB_FDCAT         TYPE LVC_T_FCAT,     " Fieldcatalog
          TB_SORT          TYPE LVC_T_SORT.     " Sorting
    DATA: OK_CODE          LIKE SY-UCOMM.       " sy-ucomm
    *--Reference variables for container and grid control.
    DATA: CUSTOM_CONTAINER TYPE REF TO CL_GUI_CUSTOM_CONTAINER,
                                                " Container reference
          OBJ_ALV_GRID     TYPE REF TO CL_GUI_ALV_GRID.
    " Alv Grid reference
                      S T R U C T U R E S
    DATA: X_FDCAT          TYPE LVC_S_FCAT,     " Fieldcatalog
          X_LAYOUT         TYPE LVC_S_LAYO,     " layout
          X_SORT           TYPE LVC_S_SORT,     " Sorting
          X_VBAK           TYPE TY_VBAK,        " sales header stucture
          X_ICON           LIKE TB_ICON.        " icons structure
                      C O N S T A N T S
    *--Declaration of Constants
    CONSTANTS :
                C_GREEN(40)    TYPE  C VALUE 'ICON_GREEN_LIGHT',
                C_RED(40)      TYPE  C VALUE 'ICON_RED_LIGHT',
                C_YELLOW(40)   TYPE  C VALUE 'ICON_YELLOW_LIGHT',
                C_X            TYPE  C VALUE 'X'.      " Flag
                      SELECTION SCREEN
    *--Block 1.
    SELECTION-SCREEN : BEGIN OF BLOCK B1 WITH FRAME TITLE TEXT-001.
    PARAMETER: P_AUDAT LIKE VBAK-AUDAT
                       DEFAULT '20050101'(003).    " doc date.
    SELECTION-SCREEN: END OF BLOCK B1.
    *--bLOCK 2.
    SELECTION-SCREEN : BEGIN OF BLOCK B2 WITH FRAME TITLE TEXT-002.
    PARAMETER :P_ALVDIS AS CHECKBOX.              " For List/Grid
    SELECTION-SCREEN : END OF BLOCK B2.
          Class LC_VBAK  definition
    CLASS  LC_VBAK DEFINITION.
      PUBLIC SECTION.
        METHODS: VBAK_POPULATE,                 " sales header population
                 ICON_POPULATE,                 " Icons population
                 FINAL_POPULATE,                " Final ALV population
                 DISPLAY,                      " Displaying ALV
                 TOP_OF_PAGE FOR EVENT TOP_OF_PAGE OF CL_GUI_ALV_GRID
                                               IMPORTING E_DYNDOC_ID.
    ENDCLASS.                    "LC_VBAK DEFINITION
          Class LC_VBAK IMPLEMENTATION
    CLASS LC_VBAK IMPLEMENTATION.
      METHOD VBAK_POPULATE.
    *-- selecting from VBAK
        SELECT VBELN
                AUDAT
                VBTYP
                AUART
                AUGRU
                NETWR
                WAERK
                INTO   CORRESPONDING FIELDS OF TABLE TB_VBAK
                FROM VBAK
                WHERE AUDAT > P_AUDAT AND
                NETWR  > 0.
        IF SY-SUBRC <> 0.
          SORT TB_VBAK  BY AUART VBTYP WAERK .
        ENDIF.
      ENDMETHOD .                    "VBAK_POPULATE
      METHOD ICON_POPULATE.
    *--selecting from ICON table
        SELECT ID
               NAME
               INTO TABLE TB_ICON
               FROM ICON.
        IF SY-SUBRC = 0.
          SORT TB_ICON BY NAME .
        ENDIF.
      ENDMETHOD .                    "ICON_POPULATE
      METHOD FINAL_POPULATE.
    *--looping through VBAK table into the work area
        LOOP AT TB_VBAK INTO X_VBAK .
          IF X_VBAK-NETWR <= 10.
    *--Reading the ICON table into work area comparing field NAME
            READ TABLE TB_ICON INTO X_ICON WITH KEY NAME = C_GREEN
                                                     BINARY SEARCH.
            IF SY-SUBRC = 0.
              X_VBAK-INDICAT =  X_ICON-ID.
    *--modifying the TB_VBAK table
              MODIFY TB_VBAK FROM X_VBAK.
            ENDIF.
          ELSEIF X_VBAK-NETWR > 10 AND X_VBAK-NETWR < 100.
    *--Reading the ICON table into work area comparing field NAME
            READ TABLE TB_ICON INTO X_ICON WITH KEY NAME = C_YELLOW
                                                     BINARY SEARCH.
            IF SY-SUBRC = 0.
              X_VBAK-INDICAT =  X_ICON-ID.
    *--modifying the TB_VBAK table
              MODIFY TB_VBAK FROM X_VBAK.
            ENDIF.
          ELSEIF X_VBAK-NETWR >= 100.
    *--Reading the ICON table into work area comparing field NAME
            READ TABLE TB_ICON INTO X_ICON WITH KEY NAME = C_RED
                                                     BINARY SEARCH.
            IF SY-SUBRC = 0.
              X_VBAK-INDICAT =  X_ICON-ID.
    *--modifying the TB_VBAK table
              MODIFY TB_VBAK FROM X_VBAK.
            ENDIF.
          ENDIF.
        ENDLOOP.
      ENDMETHOD.                    "FINAL_POPULATE
          METHOD top_of_page                                            *
      METHOD TOP_OF_PAGE.
        PERFORM EVENT_TOP_OF_PAGE USING E_DYNDOC_ID.
      ENDMETHOD.                    "top_of_page
      METHOD DISPLAY.
    *--Building fieldcatalog table
        PERFORM FIELDCATLOG.
    *--FOr making the Layout settings
        PERFORM LAYOUT.
    *--For sorting the fields
        PERFORM SORTING.
    *--perform for displaying the ALV
        PERFORM ALV_GRID_DISPLAY.
      ENDMETHOD.                    "DISPLAY
    ENDCLASS.                    "LC_VBAK IMPLEMENTATION
    *&      Form  FIELDCATLOG
         Building the FIELDCATALOG
    FORM FIELDCATLOG .
      CLEAR: X_FDCAT,TB_FDCAT[].
      X_FDCAT-ROW_POS   = 1.
      X_FDCAT-COL_POS   = 1.
      X_FDCAT-FIELDNAME = 'INDICAT'(004) .
      X_FDCAT-TABNAME   = 'TB_VBAK'(005).
      X_FDCAT-SCRTEXT_L = 'STATUS_INDICATOR'(006).
      APPEND X_FDCAT TO TB_FDCAT.
      X_FDCAT-ROW_POS   = 1.
      X_FDCAT-COL_POS   = 2.
      X_FDCAT-FIELDNAME = 'VBELN'(007) .
      X_FDCAT-TABNAME   = 'TB_VBAK'(005).
      X_FDCAT-SCRTEXT_L = 'SALES DOC'(008).
      APPEND X_FDCAT TO TB_FDCAT.
      X_FDCAT-ROW_POS   = 1.
      X_FDCAT-COL_POS   = 3.
      X_FDCAT-FIELDNAME = 'AUDAT'(009) .
      X_FDCAT-TABNAME   = 'TB_VBAK'.
      X_FDCAT-SCRTEXT_L = 'DOC DATE'(010).
      APPEND X_FDCAT TO TB_FDCAT.
      X_FDCAT-ROW_POS   = 1.
      X_FDCAT-COL_POS   = 4.
      X_FDCAT-FIELDNAME = 'VBTYP'(011) .
      X_FDCAT-TABNAME   = 'TB_VBAK'.
      X_FDCAT-SCRTEXT_L = 'SALES CATEGORY'(012).
      APPEND X_FDCAT TO TB_FDCAT.
      X_FDCAT-ROW_POS   = 1.
      X_FDCAT-COL_POS   = 5.
      X_FDCAT-FIELDNAME = 'AUART'(013) .
      X_FDCAT-TABNAME   = 'TB_VBAK'.
      X_FDCAT-SCRTEXT_L = 'DOC TYPE'(014).
      APPEND X_FDCAT TO TB_FDCAT.
      X_FDCAT-ROW_POS   = 1.
      X_FDCAT-COL_POS   = 6.
      X_FDCAT-FIELDNAME = 'AUGRU'(015) .
      X_FDCAT-TABNAME   = 'TB_VBAK'.
      X_FDCAT-SCRTEXT_L = 'REASON'(016).
      APPEND X_FDCAT TO TB_FDCAT.
      X_FDCAT-ROW_POS   = 1.
      X_FDCAT-COL_POS   = 7.
      X_FDCAT-FIELDNAME = 'NETWR'(017) .
      X_FDCAT-TABNAME   = 'TB_VBAK'.
      X_FDCAT-SCRTEXT_L = 'NET VALUE'(018).
      X_FDCAT-DO_SUM   = C_X.
      APPEND X_FDCAT TO TB_FDCAT.
      X_FDCAT-ROW_POS   = 1.
      X_FDCAT-COL_POS   = 8.
      X_FDCAT-FIELDNAME = 'WAERK'(019) .
      X_FDCAT-TABNAME   = 'TB_VBAK'.
      X_FDCAT-SCRTEXT_L = 'UNIT'(020).
      APPEND X_FDCAT TO TB_FDCAT.
    ENDFORM.                    " FIELDCATLOG
    *&      Module  STATUS_0007  OUTPUT
          module for setting the pf status
    MODULE STATUS_0007 OUTPUT.
      SET PF-STATUS 'ZSTATUS'.
    SET TITLEBAR 'xxx'.
    ENDMODULE.                 " STATUS_0007  OUTPUT
    *&      Module  USER_COMMAND_0007  INPUT
          module  for handling the user commands
    MODULE USER_COMMAND_0007 INPUT.
      OK_CODE = SY-UCOMM.
      CASE OK_CODE.
        WHEN 'BACK'.
          LEAVE TO SCREEN 0.
        WHEN 'CANCEL'.
          LEAVE TO SCREEN 0.
        WHEN 'EXIT'.
          LEAVE TO SCREEN 0.
      ENDCASE.
    ENDMODULE.                 " USER_COMMAND_0007  INPUT
    *&      Form  LAYOUT
          ALV Layout settings
    FORM LAYOUT .
      CLEAR X_LAYOUT.
    *-- making Layout settings
      X_LAYOUT-GRID_TITLE = 'Sales Header Document'(021).
      X_LAYOUT-ZEBRA      = C_X.
      IF P_ALVDIS =  C_X.
        X_LAYOUT-NO_HGRIDLN = C_X.
        X_LAYOUT-NO_VGRIDLN = C_X.
      ENDIF.
    ENDFORM.                    " LAYOUT
    *&      Form  SORTING
          sub routine for sorting criteria
    FORM SORTING .
      CLEAR X_SORT.
      X_SORT-SPOS = '1'(022).
      X_SORT-FIELDNAME = 'AUART'.
      X_SORT-UP        = C_X.
      APPEND X_SORT TO TB_SORT.
      CLEAR X_SORT.
      X_SORT-SPOS = '2'(023).
      X_SORT-FIELDNAME = 'VBTYP'.
      X_SORT-UP        = C_X.
      APPEND X_SORT TO TB_SORT.
      CLEAR X_SORT.
      X_SORT-SPOS = '3'(024).
      X_SORT-FIELDNAME = 'WAERK'.
      X_SORT-UP        = C_X.
      X_SORT-SUBTOT    = C_X.
      APPEND X_SORT TO TB_SORT.
    ENDFORM.                    " SORTING
    *&      Form  CREATE_CONTAINER_OBJECT
          subroutine to create object of container
    FORM CREATE_CONTAINER_OBJECT .
      CREATE OBJECT CUSTOM_CONTAINER
        EXPORTING
          CONTAINER_NAME              = 'CUST_CONTROL'(025)
        EXCEPTIONS
          CNTL_ERROR                  = 1
          CNTL_SYSTEM_ERROR           = 2
          CREATE_ERROR                = 3
          LIFETIME_ERROR              = 4
          LIFETIME_DYNPRO_DYNPRO_LINK = 5
          OTHERS                      = 6
      IF SY-SUBRC <> 0.
        MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                   WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    ENDFORM.                    " CREATE_CONTAINER_OBJECT
    *&      Form  CREATE_ALV_GRID_OBJECT
          subroutine to create object of ALV GRID
    FORM CREATE_ALV_GRID_OBJECT .
      CREATE OBJECT OBJ_ALV_GRID
        EXPORTING
          I_PARENT          = CUSTOM_CONTAINER
        EXCEPTIONS
          ERROR_CNTL_CREATE = 1
          ERROR_CNTL_INIT   = 2
          ERROR_CNTL_LINK   = 3
          ERROR_DP_CREATE   = 4
          OTHERS            = 5
      IF SY-SUBRC <> 0.
        MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                   WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    ENDFORM.                    " CREATE_ALV_GRID_OBJECT
    *&      Form  ALV_GRID_DISPLAY
          subroutine to call method for displaying the ALV GRID
    FORM ALV_GRID_DISPLAY .
      CALL METHOD OBJ_ALV_GRID->SET_TABLE_FOR_FIRST_DISPLAY
        EXPORTING
          IS_LAYOUT                     = X_LAYOUT
        CHANGING
          IT_OUTTAB                     = TB_VBAK
          IT_FIELDCATALOG               = TB_FDCAT
          IT_SORT                       = TB_SORT
        EXCEPTIONS
          INVALID_PARAMETER_COMBINATION = 1
          PROGRAM_ERROR                 = 2
          TOO_MANY_LINES                = 3
          OTHERS                        = 4.
      IF SY-SUBRC <> 0.
        MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                   WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      CALL SCREEN 0007.
    ENDFORM.                    " ALV_GRID_DISPLAY
                    START OF SELECTION
    START-OF-SELECTION.
    *--Creating a reference variable for the class LC_VBAK
      DATA : OBJ1 TYPE REF TO LC_VBAK.
    *--Creating a container object
      PERFORM CREATE_CONTAINER_OBJECT.
    *--Creating a ALV GRID control object
      PERFORM CREATE_ALV_GRID_OBJECT.
    *--Creating a object of class LC_VBAK
      CREATE OBJECT OBJ1.
    *--calling vbak population method
      CALL METHOD OBJ1->VBAK_POPULATE.
    *--calling icon population method
      CALL METHOD OBJ1->ICON_POPULATE.
    *--calling fianl table population method
      CALL METHOD OBJ1->FINAL_POPULATE.
    *--calling final  method for display
      CALL METHOD OBJ1->DISPLAY.
    *&      Form  EVENT_TOP_OF_PAGE
          text
         -->P_E_DYNDOC_ID  text
    FORM EVENT_TOP_OF_PAGE  USING    P_E_DYNDOC_ID TYPE REF TO
                                                      CL_DD_DOCUMENT.
    ENDFORM.                    " EVENT_TOP_OF_PAGE

  • How to save Custom control records ?

    Hi guru ,
    1. How to save Custom control records module pool program ?
    I wrote multiple lines of record in custom control
    Who to save that records ?
    thanking you.
    Regards,
    Subash.

    REPORT  ZCUSTOMC.
    CLASS event_handler DEFINITION.
      PUBLIC SECTION.
        METHODS: handle_f1 FOR EVENT f1 OF cl_gui_textedit
                 IMPORTING sender,
                 handle_f4 FOR EVENT f4 OF cl_gui_textedit
                 IMPORTING sender.
    ENDCLASS.
    DATA: ok_code LIKE sy-ucomm,
          save_ok LIKE sy-ucomm.
    DATA: init,
          container TYPE REF TO cl_gui_custom_container,
          editor    TYPE REF TO cl_gui_textedit.
    DATA: event_tab TYPE cntl_simple_events,
          event     TYPE cntl_simple_event.
    DATA: line(256) TYPE c,
          text_tab LIKE STANDARD TABLE OF line,
          field LIKE line.
    DATA handle TYPE REF TO event_handler.
    START-OF-SELECTION.
      line = 'First line in TextEditControl'.
      APPEND line TO text_tab.
      line = '----
      APPEND line TO text_tab.
      line = '...'.
      APPEND line TO text_tab.
      CALL SCREEN 100.
    MODULE status_0100 OUTPUT.
      SET PF-STATUS 'SCREEN_100'.
      IF init is initial.
        init = 'X'.
        CREATE OBJECT: container EXPORTING container_name = 'TEXTEDIT',
                       editor    EXPORTING parent = container,
                       handle.
        event-eventid = cl_gui_textedit=>event_f1.
        event-appl_event = ' '.                     "system event
        APPEND event TO event_tab.
        event-eventid = cl_gui_textedit=>event_f4.
        event-appl_event = 'X'.                     "application event
        APPEND event TO event_tab.
        CALL METHOD: editor->set_registered_events
                     EXPORTING events = event_tab.
        SET HANDLER handle->handle_f1
                    handle->handle_f4 FOR editor.
      ENDIF.
      CALL METHOD editor->set_text_as_stream EXPORTING text = text_tab.
    ENDMODULE.
    MODULE cancel INPUT.
      LEAVE PROGRAM.
    ENDMODULE.
    MODULE user_command_0100 INPUT.
      save_ok = ok_code.
      CLEAR ok_code.
      CASE save_ok.
        WHEN 'INSERT'.
          CALL METHOD editor->get_text_as_stream IMPORTING text = text_tab.
        WHEN 'F1'.
          MESSAGE i888(sabapdocu) WITH text-001.
        WHEN OTHERS.
          MESSAGE i888(sabapdocu) WITH text-002.
          CALL METHOD cl_gui_cfw=>dispatch.      "for application events
          MESSAGE i888(sabapdocu) WITH text-003.
      ENDCASE.
      SET SCREEN 100.
    ENDMODULE.
    CLASS event_handler IMPLEMENTATION.
      METHOD handle_f1.
        DATA row TYPE i.
        MESSAGE i888(sabapdocu) WITH text-004.
        CALL METHOD sender->get_selection_pos
             IMPORTING from_line = row.
        CALL METHOD sender->get_line_text
             EXPORTING line_number = row
             IMPORTING text = field.
        CALL METHOD cl_gui_cfw=>set_new_ok_code   "raise PAI for
             EXPORTING new_code = 'F1'.           "system events
        CALL METHOD cl_gui_cfw=>flush.
      ENDMETHOD.
      METHOD handle_f4.
        DATA row TYPE i.
        MESSAGE i888(sabapdocu) WITH text-005.
        CALL METHOD sender->get_selection_pos
             IMPORTING from_line = row.
        CALL METHOD sender->get_line_text
             EXPORTING line_number = row
             IMPORTING text = field.
        CALL METHOD cl_gui_cfw=>flush.
      ENDMETHOD.
    ENDCLASS.
    aniruddh

  • JUNIT : how to call static methods through mock objects.

    Hi,
    I am writing unit test cases for an action class. The method which i want to test calls one static method of a helper class. Though I create mock of that helper class, but I am not able to call the static methods through the mock object as the methods are static. So the control of my test case goes to that static method and again that static method calls two or more different static methods. So by this I am testing the entire flow instead of testing the unit of code of the action class. So it can't be called as unit test ?
    Can any one suggest me that how can I call static methods through mock objects.

    The OP's problem is that the object under test calls a static method of a helper class, for which he wants to provide a mock class
    Hence, he must break the code under test to call the mock class instead of the regular helper class (because static methods are not polymorphic)
    that wouldn't have happened if this helper class had been coded to interfaces rather than static methods
    instead of :
    public class Helper() {
        public static void getSomeHelp();
    public class MockHelper() {
        public static void getSomeHelp();
    }do :
    public class ClassUnderTest {
        private Helper helper;
        public void methodUnderTest() {  // unchanged
            helper.getSomeHelp();
    public interface Helper {
        public void getSomeHelp();
    public class HelperImpl implements Helper {
        public void getSomeHelp() {
            // actual implementation
    public class MockHelper implements Helper {
        public void getSomeHelp() {
            // mock implementation
    }

  • Custom Control Help: Draw a line and output start and end points

    I'm looking to find or make a custom control (or simple subVI) that will appear as a 100x100 unit grid and allow me to draw a line from one point to another on that grid. It will then output the (x,y) of the starting and end point of that line on the grid.  Any help or ideas?
    Thanks,
    Steve
    LabVIEW 2009 SP1
    Solved!
    Go to Solution.

    What you basically want is a loop with an event structure where you process Mouse Down, Move and Up events for your controls. There are any number of ways of implementing something like this, but this one will probably be the simplest:
    Use a multicolumn listbox or a table for your grid. Hide the scrollbars and headers.
    You can use the ActiveCell property with -2,-2 to select all cells. You can then use the cell size property to set the exact size of the cell.
    Next, you put a picture control on top of the table and color its background transparent so that the table shows through. You use property node to make sure the two are aligned to exactly the same spot and size.
    You use the mouse events on the picture control to detect the clicks and moves.
    You use the table's Point to Row Column method to translate the event's position data to a cell.
    You use the picture control VIs to draw the line on the picture based on that data.
    You can even color the selected cells in the table using the table properties.
    If you want to simplify things somewhat, you can also use the timeout event instead of the Mouse Move event to draw the line, but then you'll need to keep the timeout value in a shift register and reset it to -1 (no timeout) when the Mouse Up event happens.
    I would also suggest processing Mouse Enter and Leave events to change the cursor and cancel if the user leaves in the middle of dragging.
    Try to take over the world!

  • Equivalent to [i]this[/i] and [i]getClass()[/i] inside a static method

    All business objects of my application (Customer, Car, etc.) extend a root class (RootObject) which performs retrieving operations. Such operations are delegated to a static Loader that calls the respective method according to the type of the business object (loadAllCustomers for Customers, loadAllCars for Cars, etc). The problem is that I am unable to know which class is calling RootObject.loadAll() (a Customer or a Car) because both this and getClass() cannot be used inside static methods.
    So, my question is : how can I determine which class is extending RootObject from inside its static loadAll() method ? It is either a Customer or a Car, but I cannot figure out how to get such information.
    public class Customer extends RootObject { /*...*/ }
    public class Car extends RootObject { /*...*/ }
    public class RootObject {
      protected static Loader loader = new Loader();
      public static RootObject[] loadAll() {
        return loader.loadAll(getClass());  // does not compile
    public class Loader {
      public RootObject[] loadAll(Class classe) {
        if (classe == Customer.class) return loadAllCustomers();
        if (classe == Car.class) return loadAllCars();
        return null;
    public static void main(String args[]) {
      Car cars[] = (Car[]) Car.loadAll();
      System.out.println("number of cars = " + cars.length);
    }Thank you.

    Thank you guys.
    We are trying to simulate an object-oriented database
    on top of a relational one (or a file, or whatever).Sounds like you really want ORM, like Hibernate or TopLink.
    Then, to retrieve a given car, we could be able to do
    Car car = new Car();
    car.setId("C1");
    car.load();Instead, to retrieve a list of cars, I think it is
    more intuitive to use a class method instead of an
    instance one because we'll return a list, not a
    single object :
    Car cars[] = (Car[]) Car.loadAll();instead of
    Car car = new Car();
    Car cars[] = (Car[]) car.loadAll();  // a little odd,
    isn't it ?Then, it is a design choice to make loadAll()
    a static method.Sounds to me like you're trying to create objects that know how to persist themselves. That's one way to do it.
    Another would be to separate the persistence code into a separate, interface-based class called a Data Access Object (DAO) or Repository that would handle this for you:
    public interface CarRepository
        List<Car> find();
        Car find(Long id);
        void save(Car c);
        void update(Car c);
        delete(Car c);
    }Now you can have different implementations for this interface, depending on how to wanted to tackle persistence. If it happens to be relational, all the SQL code is hidden from clients in the interface implementation.
    %

Maybe you are looking for

  • Connect to car, IPOD Classic pauses and will not play

    Hello to all, First of all I am not very good at computer stuff. I used my IPOD Classic for about three months with a car kit and all was fine. All of a sudden it stopped playing. I figured out that the IPOD pauses when it is connected to the wire fr

  • SBS 2011 GPO for changing the default save location for Word/Excel 2013 not working

    So this is a strange one. I've got an SBS 2011 server that's the only domain controller in the org. I've created a GPO to change the default save location for Excel 2013 and Word 2013 using the Office 2013 ADMX files which were installed to the Polic

  • Compatibility of Browsers with Netweaver CE 7.2

    Hi Experts,    We are using SAP Netweaver CE 7.2 and are trying the view a WebDynpro Application on the Mobile Device.   We have used the below devices but are getting some error message when using BarCode Reader and FunctionKey Controls. The Devices

  • HT4759 How do I transfer my contacts back from my Icloud account to my Iphone

    All my contacts were deleted on my Iphone.  I have them stored on my Icloud account.  When I sign onto my Icloud account they are there but I do NOT know how to 'sync' them from my PC to my IPhone.  How do I do this?

  • Sound application

    Hello. I sometimes get lost in the sound applications (games), with it all at once, and all the other sounds on the spot. How can I fix it?