Re: adding event handling to shapes

Hi
I am trying to make the shapes clickable. I have tried to implement the MouseInputAdapter. I am not sure if I am doing it right. Hope some one will help me in this matter. I ahve attached both shape class and class implementing MouseInput adapter. The shape is called from yet another class that extends canvas.
package Drawing2d;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.event.MouseInputAdapter;
import save.pointList;
* @author venkat
public class Line extends Sketch implements MouseListener,MouseMotionListener{
    //public Point2D[][] lineEndPoints = new Point2D[10][2];
int i = 0;
public pointList plist = new pointList();  
public List lineList;
public Graphics2D g2d;
public Line(Graphics2D g2,int x0, int y0, int x1, int y1){
    lineList = new ArrayList();
    g2.setColor(Color.WHITE);
    g2d = g2;
    float[] dashPattern = { 0,0,0,0 };
    g2.setStroke(new BasicStroke(1));
    AffineTransform at = AffineTransform.getTranslateInstance(Sketch.HEIGHT/2,Sketch.WIDTH/2);
    Line2D.Double line = new Line2D.Double((double)x0,(double)y0,(double)x1,(double)y1);
    g2.draw(at.createTransformedShape(line));
    lineList.add(this);
    Point2D newLoc = at.transform(line.getBounds().getLocation(), null);
    Point p1 =  new Point(g2 ,x0, y0);
    Point p2 =  new Point(g2 ,x1, y1);
    plist.add(x0, y0);
    plist.add(x1, y1);
    LineSelect lineS = new LineSelect(this);
    addMouseListener(lineS);
    addMouseMotionListener(lineS);
* LineSelect.java
* Created on 11-Dec-2007, 16:07:50
* To change this template, choose Tools | Templates
* and open the template in the editor.
package Drawing2d;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.event.MouseInputAdapter;
* @author venkat
class LineSelect extends MouseInputAdapter{
    Line selectedLine;
    Line line2d;
    Point2D.Double p;
    public LineSelect(Line line){
        selectedLine = line;
        p = new Point2D.Double();
    public void mouseClicked(MouseEvent e) {
        java.awt.Point p = e.getPoint();      
    for(int j = 0; j < selectedLine.lineList.size(); j++)
            line2d = (Line)selectedLine.lineList.get(j);
            if(line2d.contains(p))
                selectedLine.g2d.setColor(Color.MAGENTA);              
    public void mouseDragged(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public void mouseMoved(MouseEvent e) {
    public void mousePressed(MouseEvent e) {
    public void mouseReleased(MouseEvent e) {
}

pushinglimits wrote:
Hi
I am trying to make the shapes clickable. I have tried to implement the MouseInputAdapter. I am not sure if I am doing it right. Hope some one will help me in this matter. I ahve attached both shape class and class implementing MouseInput adapter. The shape is called from yet another class that extends canvas.
package Drawing2d;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.event.MouseInputAdapter;
import save.pointList;
* @author venkat
public class Line extends Sketch implements MouseListener,MouseMotionListener{
//public Point2D[][] lineEndPoints = new Point2D[10][2];
int i = 0;
public pointList plist = new pointList();  
public List lineList;
public Graphics2D g2d;
public Line(Graphics2D g2,int x0, int y0, int x1, int y1){
lineList = new ArrayList();
g2.setColor(Color.WHITE);
g2d = g2;
float[] dashPattern = { 0,0,0,0 };
g2.setStroke(new BasicStroke(1));
AffineTransform at = AffineTransform.getTranslateInstance(Sketch.HEIGHT/2,Sketch.WIDTH/2);
Line2D.Double line = new Line2D.Double((double)x0,(double)y0,(double)x1,(double)y1);
g2.draw(at.createTransformedShape(line));
lineList.add(this);
Point2D newLoc = at.transform(line.getBounds().getLocation(), null);
Point p1 =  new Point(g2 ,x0, y0);
Point p2 =  new Point(g2 ,x1, y1);
plist.add(x0, y0);
plist.add(x1, y1);
LineSelect lineS = new LineSelect(this);
addMouseListener(lineS);
addMouseMotionListener(lineS);
* LineSelect.java
* Created on 11-Dec-2007, 16:07:50
* To change this template, choose Tools | Templates
* and open the template in the editor.
package Drawing2d;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.event.MouseInputAdapter;
* @author venkat
class LineSelect extends MouseInputAdapter{
Line selectedLine;
Line line2d;
Point2D.Double p;
public LineSelect(Line line){
selectedLine = line;
p = new Point2D.Double();
public void mouseClicked(MouseEvent e) {
java.awt.Point p = e.getPoint();      
for(int j = 0; j < selectedLine.lineList.size(); j++)
line2d = (Line)selectedLine.lineList.get(j);
if(line2d.contains(p))
selectedLine.g2d.setColor(Color.MAGENTA);              
public void mouseDragged(MouseEvent e) {
public void mouseEntered(MouseEvent e) {
public void mouseExited(MouseEvent e) {
public void mouseMoved(MouseEvent e) {
public void mousePressed(MouseEvent e) {
public void mouseReleased(MouseEvent e) {
Hi I appreciate if anybody attempted to answer. I got arounf th problem. here is how
* LineSelect.java
* Created on 11-Dec-2007, 16:07:50
* To change this template, choose Tools | Templates
* and open the template in the editor.
package Drawing2d;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.MouseEvent;
import java.awt.geom.PathIterator;
import java.util.ArrayList;
import javax.swing.event.MouseInputAdapter;
* @author venkat
class LineSelect extends MouseInputAdapter{
    Line selectedLine;
    Line line2d;
    java.awt.Point p;
    Sketch sk;
    Circle circle;
    Shape line;
    Shape shape;
    private Stroke stroke;
    public LineSelect(Sketch s){
        sk = s;
    public void mouseClicked(MouseEvent e) {
        p = e.getPoint();
        PathIterator pi;       
        boolean haveSelection = false;
        ArrayList list = sk.circleList;
        for(int j = 0; j < list.size(); j++)
            circle = (Circle)list.get(j);
            System.out.print(circle.intersects(p.x, p.y, 1, 1));
            pi = circle.getPathIterator(null);
            double[] coords = new double[6];           
            if(circle.intersects(p.x, p.y, 1, 1))
               System.out.print("reached here");
                while(!pi.isDone()){
                pi.currentSegment(coords);
                System.out.print(coords);
                pi.next();
        list = sk.lineList;       
        if(!sk.p.equals("n") && list != null){
            for(int j = 0; j < list.size(); j++)       
           // line = (Line)list.get(j);           
            line = stroke.createStrokedShape((Shape) list.get(j));
                if(line.contains(p))
                    System.out.print("reached mouse pressed");
    public void mouseDragged(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
        p = e.getPoint();
        ArrayList list;
        list = sk.circleList;
        for(int j = 0; j < list.size(); j++)
            circle = (Circle) list.get(j);           
                   if(circle.contains(p))           
                        System.out.print("reached mouse entered");           
        list = sk.lineList;
        if(!sk.p.equals("n") && list != null){
            for(int j = 0; j < list.size(); j++)       
                line = stroke.createStrokedShape((Circle) list.get(j));
                if(line.contains(p))
                    System.out.print("reached mouse pressed");
    public void mouseExited(MouseEvent e) {
    public void mouseMoved(MouseEvent e) {
    public void mousePressed(MouseEvent e) {
    public void mouseReleased(MouseEvent e) {
public class Sketch extends Canvas implements MouseListener, MouseMotionListener{
    int oldMousePositionx,oldMousePositiony, newMousePositionx, newMousePositiony;
    public String p = new String();
    Color mainColor = Color.WHITE;   
    public Save sav;
    String fileName, fileLocation;
    final int Originx = this.getWidth()/2;
    final int Originy = this.getHeight()/2;
    pointList pList = new pointList();
    pointList cList = new pointList();
    pointList rList = new pointList();
    Graphics2D g2;
    AffineTransform at = new AffineTransform();
    //intBuffer lineBuffer = new intBuffer();
    int i = 0;
    Line line;
    Circle circle;
    Rectangle rec;
    boolean islinereleased;
    boolean iscirclereleased;
    boolean isrectreleased;
    ArrayList<Shape> lineList = new ArrayList<Shape>();
    ArrayList<Circle> circleList = new ArrayList<Circle>();
    ArrayList<Shape> rectList = new ArrayList<Shape>();
    Frame fram;
     "LineSelect lineselect = new LineSelect( this );"
public void newSketch(Frame frame, String fileN, String fileL) {
    fram = frame;
    fileName = fileN.concat(".obj");
    fileLocation = fileL.concat(".obj");
    this.setSize(frame.getSize());
    this.setBackground(Color.BLACK);
    frame.add(this,BorderLayout.CENTER);
    File file = new File(fileLocation,fileName);
    sav = new Save(fileName,fileLocation);
    addMouseListener(lineselect);
    addMouseMotionListener(lineselect);
}This is just my implementation of various posts on the forum. But might give a different perspective.

Similar Messages

  • Adding event handling for panel

    Hi friendz. I have got a seemingly straightforward problem, but cant seem to figure out how to solve it. I want to add keypress event handler to a panel, so that whichever component of the panel is selected, pressing ctrl+n opens a jdialog. The problem is that when i add this event to a component(say jtable), it works fine, but when i add it to the panel, the event isnt detected. Any ideas??? Sample code would be appreciated. Thanks

    I am not sure about this but....
    Did you try to add listener to panel.getRootPane().addxxxx() ?

  • Event Handling for Graphic Shapes

    Hi guys,
    I have a problem on the implementation of a piece of software that i'm making, to be more specific i implement a GUI. In this GUI i draw rectangles, lines and that kind of things.
    The problem is that i want when clicking on a rectangle, an event to take place such as the drawing of something else, or a message, etc.
    How am i to achieve that? I've tried many things but didn't succeeded it unfortunately. How am i going to "give" life to my rectangles by adding event handling for them? What code should i write?
    Note: My class extends JPanel & i'm using paint(Graphics g) for drawing the shapes
    Thanks,
    John.

    Try this:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    public class Shapes extends JFrame
         DPanel pan = new DPanel();
    public Shapes()
         addWindowListener(new WindowAdapter()
              public void windowClosing(WindowEvent ev)
                   dispose();
                   System.exit(0);
         setBounds(10,10,400,350); 
         setContentPane(pan);
         setVisible(true);
    public class DPanel extends JPanel implements MouseListener
         Vector shapes = new Vector();
         Shape  cs;
    public DPanel()
         addMouseListener(this);
         shapes.add(new Rectangle(20,20,100,40));
         shapes.add(new Rectangle(40,80,130,60));
         shapes.add(new Line2D.Double(20,150,200,180));
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D)g;
         for (int j=0; j < shapes.size(); j++)
              g2.draw((Shape)shapes.get(j));
         g.setColor(Color.red);
         if (cs != null) g2.draw(cs);
    public void mouseClicked(MouseEvent m) {}
    public void mouseEntered(MouseEvent m) {}
    public void mouseExited(MouseEvent m)  {}
    public void mouseReleased(MouseEvent m){}
    public void mousePressed(MouseEvent m)
         for (int j=0; j < shapes.size(); j++)
              Shape s = (Shape)shapes.get(j);
              Rectangle r = new Rectangle(m.getX()-1,m.getY()-1,2,2);
              if (s.intersects(r))
                   cs = s;
                   repaint();
    public static void main (String[] args) 
          new Shapes();
    }Noah

  • Loading .EXE via event handling

    I'm adding event handling to a GUI menu - the idea being that each menu item, when selected, would launch a .exe file (for test purposes 'notepad' but in reality, it could be any xp)
    The operating system is XP, and JDK 1.5.0 is being used.
    How do I do this? - there seems to be no information on the topic in written documentation.

    Maybe this will help you a lot:
    http://java.sun.com/docs/books/tutorial/index.html
    Here is a direct link for using menu items:
    http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
    And I suggest using ProcessBuilder instead of Runtime.exec() if you are using JDK1.5.

  • Help with combobox event handling

    hey techies
    does knw any1 tutorial or where any URL which helps me adding event handling to combobox
    iam new at event handling
    i tried
    jc1.addItemListener(this);
    public void itemStateChanged(ItemEvent event)
              if(event.getSource()==jc1)
              System.out.println("hello");
         }is this way correct to specify event handling in combobox
    i tired this iam getting NPE like this
    Exception in thread "main" java.lang.NullPointerException
    at FinalMobile.<init>(FinalMobile.java:213)
    at FinalMobile.main(FinalMobile.java:740)
    plz jst let me knw and dnt tell me to refer swing tutorial i have been reffering it
    any help is appreciated

    does knw any1 tutorial or where any URL which helps me adding event handling to comboboxExcuse me, I've told you at least 4 times now to download and read the Swing tutorial which has all this information with working examples. I even provided you with the download link.
    How do you have the nerve to say you can't find any tutorial?

  • Event Handling with Java API.: Adding to a hierarchy table throws 2events

    I´m having some problems with the event handling. I´ve registered a Class with extends AbstractDataListener as EventListener. When there are changes in the product hierarchy table, some extra work should be done. However if i add a new record into the hierarchy, two events are fired.
    DEBUG DataEventListener.java:123 - Added:Development;PRODUCT_HIERARCHY;R17;Getra?nke, SEW
    DEBUG DataEventListener.java:123 - Added:Development;PRODUCT_HIERARCHY;R17;32 Zoll, B&R
    DEBUG DataEventListener.java:123 - Added:Development;PRODUCT_HIERARCHY;R18;56 Zoll, Lenze
    DEBUG DataEventListener.java:123 - Added:Development;PRODUCT_HIERARCHY;R18;20 Zoll, allgemein
    In this case, i added the records "32 Zoll, B&R" and then "20 Zoll, allgemein". As you can see in both cases two events are fired and the first event seems to come with wrong data. The reported id for the newly created record is R17. For the logging, i did lookup the entry in the hierarchy table by id and use the displayvalue of the record. But the first event always shows the displayvalue from some already existing entry.
    How can i avoid duplicate events or if this is not possible, how i can recognize that the display value of the first event is not valid.

    I have not tetsted it yet, because I'm waiting for my server to be updated, but SAP told me that the API version 5.5.42.67 should fix the problem.
    Thanks for your post.

  • Event handler if new File added in current folder

    Hi folks,
    I'm just trying to write a little jsx script for Bridge CS6.
    How can I implement an event handler that will react if the user adds a new thumbnail (new file) to the current folder in bridge.
    I've tested it with this code, but it doesn't work:
    app.document.thumbnail.watch ("children", function(id, oldVal, newVal) {
         $.writeln (oldVal + " to " + newVal);
         // some code here
    Thanks. Greetings

    Beautiful. Works as advertised. Thank you for pointing it out to me. Unfortunate that a basic subset of this extension's behaviour doesn't ship with Thunderbird out of the box, though.

  • Event Handler not Working

    Salutations!
    My College teacher was telling me about flash builder and how good it is for mobile applications. I've never done anything with actionscript before and had my first foray into such a few days ago. However I quickly ran into a problem. I've drawn a rectangle and are now wanting to try and use event handlers. For now I was wanting to say add the event handler for clicking on the rectangle. When done so then run a specifed function.
    rectangle.addEventListener(MouseEvent.CLICK, RectClicked);
    But even though there is nothing wrong anywhere in my application upon clicking the first rectangle, nothing happens. This is true for other mouse and keyboard events. My teacher said it may have something to do with having the student flash builder at College and currently having the trial here at home. It may not allow you to use certain functions.
    Do I have to purchase flash builder first before being able to use certain functionality?

    Ah... with all due respect, I think your teacher is wrong. To disable event handling would be somewhat traumatic for Flash which uses event handling as the core of its functionality. In any case, I am not aware of any functions being disabled on a trial version.
    It is far more likey to be a coding error on your part, sorry. There are a number of possibilities:
    1. You may have drawn a rectangle as a primitive (eg <s:Rect />) or as a Shape - both of which are IEventDispatcher but neither of which dispatch mouse events.
    2. You may have added the listener at the wrong point in the timeline so that the listener isn't there when you click.
    3. Some other, unspecified coding error...
    I imagine the first possibility is the most likely.
    Here is a simple pure actionscript clicker:
    [code]
    package
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    public class Clicker extends Sprite
      public function Clicker()
       var s:Sprite = new Sprite();
       s.graphics.beginFill(0xff,1);
       s.graphics.drawRect(0,0,50,50);
       s.x = s.y = 50;
       addChild(s);
       s.addEventListener(MouseEvent.CLICK,rectClicked);
      protected function rectClicked(event:MouseEvent):void {
       trace("Rectangle was clicked.");
    [/code]
    And here is the same in Flex:
    [code]
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
          xmlns:s="library://ns.adobe.com/flex/spark"
          xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
    <fx:Script>
      <![CDATA[
       import mx.graphics.SolidColor;
       protected function group1_clickHandler(event:MouseEvent):void
        trace("Rectangle was clicked.");
      ]]>
    </fx:Script>
    <fx:Declarations>
      <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Group x="50" y="50" click="group1_clickHandler(event)">
      <s:Rect width="50" height="50" fill="{new SolidColor(0xff,1)}" />
    </s:Group>
    </s:Application>
    [/code]
    G

  • Unable to get automatic event handling for OK button.

    Hello,
    I have created a form using creatobject. This form contains an edit control and Search, Cancel buttons. I have set the Search buttons UID to "1" so it can handle the Enter key hit event. Instead its caption changes to Update when i start typing in the edit control and it does not respond to the Enter key hit. Cancel happens when Esc is hit.
    My code looks like this -
    Dim oCreationParams As SAPbouiCOM.FormCreationParams
            oCreationParams = SBO_Application.CreateObject(SAPbouiCOM.BoCreatableObjectType.cot_FormCreationParams)
            oCreationParams.UniqueID = "MySearchForm"
            oCreationParams.BorderStyle = SAPbouiCOM.BoFormBorderStyle.fbs_Sizable
                    Dim oForm As SAPbouiCOM.Form = SBO_Application.Forms.AddEx(oCreationParams)
    oForm.Visible = True
    '// set the form properties
            oForm.Title = "Search Form"
            oForm.Left = 300
            oForm.ClientWidth = 500
            oForm.Top = 100
            oForm.ClientHeight = 240
            '// Adding Items to the form
            '// and setting their properties
            '// Adding an Ok button
            '// We get automatic event handling for
            '// the Ok and Cancel Buttons by setting
            '// their UIDs to 1 and 2 respectively
            oItem = oForm.Items.Add("1", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
            oItem.Left = 5
            oItem.Width = 65
            oItem.Top = oForm.ClientHeight - 30
            oItem.Height = 19
            oButton = oItem.Specific
            oButton.Caption = "Search"
            '// Adding a Cancel button
            oItem = oForm.Items.Add("2", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
            oItem.Left = 75
            oItem.Width = 65
            oItem.Top = oForm.ClientHeight - 30
            oItem.Height = 19
            oButton = oItem.Specific
            oButton.Caption = "Cancel"
    oItem = oForm.Items.Add("NUM", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            oItem.Left = 105
            oItem.Width = 140
            oItem.Top = 20
            oItem.Height = 16
            Dim oEditText As SAPbouiCOM.EditText = oItem.Specific
    What changes do i have to make to get the enter key to work?
    Thanks for your help.
    Regards,
    Sheetal

    Hello Felipe,
    Thanks for pointing me to the correct direction.
    So on refering to the documentation i tried out a few things. But I am still missing something here.
    I made the following changes to my code -
    oForm.AutoManaged = True
    oForm.SupportedModes = 1 ' afm_Ok
    oItem = oForm.Items.Add("1", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
            oItem.Left = 5
            oItem.Width = 65
            oItem.Top = oForm.ClientHeight - 30
            oItem.Height = 19
    oItem.SetAutoManagedAttribute(SAPbouiCOM.BoAutoManagedAttr.ama_Visible, 1, SAPbouiCOM.BoModeVisualBehavior.mvb_Default)
            oButton = oItem.Specific
            oButton.Caption = "OK"
    AND
    oForm.Mode = SAPbouiCOM.BoFormMode.fm_OK_MODE
    oItem = oForm.Items.Add("1", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
            oItem.Left = 5
            oItem.Width = 65
            oItem.Top = oForm.ClientHeight - 30
            oItem.Height = 19
    oItem.AffectsFormMode = False
    I get the same behaviour OK button changes to update and enter key does not work.
    Could you please tell me find what is it that i am doing wrong?
    Regards,
    Sheetal

  • Swing: when trying to get the values from a JTable inside an event handler

    Hi,
    I am trying to write a graphical interface to compute the Gauss Elimination procedure for solving linear systems. The class for computing the output of a linear system already works fine on console mode, but I am fighting a little bit to make it work with Swing.
    I put two buttons (plus labels) and a JTextField . The buttons have the following role:
    One of them gets the value from the JTextField and it will be used to the system dimension. The other should compute the solution. I also added a JTable so that the user can type the values in the screen.
    So whenever the user hits the button Dimensiona the program should retrieve the values from the table cells and pass them to a 2D Array. However, the program throws a NullPointerException when I try to
    do it. I have put the code for copying this Matrix inside a method and I call it from the inner class event handler.
    I would thank you very much for the help.
    Daniel V. Gomes
    here goes the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import AdvanceMath.*;
    public class MathF2 extends JFrame {
    private JTextField ArrayOfFields[];
    private JTextField DimOfSis;
    private JButton Calcular;
    private JButton Ativar;
    private JLabel label1;
    private JLabel label2;
    private Container container;
    private int value;
    private JTable DataTable;
    private double[][] A;
    private double[] B;
    private boolean dimensionado = false;
    private boolean podecalc = false;
    public MathF2 (){
    super("Math Calcs");
    Container container = getContentPane();
    container.setLayout( new FlowLayout(FlowLayout.CENTER) );
    Calcular = new JButton("Resolver");
    Calcular.setEnabled(false);
    Ativar = new JButton("Dimensionar");
    label1 = new JLabel("Clique no bot�o para resolver o sistema.");
    label2 = new JLabel("Qual a ordem do sistema?");
    DimOfSis = new JTextField(4);
    DimOfSis.setText("0");
    JTable DataTable = new JTable(10,10);
    container.add(label2);
    container.add(DimOfSis);
    container.add(Ativar);
    container.add(label1);
    container.add(Calcular);
    container.add(DataTable);
    for ( int i = 0; i < 10 ; i ++ ){
    for ( int j = 0 ; j < 10 ; j++) {
    DataTable.setValueAt("0",i,j);
    myHandler handler = new myHandler();
    Calcular.addActionListener(handler);
    Ativar.addActionListener(handler);
    setSize( 500 , 500 );
    setVisible( true );
    public static void main ( String args[] ){
    MathF2 application = new MathF2();
    application.addWindowListener(
    new WindowAdapter(){
    public void windowClosing (WindowEvent event)
    System.exit( 0 );
    private class myHandler implements ActionListener {
    public void actionPerformed ( ActionEvent event ){
    if ( event.getSource()== Calcular ) {
    if ( event.getSource()== Ativar ) {
    //dimensiona a Matriz A
    if (dimensionado == false) {
    if (DimOfSis.getText()=="0") {
    value = 2;
    } else {
    value = Integer.parseInt(DimOfSis.getText());
    dimensionado = true;
    Ativar.setEnabled(false);
    System.out.println(value);
    } else {
    Ativar.setEnabled(false);
    Calcular.setEnabled(true);
    podecalc = true;
    try {
    InitValores( DataTable, value );
    } catch (Exception e) {
    System.out.println("Erro ao criar matriz" + e );
    private class myHandler2 implements ItemListener {
    public void itemStateChanged( ItemEvent event ){
    private void InitValores( JTable table, int n ) {
    A = new double[n][n];
    B = new double[n];
    javax.swing.table.TableModel model = table.getModel();
    for ( int i = 0 ; i < n ; i++ ){
    for (int j = 0 ; j < n ; j++ ){
    Object temp1 = model.getValueAt(i,j);
    String temp2 = String.valueOf(temp1);
    A[i][j] = Double.parseDouble(temp2);

    What I did is set up a :
    // This code will setup a listener for the table to handle a selection
    players.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = players.getSelectionModel();
    rowSM.addListSelectionListener(new Delete_Player_row_Selection(this));
    //Class will take the event and call a method inside the Delete_Player object.
    class Delete_Player_row_Selection
    implements javax.swing.event.ListSelectionListener
    Delete_Player adaptee;
    Delete_Player_row_Selection (Delete_Player temp)
    adaptee = temp;
    public void valueChanged (ListSelectionEvent listSelectionEvent)
    adaptee.row_Selection(listSelectionEvent);
    in the row_Selection function
    if(ex.getValueIsAdjusting()) //To remove double selection
    return;
    ListSelectionModel lsm = (ListSelectionModel) ex.getSource();
    if(lsm.isSelectionEmpty())
    System.out.println("EMtpy");
    else
    int selected_row = lsm.getMinSelectionIndex();
    ResultSetTableModel model = (ResultSetTableModel) players.getModel();
    String name = (String) model.getValueAt(selected_row, 1);
    Integer id = (Integer) model.getValueAt(selected_row, 3);
    This is how I got info out of a table when the user selected it

  • Event Receiver:Item is Being Adding Event Recevier Issue

    Hi All,
     * I had written Simple event receviers(Item is Being Adding) to a site at FarmLevel(Farm Solution) and below is the code for it.
    * In below code I am adding the List name to a Column called "Name" ,when Item is being adding the code is getting loop and inserting unwanted data and updating Column "Name" with it instead of updating when item is added
    *Below if u see there is no value in Column "Name" when I insert values "Mark Devis"(Title) and "In Meeting"(Body) columns
    Can any one help me how can I solve the issue
           Code:
    string listitle = properties.List.Title + "" + "is List Name";
    string siteurl = http://sp2010:8080/personal/Sample/;
    using (SPSite mysite = new SPSite(siteurl))
    using (SPWeb myweb = mysite.OpenWeb())
    SPList mylist = myweb.Lists["Announcements"];    
    SPListItem newitem = mylist.Items.Add();
          newitem["Name"] = listitle.ToString();
          newitem.Update();
    Result:
    Samar

    Hello Samar,
    Try to use before/after properties to update item in list on ItemAdding event.
    http://sarveshspn.blogspot.in/2010/05/using-itemadding-and-afterproperties-to_08.html
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/1ed217b1-9441-4fe1-b3aa-68b2768bdfc7/updating-list-item-value-on-the-itemadding-event-handler-of-an-item-receiver-class?forum=sharepointdevelopmentlegacy
    Also make sure that you have at least contributor right in list to edit data.
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • Can  DISABLE preProcess Event Handler add to the Orchestration parameters?

    I have a DISABLE pre-process event handler defined on the User object. I need to set the current date on a USR UDF attribute whenever the user is disabled or enabled or created. The CREATE handler works and the date value shows up on the user profile. However, when I try to set this attribute on the pre-process DISABLE or ENABLE event handlers, the new date does not show up. Here is the code I am using in my DISABLE/ENABLE event handler:
    Date currentTime = new Date(System.currentTimeMillis());
    orchestration.addParameter(USER_STATUS_DATETIME_ATTR_NAME, currentTime);
    Where the orchestration object is from the execute() parameter list.
    Any ideas as to why this is not working? Is adding to the orchestration not allowed for DISABLE or ENABLE event handlers? I know my handler is getting calls as I am logging the orchestration.getOperation() value.
    Thanks for any suggestions.
    -Dave
    Edited by: user552098 on Nov 12, 2012 1:56 PM

    When you update the field, make sure you are using the field label name, and not the UDF value.
    -Kevin

  • Setting Item level access rights on sharepoint list item in ItemAdding event handler

    Hi ,
    I am using sharepoint 2013. I am trying to set item level access rights when a list item is added using the following code snippet,
    public override void ItemAdding(SPItemEventProperties properties)
    base.ItemAdding(properties);
    ConfigureItemSecurity(properties);
    private void ConfigureItemSecurity(SPItemEventProperties properties)
    var item=properties.ListItem;
    SPSecurity.RunWithElevatedPrivileges(delegate()
    using (SPSite site = new SPSite(properties.SiteId))
    using (SPWeb oWeb = site.OpenWeb())
    item.ParentList.BreakRoleInheritance(true);
    oWeb.AllowUnsafeUpdates = true;
    var guestRole = oWeb.RoleDefinitions.GetByType(SPRoleType.Reader);
    var editRole = oWeb.RoleDefinitions.GetByType(SPRoleType.Editor);
    SPGroup HRGroup = oWeb.SiteGroups.Cast<SPGroup>().AsQueryable().FirstOrDefault(g => g.LoginName=="HR Team");
    SPRoleAssignment groupRoleAssignment = new SPRoleAssignment(HRGroup);
    groupRoleAssignment.RoleDefinitionBindings.Add(guestRole);
    SPUserCollection users = oWeb.Users;
    SPFieldUserValueCollection hm = (SPFieldUserValueCollection)item["HiringManager"];
    SPFieldUserValueCollection pm = (SPFieldUserValueCollection)item["ProjectManager"];
    SPFieldUserValueCollection pmChiefs = (SPFieldUserValueCollection)item["ProjectManagerChief"];
    item.BreakRoleInheritance(true);
    item.RoleAssignments.Add(groupRoleAssignment);
    foreach (SPFieldUserValue staffMember in hm)
    SetRightsOnItem(item, staffMember, editRole);
    foreach (SPFieldUserValue staffMember in pm)
    SetRightsOnItem(item, staffMember, guestRole);
    foreach (SPFieldUserValue staffMember in pmChiefs)
    SetRightsOnItem(item, staffMember, guestRole);
    item.Update();
    private void SetRightsOnItem(SPListItem item, SPFieldUserValue staffMember, SPRoleDefinition role)
    SPUser employeeUser = staffMember.User;
    var userRoleAssignment = new SPRoleAssignment(employeeUser);
    userRoleAssignment.RoleDefinitionBindings.Add(role);
    item.RoleAssignments.Add(userRoleAssignment);
    Nothing is happening though... Is the event handler the right place to do this?
    thank you

    Hi ,
    You can refer to the code working in my environment:
    using System;
    using System.Security.Permissions;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;
    using Microsoft.SharePoint.Workflow;
    namespace ItemLevelSecurity.ItemSecurity
    /// <summary>
    /// List Item Events
    /// </summary>
    public class ItemSecurity : SPItemEventReceiver
    /// <summary>
    /// An item was added.
    /// </summary>
    public override void ItemAdded(SPItemEventProperties properties)
    SPSecurity.RunWithElevatedPrivileges(delegate()
    try
    using (SPSite oSPSite = new SPSite(properties.SiteId))
    using (SPWeb oSPWeb = oSPSite.OpenWeb(properties.RelativeWebUrl))
    //get the list item that was created
    SPListItem item = oSPWeb.Lists[properties.ListId].GetItemById(properties.ListItem.ID);
    //get the author user who created the item
    SPFieldUserValue valAuthor = new SPFieldUserValue(properties.Web, item["Created By"].ToString());
    SPUser oAuthor = valAuthor.User;
    //assign read permission to item author
    AssignPermissionsToItem(item,oAuthor,SPRoleType.Reader);
    //update the item
    item.Update();
    base.ItemAdded(properties);
    catch (Exception ex)
    properties.ErrorMessage = ex.Message; properties.Status = SPEventReceiverStatus.CancelWithError;
    properties.Cancel = true;
    public static void AssignPermissionsToItem(SPListItem item, SPPrincipal obj, SPRoleType roleType)
    if (!item.HasUniqueRoleAssignments)
    item.BreakRoleInheritance(false, true);
    SPRoleAssignment roleAssignment = new SPRoleAssignment(obj);
    SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
    roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
    item.RoleAssignments.Add(roleAssignment);
    Thanks,
    Eric
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected].
    Eric Tao
    TechNet Community Support

  • Event Handling in Fullscreen Exclusive Mode???????

    WIndows XP SP2
    ATI 8500 All-In-Wonder
    JDK 1.6
    800x600 32dpi 200 refresh
    1-6 buffer strategy.
    the graphic rendering thread DOESN'T sleep.
    Here's my problem. I have a bad trade off. In fullscreen exclusive mode my animation runs <30 fps and jerks when rendering. i.e. stop and go movement (not flickering/jittering just hesitant motion) when the animation is running. I solved this problem by raising the thread priority of the rendering (7-8). . . this resulted in latency/no activity for my input events both key and mouse. For instance closing the program alt-f4 will arbitrarily fail or be successful when the thread priority is raised above 6.
    How does one accomplish a >30 fps and Instant event handling simultaneously in Fullscreen Exclusive Mode?
    Is there a way to raise thread priority for event handling?
    Ultimately I want to be able to perform my animations and handle key and mouse input events without having a visible 'hiccups' on the screen.
    Much Appreciated!

    If I remember correctly the processor is a 1.4(or)6ghz AMD Duron
    Total = 1048048kb
    Available = 106084kb
    Sys Cache = 211788kb
    PF Usage = 1.01 GB
    I solved some of the problem after posting this thread. . . .
    I inserted a thread.sleep(1) and my alt-f4 operation worked unhindered with the elevated thread priority.
    I haven't tested it with mouse event or any other key event but at the moment it looks I may have solved the problem.
    If so, my next question will be is there a way to reduce the amount of cpu power needed to run the program.
    I'm afraid that the other classes that I'm adding will actually become even more process consuming than the actually rendering thread.
    public class RenderScreen extends Thread
      // Screen Rendering status code
      protected final static int RUNNING = 0,
                                 PAUSED = -1;
      // frames per second and process time counters
      protected long now = 0, fps = 0, fpsCount = 0, cycTime = 0;
      // thread status
      protected int status = 0;
      protected Screen screen;
      public void setStatus(int i){ status = i; };
      public void setTarget(Screen screen){ this.screen=screen; };
      public void run()
        setName("Screen Render");
        screen.createBufferStrategy(1);
        screen.strategy = screen.getBufferStrategy();
        for(;;)
          if(status == RUNNING)
            now = System.currentTimeMillis();
            while(System.currentTimeMillis() <= now+1000)
              // call system processes
              // fps increment / repaint interface
              fpsCount++;
              screen.renderView();
              try { Thread.sleep(1);}catch(InterruptedException ie){ ie.printStackTrace(); }
            fps = fpsCount;
            cycTime = System.currentTimeMillis() - (now + 1000);
            fpsCount=0;
      public RenderScreen(){};
      public RenderScreen(Screen screen){ this.screen=screen; };
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Screen extends Window
      BufferedImage image = new BufferedImage(800,600,BufferedImage.TYPE_INT_RGB);
      Graphics2D gdd = image.createGraphics();
      MediaTracker tracker = new MediaTracker(this);
      Image bground = getToolkit().getImage("MajorityRule.jpg"),
            bawl = getToolkit().getImage("bawl.gif");
      RenderScreen rScreen = new RenderScreen(this);
      BufferStrategy strategy;
      Graphics g;
      Rectangle rect = new Rectangle(400,0,150,150);
      //Game game = new Game();
      public void renderView()
        g = strategy.getDrawGraphics();
        //--------- Game Procedures [start]
        gdd.drawImage(bground,0,0,this);
        gdd.drawString("fps: ["+rScreen.fps+"] Cycle Time: ["+rScreen.cycTime+"]",0,10);
        //--------- Game Procedures [end]
        //---------test
        gdd.drawImage(bawl,rect.x,rect.y,rect.width,rect.height,this);
        rect.translate(0,1);
        g.drawImage(image,0,0,this);
        //g.dispose();
        strategy.show();
      public Screen(JFrame frame)
        super(frame);
        try
          tracker.addImage(bground,0);
          tracker.addImage(bawl,1);
          tracker.waitForAll();
        catch(InterruptedException ie){ ie.printStackTrace(); }
        setBackground(Color.black);
        setForeground(Color.white);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MajorityRule extends JFrame
      // Graphic System Handlers
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      GraphicsDevice gd = ge.getDefaultScreenDevice();
      GraphicsConfiguration gc = gd.getDefaultConfiguration();
      Screen screen = new Screen(this);
      Paper paper = new Paper();
      public void windowed()
        paper.setSize(getWidth(),getHeight());
        getContentPane().add(paper);
        setResizable(false);
        setVisible(true);
      public void fullscreen()
        DisplayMode dMode = new DisplayMode(800,600,32,200);
        screen.setBounds(0,0,800,600);
        if (gd.isFullScreenSupported()) gd.setFullScreenWindow(screen);
        if (gd.isDisplayChangeSupported()){ gd.setDisplayMode(dMode); };
        screen.setIgnoreRepaint(true);
        screen.setVisible(true);
        screen.rScreen.setPriority(Thread.MAX_PRIORITY);
        screen.rScreen.start();
        screen.requestFocus();
      public MajorityRule(String args[])
        setTitle("Majority Rule [Testing Block]");
        setBounds(0,0,410,360);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        getContentPane().setLayout(null);
        if (args.length > 0 && args[0].equals("-window")) windowed();
        else fullscreen();
      public static void main(String args[])
        new MajorityRule(args);
    };

  • Event handling in Network UI element in Webdynpro

    Hi ,
       I am developing a hierarchial graph using Network UI element.I want to incorporate event handling so that the graph will respond to user actions like on double clicking a node an URL will be opened.I can notproceed with the event handling.
                         Can anyone tell me the procedure to do this from webdynpro java.
    Regards
    Nayeem

    Hi Nayeem,
    The Network UI element has lots of events defined for it which can be handled to get the desired functionality.
    Go to the View in which you have added the Network Element, select the Element and go to the
    properties tab.
    Under events , you can see a list of events defined for this UI element.
    Select the event you wish to handle and press the Create button which gets visible once
    an event say onNodeSelected is selected
    You can then give a name to the action say UserClicked and save it .
    In the properties tab of the UI element , the action will be registed against the event .
    Now select the event again and press the go button.
    It will redirect you to the java editor of the view where in you can place your event handling logic.
    Alternatively, if you have created the UI element dynamically then you can add the event to the UI element by using the following code
    IWDNetwork network = (IWDNetwork)view.createElement(IWDNetwork.class);
    network.setOnNodeSelected(/*Your Action handler already defined in the View*/);
    Regards,
    Ashish

Maybe you are looking for

  • Cannot upgrade to itunes 10

    when i try to download itunes 10 it looks like it will load, but nothing happens. When i called support they told me to uninstall 9.2, but my system says "The windows installer could not be accessed. This can occur if you are running windows in safe

  • Deleted DFS Namespace still works

    Hi All, I inherited a network with a fairly poor DFS Domain based configuration as follows (with no replication): 2x DCs, (DC01(FSMO RoleHolder) & DC03) 1x Storage Server (NAS03) All servers are 2012R2 DC01 was the name space server pointing at folde

  • Installation error message - can't get rid of it

    here was an error with this action. Try again later. c35b41ef-ee6d-400e-bde1-6bf8ab4038f1 Can't get rid of error message, can't license the product after trial period Yes I have a subscription - 12mths

  • Value Mapping : Different Source - Same Target

    Hi all, Is it possible to map the different source value to the same target value with XI Value mappuing. Because when i try to set the same target value for a second value .. the directory delete it for the first one. for example i have: Value1 Valu

  • Why do I get a "call ended" alert when using  Googles Maps through hands free Blue Tooth service in my car

    Why do I get a "call ended" alert after voice directions, when using Googles Maps App with my iPhone 5s paired to Bluetooth service in my GM auto