JRadioButton Event Handling Help???

Hello everyone. I have been working on this program for a while now and it is just bugging me. It is a stoplight in which the lights are turned on by radio buttons. I have all the code but for some reason my radio buttons do not work. I have a listener and the actionperformed class defined and I just cannot figure out what is going on. Any help would be greatly appreciated.
Thanks,
Austin
import java.awt.*;*
*import java.awt.event.*;
import javax.swing.*;*
*class Lights extends JPanel*
*public JRadioButton btnR;*
*public JRadioButton btnY;*
*public JRadioButton btnG;*
*public JRadioButton btnO;*
*public Color rColor;*
*public Color yColor;*
*public Color gColor;*
*public Color general;*
*public void paintComponent ( Graphics g)*
*super.paintComponent ( g );*
*general= getBackground();*
*// Set foreground color*
*g.setColor (Color.black);*
*// get the size of the drawing area*
*Dimension size = this.getSize();*
*// Bounding rectangle for the traffic lights*
*int rectWidth = (int) (0.4* size.width);
int rectHeight = (int) (0.8 *size.height);*
*// Location where the rectangle is to be drawn*
*int xint = (int) (0.3* size.width);
int yint = (int) (0.1 *size.height);*
*// Draw bounding rectangle*
*g.drawRect (xint, yint, rectWidth, rectHeight);*
*// Draw three circles inside the rectangle*
*int circleHeight = (int) (0.9* rectHeight / 3);
int circleWidth = (int) (0.8 *rectWidth);*
*int circleDia = (circleHeight < circleWidth)? circleHeight : circleWidth;*
*int xOffset = (rectWidth - circleDia) / 2;*
*int yOffset = (rectHeight - 3* circleDia) / 4;
xint = xint +xOffset;+
+yint = yint+ yOffset;
// Draw the red light
g.setColor(getBackground());
g.setColor(rColor);
g.fillOval (xint, yint, circleDia, circleDia);
g.setColor(Color.black);
g.drawOval (xint, yint, circleDia, circleDia);
g.setColor(getBackground());
rColor= general;
// Draw the yellow light
yint = yint +circleDia+ yOffset;
g.setColor(yColor);
g.fillOval (xint, yint, circleDia, circleDia);
g.setColor(Color.black);
g.drawOval (xint, yint, circleDia, circleDia);
g.setColor(getBackground());
yColor= general;
// Draw the green light
yint = yint +circleDia+ yOffset;
g.setColor(gColor);
g.fillOval (xint, yint, circleDia, circleDia);
g.setColor(Color.black);
g.drawOval (xint, yint, circleDia, circleDia);
g.setColor(getBackground());
gColor= general;
public class TrafficLights
public static void main (String[] args)
Lights lightPanel = new Lights();
lightPanel.setBorder ( BorderFactory.createEmptyBorder (10, 20, 10, 20 ));
// Create buttons to simulate switches
lightPanel.btnR = new JRadioButton ("Red");
lightPanel.btnY = new JRadioButton ("Yellow");
lightPanel.btnG = new JRadioButton ("Green");
lightPanel.btnO = new JRadioButton ("Off");
ButtonGroup switches = new ButtonGroup ();
switches.add (lightPanel.btnR);
switches.add (lightPanel.btnY);
switches.add (lightPanel.btnG);
switches.add (lightPanel.btnO);
JPanel switchPanel = new JPanel();
switchPanel.setBorder ( BorderFactory.createEmptyBorder (10, 20, 10, 20 ));
switchPanel.setLayout (new GridLayout (1, 4));
switchPanel.add (lightPanel.btnR);
switchPanel.add (lightPanel.btnY);
switchPanel.add (lightPanel.btnG);
switchPanel.add (lightPanel.btnO);
JFrame frame = new JFrame ("Traffic Lights");
frame.getContentPane().add( lightPanel, BorderLayout.CENTER);
frame.getContentPane().add( switchPanel, BorderLayout.SOUTH);
frame.setSize (400, 600);
frame.setVisible (true);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
class LightButtonListener implements ActionListener
private Lights theLight;
//public Color c;
public LightButtonListener ( Lights aLight )
theLight = aLight;
//create listener and add buttons to it
theLight.btnR.addActionListener ( this );
theLight.btnY.addActionListener ( this );
theLight.btnG.addActionListener ( this );
theLight.btnO.addActionListener ( this );
public void actionPerformed ( ActionEvent evt )
if ( evt.getSource() == theLight.btnR)
theLight.rColor= Color.red;
theLight.repaint();
else if (evt.getSource() == theLight.btnY)
theLight.yColor= Color.yellow;
theLight.repaint();
else if (evt.getSource() == theLight.btnG)
theLight.rColor= Color.green;
theLight.repaint();
else if (evt.getSource() == theLight.btnO)
theLight.repaint();
}

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Lights extends JPanel
  public JRadioButton btnR;
  public JRadioButton btnY;
  public JRadioButton btnG;
  public JRadioButton btnO;
  public Color rColor;
  public Color yColor;
  public Color gColor;
  public Color general;
  public void paintComponent ( Graphics g)
    super.paintComponent ( g );
    general= getBackground();
    // Set foreground color
    g.setColor (Color.black);
    // get the size of the drawing area          
    Dimension size = this.getSize();
    // Bounding rectangle for the traffic lights
    int rectWidth = (int) (0.4 * size.width);
    int rectHeight = (int) (0.8 * size.height);
    // Location where the rectangle is to be drawn
    int xint = (int) (0.3 * size.width);
    int yint = (int) (0.1 * size.height);
    // Draw bounding rectangle
    g.drawRect (xint, yint, rectWidth, rectHeight);
    // Draw three circles inside the rectangle
    int circleHeight = (int) (0.9 * rectHeight / 3);
    int circleWidth = (int) (0.8 * rectWidth);
    int circleDia = (circleHeight < circleWidth)? circleHeight : circleWidth;
    int xOffset = (rectWidth - circleDia) / 2;
    int yOffset = (rectHeight - 3 * circleDia) / 4;
    xint = xint + xOffset;
    yint = yint + yOffset;
    // Draw the red light
    g.setColor(getBackground());
    g.setColor(rColor);
    g.fillOval (xint, yint, circleDia, circleDia);
    g.setColor(Color.black);
    g.drawOval (xint, yint, circleDia, circleDia);
    g.setColor(getBackground());
    rColor= general;
    // Draw the yellow light
    yint = yint + circleDia + yOffset;
    g.setColor(yColor);
    g.fillOval (xint, yint, circleDia, circleDia);
    g.setColor(Color.black);
    g.drawOval (xint, yint, circleDia, circleDia);
    g.setColor(getBackground());
    yColor= general;
    // Draw the green light
    yint = yint + circleDia + yOffset;
    g.setColor(gColor);
    g.fillOval (xint, yint, circleDia, circleDia);
    g.setColor(Color.black);
    g.drawOval (xint, yint, circleDia, circleDia);
    g.setColor(getBackground());
    gColor= general;
public class TrafficLights
  public static void main (String[] args)
     Lights lightPanel = new Lights();
     lightPanel.setBorder ( BorderFactory.createEmptyBorder (10, 20, 10, 20 ));
    // Create buttons to simulate switches
    lightPanel.btnR = new JRadioButton ("Red");
    lightPanel.btnY = new JRadioButton ("Yellow");
    lightPanel.btnG = new JRadioButton ("Green");
    lightPanel.btnO = new JRadioButton ("Off");
    ButtonGroup switches = new ButtonGroup ();
    switches.add (lightPanel.btnR);
    switches.add (lightPanel.btnY);
    switches.add (lightPanel.btnG);
    switches.add (lightPanel.btnO);
    JPanel switchPanel = new JPanel();
    switchPanel.setBorder ( BorderFactory.createEmptyBorder (10, 20, 10, 20 ));
    switchPanel.setLayout (new GridLayout (1, 4));
    switchPanel.add (lightPanel.btnR);
    switchPanel.add (lightPanel.btnY);
    switchPanel.add (lightPanel.btnG);
    switchPanel.add (lightPanel.btnO);
    JFrame frame = new JFrame ("Traffic Lights");
    frame.getContentPane().add( lightPanel, BorderLayout.CENTER);
    frame.getContentPane().add( switchPanel, BorderLayout.SOUTH);
    frame.setSize (400, 600);
    frame.setVisible (true);
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
class LightButtonListener implements ActionListener
  private Lights theLight;
  //public Color c;
  public LightButtonListener ( Lights aLight )
    theLight = aLight;
    //create listener and add buttons to it
    theLight.btnR.addActionListener ( this );
    theLight.btnY.addActionListener ( this );
    theLight.btnG.addActionListener ( this );
    theLight.btnO.addActionListener ( this );
  public void actionPerformed ( ActionEvent evt )
    if ( evt.getSource() == theLight.btnR)
      theLight.rColor= Color.red;
      theLight.repaint();
    else if (evt.getSource() == theLight.btnY)
         theLight.yColor= Color.yellow;
        theLight.repaint();
    else if (evt.getSource() == theLight.btnG)
         theLight.rColor= Color.green;
        theLight.repaint();
    else if (evt.getSource() == theLight.btnO)
        theLight.repaint();
}Edited by: CS313e on Mar 27, 2010 1:21 AM
Edited by: CS313e on Mar 27, 2010 9:59 AM

Similar Messages

  • Event Handling Help needed please.

    Hi,
    I am writing a program to simulate a supermarket checkout. I have done the GUI and now i am trying to do the event handling. I have come up against a problem.
    I have a JCombobox called prodList and i have added an string array to it called prods . I have also created 2 more arrays with numbers in them.
    I want to write the code for if an item is selected from the combo box that the name from the array is shown in a textfield tf1, and also the price and stock no which correspond to the seclected item (both initialised in the other arrays) are also added to the textfield tf1.
    I have started writng the code but i am really stuck. Could someone please help me with this please. The code i have done so far is as follows(just the event handling code shown)
              public void ItemStateChange(ItemEvent ie){
              if(ie.getItemSelected()== prodList)
                   changeOutput();
              public void changeOutput()
                   if(ItemSelected ==0)
                        tf1.setText("You have selected" +a +b +c);
         }

    Do you say this because i missed the d of ItemStateChanged ?
    I have amended that but still i am getting the same errors class or enum expected. 4 of them relating to the itemStateChanged method.
    i will post my whole code if it helps
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Observer;  //new
    import java.util.Observable;//new
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.border.TitledBorder;
    public class MySuperMktPro
         public MySuperMktPro()
              CheckoutView Check1 = new CheckoutView(1,0,0);
              CheckoutView Check2 = new CheckoutView(2,300,0);
              CheckoutView Check3 = new CheckoutView(3,600,0);
              CheckoutView Check4 = new CheckoutView(4,0,350);
              CheckoutView Check5 = new CheckoutView(5,600,350);
              OfficeView off111 = new OfficeView();
        public static void main(String[] args) {
             // TODO, add your application code
             System.out.println("Starting My Supermarket Project...");
             MySuperMktPro startup = new MySuperMktPro();
        class CheckoutView implements ItemListener , ActionListener
        private OfficeView off1;
         private JFrame chk1;
         private Container cont1;
         private Dimension screensize,tempDim;
         private JPanel pan1,pan2,pan3,pan4,pan5;
         private JButton buyBut,prodCode;
         private JButton purchase,cashBack,manual,remove,disCo;
         private JButton but1,but2,finaLi1,but4,but5,but6;
         private JTextArea tArea1,tArea2;
         private JTextField tf1,tf2,tf3,list2;
         private JComboBox prodList;
         private JLabel lab1,lab2,lab3,lab4,lab5,lab6,lab7;
         private int checkoutID; //New private int for all methods of this class
         private int passedX,passedY;
         private String prods[];
         private JButton rb1,rb2,rb3,rb4;
         private double price[];
         private int code[];
         public CheckoutView(int passedInteger,int passedX,int passedY)
              checkoutID = passedInteger; //Store the int passed into the method
            this.passedX = passedX;
            this.passedY = passedY;
              drawCheckoutGui();
         public void drawCheckoutGui()
              prods= new String[20];
              prods[0] = "Beans";
              prods[1] = "Eggs";
              prods[2] = "bread";
              prods[3] = "Jam";
              prods[4] = "Butter";
              prods[5] = "Cream";
              prods[6] = "Sugar";
              prods[7] = "Peas";
              prods[8] = "Milk";
              prods[9] = "Bacon";
              prods[10] = "Spaghetti";
              prods[11] = "Corn Flakes";
              prods[12] = "Carrots";
              prods[13] = "Oranges";
              prods[14] = "Bananas";
              prods[15] = "Snickers";
              prods[16] = "Wine";
              prods[17] = "Beer";
              prods[18] = "Lager";
              prods[19] = "Cheese";
              for(i=0; i<prods.length;i++);
              code = new int [20];
              code[0] = 1;
              code[1] = 2;
              code[2] = 3;
              code[3] = 4;
              code[4] = 5;
              code[5] = 6;
              code[6] = 7;
              code[7] = 8;
              code[8] = 9;
              code[9] = 10;
              code[10] = 11;
              code[11] = 12;
              code[12] = 13;
              code[13] = 14;
              code[14] = 15;
              code[15] = 16;
              code[16] = 17;
              code[17] = 18;
              code[18] = 19;
              code[19] = 20;
              for(b=0; b<code.length; b++);
              price = new double [20];
              price[0] = 0.65;
              price[1] = 0.84;
              price[2] = 0.98;
              price[3] = 0.75;
              price[4] = 0.45;
              price[5] = 0.65;
              price[6] = 1.78;
              price[7] = 1.14;
              price[8] = 0.98;
              price[9] = 0.99;
              price[10] = 0.98;
              price[11] = 0.65;
              price[12] = 1.69;
              price[13] = 2.99;
              price[14] = 0.99;
              price[15] = 2.68;
              price[16] = 0.89;
              price[17] = 5.99;
              price[18] = 1.54;
              price[19] = 2.99;
              for(c=0; c<code.length; c++);
              screensize = Toolkit.getDefaultToolkit().getScreenSize();
              chk1 = new JFrame();
              chk1.setTitle("Checkout #" + checkoutID); //Use the new stored int
              chk1.setSize(300,350);
              chk1.setLocation(passedX,passedY);
              chk1.setLayout(new GridLayout(5,1));
              //chk1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              cont1 = chk1.getContentPane();
              //chk1.setLayout(new BorderLayout());
                 pan1 = new JPanel();
                 pan2 = new JPanel();
              pan3 = new JPanel();
              pan4 = new JPanel();
              pan5 = new JPanel();
              //panel 1
              pan1.setLayout(new FlowLayout());
              pan1.setBackground(Color.black);          
              prodList = new JComboBox(prods);
              prodList.setMaximumRowCount(2);
              prodList.addItemListener(this);
              but1 = new JButton("Buy");
              but1.addActionListener(this);
              lab1 = new JLabel("Products");
              lab1.setForeground(Color.white);
              lab1.setBorder(BorderFactory.createLineBorder(Color.white));
              pan1.add(lab1);
              pan1.add(prodList);          
              pan1.add(but1);
              //panel 2
              pan2 = new JPanel();
              pan2.setLayout(new BorderLayout());
              pan2.setBackground(Color.black);
              lab3 = new JLabel("                                Enter Product Code");
              lab3.setForeground(Color.white);
              tArea2 = new JTextArea(8,10);
              tArea2.setBorder(BorderFactory.createLineBorder(Color.white));
              lab5 = new JLabel("  Tesco's   ");
              lab5.setForeground(Color.white);
              lab5.setBorder(BorderFactory.createLineBorder(Color.white));
              lab6 = new JLabel("Checkout");
              lab6.setForeground(Color.white);
              lab6.setBorder(BorderFactory.createLineBorder(Color.white));
              lab7 = new JLabel("You  selected                      ");
              lab7.setForeground(Color.cyan);
              //lab7.setBorder(BorderFactory.createLineBorder(Color.white));
              pan2.add(lab7,"North");
              pan2.add(lab6,"East");
              pan2.add(tArea2,"Center");
              pan2.add(lab5,"West");
              pan2.add(lab3,"South");
              //panel 3
              pan3 = new JPanel();
              pan3.setLayout(new FlowLayout());
              pan3.setBackground(Color.black);
              manual = new JButton("Manual");
              manual.addActionListener(this);
              manual.setBorder(BorderFactory.createLineBorder(Color.white));
              remove = new JButton("Remove");
              remove.addActionListener(this);
              remove.setBorder(BorderFactory.createLineBorder(Color.white));
              tf1 = new JTextField(5);
              pan3.add(manual);
              pan3.add(tf1);
              pan3.add(remove);
              //panel 4
              pan4 = new JPanel();
              pan4.setLayout(new FlowLayout());
              pan4.setBackground(Color.black);
              finaLi1 = new JButton("Finalise");
         //     finaLi1.addActionListener(this);
              cashBack = new JButton("Cashback");
              JTextField list2 = new JTextField(5);
              but4 = new JButton(" Sum Total");
              but4.addActionListener(this);
              but4.setBorder(BorderFactory.createLineBorder(Color.white));
              cashBack.setBorder(BorderFactory.createLineBorder(Color.white));
              pan4.add(cashBack);
              pan4.add(list2);
              pan4.add(but4);
              //panel 5
              pan5 = new JPanel();
              pan5.setLayout(new GridLayout(2,3));
              pan5.setBackground(Color.black);
              disCo = new JButton("Discount");
              disCo.addActionListener(this);
              disCo.setBorder(BorderFactory.createLineBorder(Color.black));
              but6 = new JButton("Finalise");
              but6.addActionListener(this);
              but6.setBorder(BorderFactory.createLineBorder(Color.black));
              rb1 = new JButton("Cash");
              rb1.addActionListener(this);
              rb1.setBorder(BorderFactory.createLineBorder(Color.black));
              rb2 = new JButton("Card");
              rb2.addActionListener(this);
              rb2.setBorder(BorderFactory.createLineBorder(Color.black));
              rb3 = new JButton("Cheque");
              rb3.addActionListener(this);
              rb3.setBorder(BorderFactory.createLineBorder(Color.black));
              rb4 = new JButton("Voucher");
              rb4.addActionListener(this);
              rb4.setBorder(BorderFactory.createLineBorder(Color.black));
              pan5.add(disCo);
              pan5.add(but6);
              pan5.add(rb1);
              pan5.add(rb2);
              pan5.add(rb3);
              pan5.add(rb4);
              //add the panels to the container        
              cont1.add(pan1);
              cont1.add(pan4);     
              cont1.add(pan2);
              cont1.add(pan3);          
              cont1.add(pan5);          
              chk1.setContentPane(cont1);
              chk1.setVisible(true);     
    class OfficeView
         private OfficeView off111;
         private JFrame offMod1;
         private JPanel pane1;
         private JButton refill;
         private Container cont11;
         private Dimension screensize;
         private JTextField tf11,tf12;
         public OfficeView()
              drawOfficeGUI();
         public void drawOfficeGUI()
              screensize = Toolkit.getDefaultToolkit().getScreenSize();
              offMod1 = new JFrame("Office Control");
              int frameWidth = 300;
              int frameHeight = 250;
              offMod1.setSize(frameWidth,frameHeight);
              offMod1.setLocation(300,350);
              offMod1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              cont11 = offMod1.getContentPane();
              pane1 = new JPanel();
              pane1.setBackground(Color.cyan);
              refill = new JButton("Refill");
              tf11 = new JTextField(25);
              tf12 = new JTextField(25);
              pane1.add(tf11);
              pane1.add(refill);
              pane1.add(tf12);
              cont11.add(pane1);
              offMod1.setContentPane(cont11);
              offMod1.setVisible(true);
              public void ItemStateChanged(ItemEvent ie)
                        if(ie.getItemSelected()== prodList)
                                  changeOutput();
              public void changeOutput()
                        if(ItemSelected ==0)
                                  tf1.setText("You have selected", +a +b +c);
                   }Message was edited by:
    fowlergod09

  • Event handling help

    1.     getGraphics()
    2.     setCursor(?)
    3.     Use setDefaultCloseOperation(Jframe.CLOSE_ON_EXIT);
    4.     The DemoPanel needs a reference to the frame so the easiest way to accomplish this is to have your DemoPanel constructor take an argument of type JFrame. So when you create the DemoPanel you pass it the JFrame reference as an argument. In the constructor you save the reference as an instance variable.
    5.     On the DemoPanel make sure to provide public boolean isFocusTraversable() {return true;}
    6.     You can get the getClickCount() from the MouseEvent class
    7.     You can get what mouse key is pressed using the MouseEvent class CJ5e 384 (hint: e.getModifiers() & InputEvent.Button#_MARK button 1 is left and button 3 is right)
    8.     ParseInt
    9.     Remember when the frame is resized, moved, or covered paintComponent will be called to repaint the Sqaures.
    10.     I think that action key don?t generate a keyTyped event.
    11.     Use the KeyEvent.getKeyChar() in keyTyped to get the character typed.
    12.     Use an array of Color.red, Color.blue, Color.green to key track and iterate through your colors.
    13.     event.getKeyCode() == KeyEvent.VK_ENTER to determine an Enter key
    14.     Use if (!event.isActionKey()) to determine a non actionkey
    public class Demo extends JFrame
    DemoPanel thePanel;
    public Demo()
    // get screen dimensions
    Toolkit kit = Toolkit.getDefaultToolkit();
    Dimension screenSize = kit.getScreenSize();
    int screenHeight = screenSize.height;
    int screenWidth = screenSize.width;
    // put frame in upper right hand corner
    setSize(screenWidth / 2 , screenHeight / 2);
    setLocation((screenWidth / 2),0);
    setTitle("Event-Handling Demonstration");
    // add panel to frame
    thePanel = new DemoPanel(theFrame);
    Container c = this.getContentPane();
    c.add(thePanel);
    this.addWindowListener(new WindowAdapter()
    public void windowDeiconified(WindowEvent e)
    this.show();
    static public void main(String args[])
    Demo theFrame = new Demo();
    [\code]
    Second, does this sound reasonable?
    Do you see anything wrong in the code?

    Yeah, here's a suggestion - quit cross-posting your
    stupid question all over the place and when everyone
    ignores it for another 6 hours, don't bring it back to
    the top AGAIN.Hey, dear friend, don't you ever REALY need an answer for you question.
    If you don't know answer, better don't post ANY message.
    And one more, stupidity of question is a rather personal thing.

  • JRadioButton Event Handling Problem

    I'm having trouble getting my JRadioButtons to work. They appear and function, but when I click them, they don't do what they should. I used e.getActionCommand() to get the string name of the JRadioButton, and I used e.getSource() to compare it to the name of the radiobutton, which is the same as the text of the button. I read in one of the tutorials that a JRadioButton fires an action event and an item event. Should I use an item event? I'm trying to perform certain actions based on which button is selected. This code sets the string radioname to the name of the button selected, which I later use to perform other actions. I get major errors when I try changing things, because I don't really know how the buttons work. Thanks.
    private JRadioButton d0,d1,d2,d3,d4,d5,d6,d7,d8,d9;
    public void actionPerformed(ActionEvent e)
    if (e.getSource() == "d0" || e.getSource() == "d1"                || e.getSource() == "d2" || e.getSource() == "d3"                || e.getSource() == "d4" || e.getSource() == "d5"                || e.getSource() == "d6" || e.getSource() == "d7"                || e.getSource() == "d8" || e.getSource() == "d9")
         radioname = e.getActionCommand();
              System.out.println(radioname);
              System.out.println("radio event fired");
    }

    I tried that, but that gives me a bunch of error messages, mostly from java.awt about dispatch events and dispatch threads when I click one of the buttons. Does it have something to do with the ButtonGroup the JRadioButtons are in? This is the end of the errors, which is all I can view.
    at javax.swing.JToggleButton$ToggleButtonModel.setPressed(JToggleButton.
    java:268)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:216)
    at java.awt.Component.processMouseEvent(Component.java:3715)
    at java.awt.Component.processEvent(Component.java:3544)
    at java.awt.Container.processEvent(Container.java:1164)
    at java.awt.Component.dispatchEventImpl(Component.java:2593)
    at java.awt.Container.dispatchEventImpl(Container.java:1213)
    at java.awt.Component.dispatchEvent(Component.java:2497)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:2451
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2216)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2125)
    at java.awt.Container.dispatchEventImpl(Container.java:1200)
    at java.awt.Component.dispatchEvent(Component.java:2497)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:131)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:98)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)

  • Button Event Handler in a JList, Please help.

    Hi everyone,
    I have created a small Java application which has a JList. The JList uses a custom cell renderer I named SmartCellRenderer. The SmartCellRenderer extends JPanel and implements the ListCellRenderer. I have added two buttons on the right side inside the JPanel of the SmartCellRenderer, since I want to buttons for each list item, and I have added mouse/action listeners for both buttons. However, they don't respond. It seems that the JList property overcomes the buttons underneath it. So the buttons never really get clicked because before that happens the JList item is being selected beforehand. I've tried everything. I've put listeners in the Main class, called Editor, which has the JList and also have listeners in the SmartCellRenderer itself and none of them get invoked.
    I also tried a manual solution. Every time the event handler for the JList was invoked (this is the handler for the JList itself and not the buttons), I sent the mouse event object to the SmartCellRenderer to manually check if the point the click happened was on one of the buttons in order to handle it.
    I used:
    // Inside SmartCellRenderer.java
    // e is the mouse event object being passed from the Editor whenever
    // a JList item is selected or clicked on
    Component comp = this.getComponent (e.getX(), e.getY())
    if(!(comp instanceof JButton)) {
              System.out.println("Recoqnized Event, but not a button click...");
              //return;
    } else {
              System.out.println("Recognized Event, IT IS A MOUSE CLICK, PROCESSING...");
              System.out.println("VALUE: "+comp.toString());
    What I realized is that not only this still doesn't work (it never realizes the component as a JButton) it also throws an exception for the last line saying comp is null. Meaning with the passed x,y position the getComponent() returns a null which happens when the coordinates passed to it are outside the range of the Panel. Which is a whole other problem?
    I have yet to find an example on the web, using Google, that demonstrated using buttons inside a JList.
    Can anyone help me with this. Thanks.

    A renderer is not a component, so you can't click on it. A renderer is just used to paint a representation of a component at a certain position in your JList.
    I have yet to find an example on the web, using Google, that demonstrated using buttons inside a JList.Thats probably because this is not a common design. The following two designs are more common:
    a) Create a separate panel for your JButtons. Then when you click on the button it would act on each selected row in the JList
    b) Or maybe like windows explorer. Select the items in the list and then use a JPopupMenu to perform the desired functionality.
    I've never tried to add a clickable button to a panel, but this [url http://forum.java.sun.com/thread.jspa?threadID=573721]posting shows one way to add a clickable JButton as a column in a JTable. You might be able to use some of the concepts to add 2 button to the JPanel or maybe you could use a JTable with 3 columns, one for your data and the last two for your buttons.

  • Help with Javascript error in event handler slowing animation down.

    Hi all--
    I did an animated book cover for my publisher, Baen Books, but an error keeps coming up in my animation.  The actual animating can be viewed here:
    http://baen.com/310x204/A_CallToDuty.html
    As you can see, when the error pops up, the animation grinds to a halt, an it has to recover.  I am not well enough versed in javascript to know what is going on. The error code below repeats over and over again as it plays.
    6Javascript error in event handler! Event Type = timeline edge.3.0.0.min.js:171
    3
    <error> VM26:184
    Javascript error in event handler! Event Type = timeline edge.3.0.0.min.js:1714Javascript error in event handler! Event Type = timeline edge.3.0.0.min.js:1713
    <error>
    If anyone has an idea what is causing this, I would be extremely grateful for  any help.
    David Mattingly

    Hi Hemanth--
    I put it in a dropbox folder for you here:
    Dropbox - EdgeAnimation
    This contains 2 versions--a small one for the preview, and then a larger one when people click on the cover preview. Thanks in advance for your help.\
    David Mattingly

  • 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 Handler is not getting trigger for Freely Programmed search help

    Hi All,
       I am having a component comp1 defined for value help with one event. In component comp2 i want to call the comp1 but the event handler which i have created is not getting triggered. Any reasons for it.
    Thanks
    Raghavendra

    Hi Kumar,
    Please check these forum threads.
    Re: Help required on Freely Programmed Input help
    Re: Custom search help

  • Help needed in implementing validation event handler in OIM 11g

    Hello experts,
    I am trying to set username policy by implementing a validation event handler in OIM 11.1.1.5.
    Following are the steps followed
    1. Import metadata
    Created a file called Eventhandler.xml as below and imported using weblogicImportmetadata.sh
    <?xml version='1.0' encoding='UTF-8'?>
    <eventhandlers xmlns="http://www.oracle.com/schema/oim/platform/kernel" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.oracle.com/schema/oim/platform/kernel orchestration-handlers.xsd">
    <validation-handler class="test.iam.eventhandlers.CustomValidationEventHandler" entity-type="User" operation="CREATE" name="CustomValidationEventHandler" order="1000" sync="TRUE"/>
    </eventhandlers>
    2. Register plugin
    plugin.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <oimplugins xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <plugins pluginpoint="oracle.iam.platform.kernel.spi.ValidationHandler">
    <plugin pluginclass="test.iam.eventhandlers.CustomValidationEventHandler" version="1.0" name="CustomValidationEventHandler" />
    </plugins>
    </oimplugins>
    Just givng sys out in the below code to check whther it is getting triggerred during user create.
    package test.iam.eventhandlers;
    import java.util.HashMap;
    import oracle.iam.platform.Platform;
    import oracle.iam.platform.context.ContextAware;
    import oracle.iam.platform.kernel.ValidationException;
    import oracle.iam.platform.kernel.ValidationFailedException;
    import oracle.iam.platform.kernel.spi.ValidationHandler;
    import oracle.iam.platform.kernel.vo.BulkEventResult;
    import oracle.iam.platform.kernel.vo.BulkOrchestration;
    import oracle.iam.platform.kernel.vo.Orchestration;
    public class CustomValidationEventHandler implements ValidationHandler {
         @Override
         public void initialize(HashMap<String, String> arg0) {
         // TODO initialization
              System.out.println("init validate event handler");
         @Override
         public void validate(long processId, long eventId, Orchestration orchestration)
         throws ValidationException, ValidationFailedException {
              System.out.println("Beginning of validation");
              System.out.println("End of validation");
         @Override
         public void validate(long processId, long eventId, BulkOrchestration arg2)
         throws ValidationException, ValidationFailedException {
         // TODO - N/A
              System.out.println("Bulk Orchestration not yet implemented");     
    Now when i create a user it is not allowing and i am getting system error in the front end and in the logs i could see something below
    <May 28, 2012 3:03:29 PM CEST> <Error> <oracle.iam.identity.usermgmt.impl> <IAM-3050029> <The user cannot be created due to validation errors.
    oracle.iam.platform.kernel.ValidationFailedException: Event handler CustomValidationEventHandler implemented using class/plug-test.iam.eventhandlers.CustomValidationEventHandler could not be loaded.
    at oracle.iam.platform.kernel.impl.OrchProcessData.runValidationEvents(OrchProcessData.java:177)
    at oracle.iam.platform.kernel.impl.OrchestrationEngineImpl.validate(OrchestrationEngineImpl.java:644)
    at oracle.iam.platform.kernel.impl.OrchestrationEngineImpl.process(OrchestrationEngineImpl.java:497)
    at oracle.iam.platform.kernel.impl.OrchestrationEngineImpl.orchestrate(OrchestrationEngineImpl.java:444)
    at oracle.iam.platform.kernel.impl.OrchestrationEngineImpl.orchestrate(OrchestrationEngineImpl.java:378)
    at oracle.iam.identity.usermgmt.impl.UserManagerImpl.create(UserManagerImpl.java:656)
    at oracle.iam.identity.usermgmt.api.UserManagerEJB.createx(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.bea.core.repackaged.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
    I have implemented preprocess and postprocess event handler before with similar kind of plugin registration, metadata import and everything worked fine. Not sure what is the problem here with validation event handler.
    Thanks
    DK

    Instead of registering the plug-in can u try placing it in the plugins folder under Oracle_IDM1/server folder.
    at times restart is required. esp when the server is running in production mode.
    Regards
    user12841694

  • Help event handling

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class DemoWindow extends JFrame
         private final int WIDTH = 200, HEIGHT = 200;
         public DemoWindow() {
              //set title
              setTitle( "Event-Handling Demostration" );
              //get screen size
              Dimension d = this.getToolkit().getScreenSize();
              //1. if u want the fram to fill the whole screen use this code
              setLocation( 0, 0 );   //may not need because it's default
              setSize( d.width, d.height );
              //2. if u have a custom frame size use this code to
              //   dynamically center it (assume the given size at top)
              setSize( WIDTH, HEIGHT );
              setLocation( (d.width-this.getWidth()) / 2,
              (d.height-this.getHeight())/ 2 );
              //to end program when frame is closed (using anynomus inner class)
              addWindowListener( new WindowAdapter() {
                   public void windowClosing( WindowEvent e ) {
                        System.exit( 0 );
                        }); //end of inner class
                        public static void main( String[] args ) {
                             DemoWindow test = new DemoWindow();
                             test.setVisible( true );   }} //end of DemoWindow classWhen the program starts, the Demo window will fill � the area of the screen, and the center of the
    window will be at the center of the screen. This sizing and positioning will be based on the current
    screen display mode, not on hard-coded constants. The window title will be "Event-Handling
    Demonstration". When the window is closed, the program will end.
    The DemoPanel class will handle keyboard events using an inner class or classes. The
    isFocusTraversable method will be used to allow the DemoPanel to obtain keyboard focus.
    DemoPanel will collect from the keyboard all characters that are not action keys. Each time the Enter
    key is pressed, DemoPanel will set the title of the Demo window equal to the characters collected since
    the last time the Enter key was pressed, not including the Enter key. If the characters entered are an
    integer number greater than 0, DemoPanel will set the current drawing square size (see below) equal to
    this number. To set the square size, use a code structure similar to the following, where str is the
    String of collected characters:
    try {
    squareSize = Integer.parseInt(str);
    } catch (NumberFormatException xcp) {};
    how do i do the second part

    help

  • Need Help with Event Handler Code - Doesnt come up in Event Handler Manager

    Hello there,
    Below is the code snippet that I am using to create a event handler:
    package com.oracle.events;
    import com.thortech.util.logging.Logger;
    import com.thortech.xl.client.events.tcBaseEvent;
    import com.thortech.xl.dataobj.tcDataObj;
    import com.thortech.xl.util.logging.LoggerModules;
    public class tcCheckOvrallProvStatusUDFs extends tcBaseEvent
         private static Logger logger = Logger.getLogger(LoggerModules.XL_JAVA_CLIENT);
         public tcCheckOvrallProvStatusUDFs()
              setEventName("Generating tcCheckOvrallProvStatusUDFs");
    * @Override
    * @throws Exception
         protected void implementation() throws Exception {
              tcDataObj data = getDataObject();
              String OIDProvStatus = data.getString("usr_udf_oidusrprovstatus");
    String EBSProvStatus = data.getString("usr_udf_ebstcausrprovstatus");
              if (OIDProvStatus.equals("Provisioned") && EBSProvStatus.equals("Provisioned")) {
                   setOverAllProvStatus(data);
         * @param data
         * @throws Exception
         private void setOverAllProvStatus(tcDataObj data) throws Exception
              data.setString("usr_udf_ovrrscprovstatus", "Provisioned");
    Its a simple code that I am using to populate value of a UDF field depending on the value of other 2 fields. I want to trigger it on Post-Insert and Post-Update events.
    But even if I restart the OIM server after placing the successfully compiled file (0 errors, 0 warnings) into the EventHandlers folder of OIM_HOME; it doesnt show up in the Design Console -> Development Tools -> Business Rule Definition -> Event Handler Manager. :( In order to create a event handler i need that file to show up in the lookup of event handlers/adapters. This JAR file doesnt come up over there.
    Is there anything missing within the code ?
    What else needs to be specified?
    Please provide some guidance.
    Thanks,
    - jhb.

    Now I have placed this JAR file in JAVATasks folder - made an entity adapter - in the event handler manager - i gave the class name/event handler name as 'setUDFValue' and the package as 'project5'. But now im getting it 'DOBJ.EVT_NOT_FOUND - Event Handler not found' error.
    package project5;
    import java.util.Hashtable;
    import Thor.API.Exceptions.tcAPIException;
    import java.util.Hashtable;
    import java.util.HashMap;
    import com.thortech.xl.util.config.ConfigurationClient;
    import Thor.API.tcResultSet;
    import Thor.API.tcUtilityFactory;
    import Thor.API.Operations.tcUserOperationsIntf;
    import java.lang.System;
    import Thor.API.Exceptions.tcUserNotFoundException;
    import java.util.Properties;
    import javax.mail.Message;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    public class setUDFValue {
    private static final String SMTP_HOST_NAME="mail.smtp.host";
    public setUDFValue() {
    // public static void main(String[] args) {
    // setUDFValue.setvalue("jatinbhatt");
    // setUDFValue.sendemail("[email protected]","[email protected]");
    public static void setvalue(String UserID) {   
    try
    System.setProperty("XL.HomeDir", "F:/oim/oimserver/xellerate");
    System.setProperty("log4j.configuration",
    "F:/oim/oimserver/xellerate/config/log.properties");
    System.setProperty("java.security.policy",
    "F:/oim/oimserver/xellerate/config/xl.policy");
    System.setProperty("java.security.auth.login.config",
    "F:/oim/oimserver/xellerate/config/auth.conf");
    System.out.println("Startup...");
    System.out.println("Getting configuration...");
    ConfigurationClient.ComplexSetting config = ConfigurationClient.getComplexSettingByPath("Discovery.CoreServer");
    System.out.println("Login...");
    Hashtable env = config.getAllSettings();
    tcUtilityFactory ioUtilityFactory = new tcUtilityFactory(env,"xelsysadm","oimadmin1");
    System.out.println("Getting utility interfaces...");
    tcUserOperationsIntf moUserUtility = (tcUserOperationsIntf)ioUtilityFactory.getUtility("Thor.API.Operations.tcUserOperationsIntf");
    HashMap userMap = new HashMap();
    String str1 = null;
    String str2 = null;
    userMap.put("Users.User ID",UserID);
    userMap.put("Users.Status", "Active");
    tcResultSet userResultSet = null;
    try {
    userResultSet = moUserUtility.findAllUsers(userMap);
    } catch (tcAPIException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
    for (int i=0; i<userResultSet.getRowCount(); i++)
    userResultSet.goToRow(i);
    str1 = userResultSet.getStringValue("USR_UDF_OIDUSERPROV");
    str2 = userResultSet.getStringValue("USR_UDF_EBSUSERPROV");
    // System.out.println(userResultSet.getStringValue("USR_UDF_OIDUSERPROV"));
    // System.out.println(userResultSet.getStringValue("USR_UDF_EBSUSERPROV"));
    if (str1.equals("Provisioned") && (str2.equals("Provisioned") || str2.equals("NA")))
    userMap.put("USR_UDF_OVRRSCPROVSTATUS","Provisioned");
    moUserUtility.updateUser(userResultSet,userMap);
    moUserUtility.close();
    }catch (Exception e){
    e.printStackTrace();
    ERROR:
    ERROR RMICallHandler-63 XELLERATE.SERVER - Class/Method: tcDataObj/ runEvent encounter some problems: project5.setUDFValue
    java.lang.ClassCastException: project5.setUDFValue
         at com.thortech.xl.dataobj.tcDataObj.runEvent(Unknown Source)
         at com.thortech.xl.dataobj.tcDataObj.eventPostUpdate(Unknown Source)
         at com.thortech.xl.dataobj.tcUSR.eventPostUpdate(Unknown Source)
         at com.thortech.xl.dataobj.tcDataObj.update(Unknown Source)
         at com.thortech.xl.dataobj.tcDataObj.save(Unknown Source)
         at com.thortech.xl.dataobj.tcTableDataObj.save(Unknown Source)
         at com.thortech.xl.ejb.beansimpl.tcUserOperationsBean.updateUserData(Unknown Source)
         at com.thortech.xl.ejb.beansimpl.tcUserOperationsBean.updateUser(Unknown Source)
         at com.thortech.xl.ejb.beans.tcUserOperationsSession.updateUser(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at com.evermind.server.ejb.interceptor.joinpoint.EJBJoinPointImpl.invoke(EJBJoinPointImpl.java:35)
         at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:119)
         at com.evermind.server.ejb.interceptor.system.DMSInterceptor.invoke(DMSInterceptor.java:52)
         at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:119)
         at com.evermind.server.ejb.interceptor.system.TxRequiredInterceptor.invoke(TxRequiredInterceptor.java:50)
         at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:119)
         at com.evermind.server.ejb.interceptor.system.SecurityRoleInterceptor.invoke(SecurityRoleInterceptor.java:47)
         at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:119)
         at com.evermind.server.ejb.interceptor.system.DMSInterceptor.invoke(DMSInterceptor.java:52)
         at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:119)
         at com.evermind.server.ejb.InvocationContextPool.invoke(InvocationContextPool.java:55)
         at com.evermind.server.ejb.StatelessSessionEJBObject.OC4J_invokeMethod(StatelessSessionEJBObject.java:87)
         at tcUserOperations_RemoteProxy_6ocop18.updateUser(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at com.evermind.server.rmi.RmiMethodCall.run(RmiMethodCall.java:53)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
         at java.lang.Thread.run(Thread.java:595)
    Thanks,
    - jhb.

  • 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

  • Problem with event handling

    Hello all,
    I have a problem with event handling. I have two buttons in my GUI application with the same name.They are instance variables of two different objects of the same class and are put together in the one GUI.And their actionlisteners are registered with the same GUI. How can I differentiate between these two buttons?
    To be more eloborate here is a basic definition of my classes
    class SystemPanel{
             SystemPanel(FTP ftp){ app = ftp};
             FTP app;
             private JButton b = new JButton("ChgDir");
            b.addActionListener(app);
    class FTP extends JFrame implements ActionListener{
               SystemPanel rem = new SystemPanel(this);
               SystemPanel loc = new SystemPanel(this);
               FTP(){
                       add(rem);
                       add(loc);
                       pack();
                       show();
           void actionPerformed(ActionEvent evt){
            /*HOW WILL I BE ABLE TO KNOW WHICH BUTTON WAS PRESSED AS THEY
               BOTH HAVE SAME ID AND getSouce() ?
               In this case..it if was from rem or loc ?
    }  It would be really helpful if anyone could help me in this regard..
    Thanks
    Hari Vigensh

    Hi levi,
    Thankx..
    I solved the problem ..using same concept but in a different way..
    One thing i wanted to make clear is that the two buttons are in the SAME CLASS and i am forming 2 different objects of the SAME class and then putting them in a GUI.THERE IS NO b and C. there is just two instances of b which belong to the SAME CLASS..
    So the code
    private JButton b = new JButton("ChgDir");
    b.setActionCommand ("1");
    wont work as both the instances would have the label "ChgDir" and have setActionCommand set to 1!!!!
    Actually I have an array of buttons..So I solved the prob by writting a function caled setActionCmdRemote that would just set the action commands of one object of the class differently ..here is the code
    public void setActionCommandsRemote()
         for(int i = 0 ; i <cmdButtons.length ; i++)
         cmdButtons.setActionCommand((cmdButtons[i].getText())+"Rem");
    This just adds "rem" to the existing Actioncommand and i check it as folows in my actionperformed method
         if(button.getActionCommand().equals("DeleteRem") )          
                        deleteFileRemote();
          else if(button.getActionCommand().equals("Delete") )
                     deleteFileLocal();Anyway thanx a milion for your help..this was my first posting and I was glad to get a prompt reply!!!

  • How to create event handler in project online

     how to create a remote event handler for project online...
    i want to create a event handler onprojectcreating using CSOM...need Help..

    Hi Abidulla,
    Here is a good post from UMT for you to start.
    http://www.umtsoftware.com/blog/2013/08/01/project-server-2013-remote-event-handlers/
    Hope this helps,
    Guillaume Rouyre, MBA, MCP, MCTS |

Maybe you are looking for