JRadioButton Event

Hi! I have a problem with the JRadioButton events. In my application I have a Jpanel in which I add new components when my program is run depend of the information of my dataBase. The code is the next:
void new_jPanel_attrib(...){
if(caso.equals("Query")){
ButtonGroup buttonGroup1 = new ButtonGroup();
JRadioButton jRadioButton1 = new JRadioButton();
JRadioButton jRadioButton2 = new JRadioButton();
jRadioButton1.setText("Exacto");
jRadioButton2.setText("Impreciso");
jRadioButton1.setActionCommand("Exacto");
jRadioButton2.setActionCommand("Impreciso");
this.jPanel9.add(jRadioButton1);
this.jPanel9.add(jRadioButton2);
buttonGroup1.add(jRadioButton2);
buttonGroup1.add(jRadioButton1);
JComboBox jComboBox = new JComboBox();
JTextField jTextField = new JTextField();
jTextField.setName("");
jTextField.setColumns(4);
this.jPanel4.add(jTextField);
this.jPanel4.add(jComboBox);
and I want that when the jRadioButton1 is pressed the jComboBox1 becames unEditable, and when I press the jRadioButton2 is pressed the jTextField1 becames unEditable.
I have write this function but I don�t know how to access to the components in the jPanel4 because I have created it in another function.
/** Listens to the radio buttons. */
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Exacto"))
//here I want to change the jComboBox to set it not Editable
else if (e.getActionCommand().equals("Impreciso"))
//here I want to change the jTextField to set it not Editable
}

Declare the combo box and text field as globals:class ABC implements ActionListener, ... {
    private JComboBox box;
    private JTextField field;
    public ABC () {
    public void actionPerformed (ActionEvent event) {
        if (...) {
            box.setEnabled (false);
            field.setEnabled (true);
        } else if (...) {
            box.setEnabled (true);
            field.setEnabled (false);
}Kind regards,
  Levi

Similar Messages

  • 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

  • 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)

  • Help on JRadioButton event

    While i was searching for a code sample for getting the selected radio button, I have found following method
    I have following method that returns selected radio button of a group.
        public static JRadioButton getSelection(ButtonGroup group) {
            for (java.util.Enumeration e=group.getElements(); e.hasMoreElements(); ) {
                JRadioButton b = (JRadioButton)e.nextElement();
                if (b.getModel() == group.getSelection()) {
                    return b;
            return null;
        }Now if radio button is not selected this method returns null. When i call this method to get the selected radiobutton and if radio button is not selected then it throwing nullpointerexception. How can i fix this.

    if no selection you are returning null, so test the return value
    JRadioButton rb = getSelection(...);
    if(rb == null) doSomething();
    else doSomethingElse();

  • I can't show the correct event .

    I have check again . I had written Oval, Rectangle and Line JButton.
    However, I just show circle.
    I think this parts of the code has problem :but I don't clear
    And the following has this all code(2 file) , thx a lot !
    '************************************************I'm sure problem . I guess
    clear.addActionListener(
    new ActionListener() {
    public void actionPerformed(ActionEvent e){
    repaint();
    System.out.println("Clear button is clicked");
    public void itemStateChanged(ItemEvent event){
    if (event.getSource() == oval)
    p3 = new Painter(0);
    else if (event.getSource() == oval && event.getSource() == filled)
    p3 = new Painter(1);
    else if (event.getSource() == line)
    p3 = new Painter(2);
    else if (event.getSource() == rectangle)
    p3 = new Painter(3);
    else if (event.getSource() == rectangle && event.getSource() == filled)
    p3 = new Painter(4);
    This is the following my code : thx .
    '*************************************************JavaAss2.java
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class JavaAss2 extends JFrame implements ItemListener {
    private JCheckBox filled = new JCheckBox("filled");
    private JRadioButton oval = new JRadioButton("Oval");
    private JRadioButton line = new JRadioButton("Line");
    private JRadioButton rectangle = new JRadioButton("Rectangle");
    private JButton clear = new JButton("Clear");
    private Painter p3;
    public JavaAss2() {
    setBackground(Color.gray);
    Container c = getContentPane();
    c.setLayout(new BorderLayout());
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(5, 1));
    c.add(p1, BorderLayout.EAST);
    Painter p2 = new Painter();
    p2.setLayout(new BorderLayout());
    c.add(p2, BorderLayout.CENTER);
    clear.setSize(30, 15);
    ButtonGroup btngp = new ButtonGroup();
    btngp.add(oval);
    btngp.add(line);
    btngp.add(rectangle);
    p1.add(oval);
    p1.add(line);
    p1.add(rectangle);
    p1.add(filled);
    p1.add(clear);
    oval.addItemListener(this);
    line.addItemListener(this);
    rectangle.addItemListener(this);
    filled.addItemListener(this);
    clear.addActionListener(
    new ActionListener() {
    public void actionPerformed(ActionEvent e){
    repaint();
    System.out.println("Clear button is clicked");
    public void itemStateChanged(ItemEvent event){
    if (event.getSource() == oval)
    p3 = new Painter(0);
    else if (event.getSource() == oval && event.getSource() == filled)
    p3 = new Painter(1);
    else if (event.getSource() == line)
    p3 = new Painter(2);
    else if (event.getSource() == rectangle)
    p3 = new Painter(3);
    else if (event.getSource() == rectangle && event.getSource() == filled)
    p3 = new Painter(4);
    if (oval.isSelected())
    new Painter(0);
    else if (oval.isSelected() && filled.isSelected())
    new Painter(1);
    else if (line.isSelected())
    new Painter(2);
    else if (rectangle.isSelected())
    new Painter(3);
    else if (rectangle.isSelected() && filled.isSelected())
    new Painter(4); */
    public static void main (String args[]){
    JavaAss2 javaAss2 = new JavaAss2();
    javaAss2.setTitle("Painter");
    javaAss2.setSize(500, 500);
    //javaAss2.pack();
    javaAss2.setVisible(true);
    javaAss2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    '******************************************Painter.java
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Painter extends JPanel{
    private int Oid;
    public Painter() {
    setBackground(Color.white);
    setSize(500, 500);
    public Painter(int id){
    Oid = id;
    public void paintComponent(Graphics g){
    super.paintComponent(g);
    switch(Oid) {
    case 0: g.drawOval(20, 20, 50, 50);
    System.out.println("You have chosen Oval !!!");
    break;
    case 1: g.fillOval(20, 20, 50, 50);
    System.out.println("You have chosen Oval with fill colour !!!");
    break;
    case 2: g.drawLine(100, 100, 150, 150);
    System.out.println("You have chosen Line !!!");
    break;
    case 3: g.drawRect(30, 120, 150, 75);
    System.out.println("You have chosen Rectangle !!!");
    break;
    case 4: g.fillRect(30, 120, 150, 75);
    System.out.println("You have chosen Rectangle with fill colour !!!");
    break;
    }

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class test extends JFrame implements ItemListener {
      private JCheckBox filled = new JCheckBox("filled");
      private JRadioButton oval = new JRadioButton("Oval");
      private JRadioButton line = new JRadioButton("Line");
      private JRadioButton rectangle = new JRadioButton("Rectangle");
      private JButton clear = new JButton("Clear");
      // we need these references in itemStateChanged()
      private Painter p3;
      Container c;
      public test() {
        setBackground(Color.gray);
    //    Container c = getContentPane();
        c = getContentPane();
        c.setLayout(new BorderLayout());
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(5, 1));
        c.add(p1, BorderLayout.EAST);
        // so we can use p3 in itemStateChanged()
    //    Painter p2 = new Painter();
        p3 = new Painter();
    //    p2.setLayout(new BorderLayout());
        p3.setLayout(new BorderLayout());
    //    c.add(p2, BorderLayout.CENTER);
        c.add(p3, BorderLayout.CENTER);
        clear.setSize(30, 15);
        ButtonGroup btngp = new ButtonGroup();
        btngp.add(oval);
        btngp.add(line);
        btngp.add(rectangle);
        p1.add(oval);
        p1.add(line);
        p1.add(rectangle);
        p1.add(filled);
        p1.add(clear);
        oval.addItemListener(this);
        line.addItemListener(this);
        rectangle.addItemListener(this);
        // line below >> class cast exception - because
        // in itemStateChanged we cast all events to JRadioButton
        // we really don't need a listener for the check box
        // we'll check to see if it is selected in our
        // itemStateChanged method
        //filled.addItemListener(this);
        clear.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e){
            System.out.println("Clear button is clicked");
        setLocation(300,25);
      public void itemStateChanged(ItemEvent event){
        JRadioButton button = (JRadioButton)event.getSource();
        String id = button.toString().substring(
                     button.toString().indexOf("text=") + 5,
                     button.toString().lastIndexOf("]"));
        System.out.println("id = " + id);
        c.remove(p3);
        if (button == oval) {
          if(filled.isSelected())
            p3 = new Painter(1); // fill
          else
            p3 = new Painter(0); // draw
        if (button == line)
          p3 = new Painter(2);
        if (button == rectangle) {
          if(filled.isSelected())
            p3 = new Painter(4); // fill
          else
            p3 = new Painter(3); // draw
        c.add(p3, BorderLayout.CENTER);
        c.repaint();
        c.validate();
      public class Painter extends JPanel{
        private int Oid;
        public Painter() {
          setBackground(Color.white);
          setSize(500, 500);
        public Painter(int id){
          Oid = id;
        public void paintComponent(Graphics g){
          super.paintComponent(g);
          System.out.println("Oid = " + Oid);
          switch(Oid) {
            case 0:
              g.drawOval(20, 20, 50, 50);
              System.out.println("You have chosen Oval !!!");
              break;
            case 1:
              g.fillOval(20, 20, 50, 50);
              System.out.println("You have chosen Oval with " +
                                 "fill colour !!!");
              break;
            case 2:
              g.drawLine(100, 100, 150, 150);
              System.out.println("You have chosen Line !!!");
              break;
            case 3:
              g.drawRect(30, 120, 150, 75);
              System.out.println("You have chosen Rectangle !!!");
              break;
            case 4:
              g.fillRect(30, 120, 150, 75);
              System.out.println("You have chosen Rectangle " +
                                 "with fill colour !!!");
      public static void main(String[] args) {
        test javaAss2 = new test();
    //    JavaAss2 javaAss2 = new JavaAss2();
        javaAss2.setTitle("Painter");
        javaAss2.setSize(500, 500);
        //javaAss2.pack();
        javaAss2.setVisible(true);
        javaAss2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  • Disable/Enable itemStateChanged event of JRadioButton

    Hi,
    In my program, I select the JRadioButton two ways:
    (1) Select by clicking on perticular JRadioButton
    (2) Programatically select the JRadioButton
    e.g.
    ButtonModel model;
              model = gRadioButton.getModel();
              range_group.setSelected( model, true );
    I want to ignore ( or disable ) itemStateChanged event while I select the JRadioButton programatically. And enable back.
    In short, I don't want to execute itemStateChanged event if I select the JRadioButton programatically by calling setSelected method.
    I searched net and this forum but couldn't get the solution. Please let me know.
    Thanks,

    That is helpful.
    I searched everything and I didn't find anyway to disable and enable the listener.
    So I think remove listener is the solution.

  • Event handling JRadioButton

    Just wondering, why is it when you add JRadioButtons on JMenus you are 'forced' ? to use ActionListeners instead of ItemListeners ??
    which is which? I just wanted to get things clear...

    You can add an ItemListener to JRadioButton. But the ItemListener must be added to each button, not the "group" as you would with a list.
          JRadioButton redRB = new JRadioButton("red");
          JRadioButton blueRB = new JRadioButton("blue");
          JRadioButton greenRB = new JRadioButton("green");
          ButtonGroup bg = new ButtonGroup();
          bg.add(redRB);
          bg.add(blueRB);
          bg.add(greenRB);
          ItemListener itemListener = new ItemListener()
                                        public void itemStateChanged(ItemEvent e)
                                           JRadioButton jrb = (JRadioButton)e.getSource();
                                           if (e.getStateChange() == ItemEvent.DESELECTED)
                                              System.out.println("itemStateChanged: " + jrb.getText() + " was deselected");
                                           else if (e.getStateChange() == ItemEvent.SELECTED)
                                              System.out.println("itemStateChanged: " + jrb.getText() + " was selected");
          redRB.addItemListener(itemListener);
          blueRB.addItemListener(itemListener);
          greenRB.addItemListener(itemListener);(I then went on to add the three radio buttons to a menu, added the menu to a menubar, added the menubar to a frame, and showed the frame, and it worked.)
    According to my javadoc (1.3), JRadioButtons have or inherit all these addXXXListener methods, so I am not sure what you mean by 'forced':
    addActionListener
    addChangeListener
    addItemListener
    addAncestorListener
    addPropertyChangeListener
    addVetoableChangeListener
    addContainerListener
    addComponentListener
    addFocusListener
    addHierarchyBoundsListener
    addHierarchyListener
    addInputMethodListener
    addKeyListener
    addMouseListener
    addMouseMotionListener
    /Mel

  • Help with event listener

    I'm having some trouble trying to figure out how this event listener will work.
    The main application is building an arrayCollection of a calendarDay custom components which is displayed by a DataGroup.
    Within each calendarDay custom component i may create an arrayList of a DriverDetailComponent custom components displayed within the calendarDay by a DataGroup.
    If a user double clicks on the DriverDetailComponent that is two layers in I would like to change states of the main application.  I'm having trouble figuring out what item in the main application to set the listener on.  Please help.
    I can't figure out how to post the below as scrollable code snips so this is very long.
    Main application code:
    <code><?xml version="1.0" encoding="utf-8"?>
    <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:components="components.*"
                   preinitialize="readDataFile()"
                   creationComplete="buildRowTitles()"
                   width="1024" height="512"  backgroundColor="#A4BDD8">
        <s:states>
            <s:State name="State1"/>
            <s:State name="driverDetailState"/>
        </s:states>
        <!--
        <fx:Style source="EventCalendar.css"/>
        creationComplete="readDataFile()"    creationComplete="driversList.send()"-->
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->       
            <mx:DateFormatter id="myDateFormatter"
                              formatString="EEE, MMM D, YYYY"/>
            <!--<s:HTTPService id="driversList"
                           url="files/drivers.xml"
                           result="driversList_resultHandler(event)"
                           fault="driversList_faultHandler(event)"/>
            <s:HTTPService id="postDriversList"
                           url="files/drivers.xml"
                           method="POST"
                           result="postDriversList_resultHandler(event)"
                />-->
            <!--<s:Move id="expandTab"
                    target="{labelTab}"
                    xBy="250"/>-->
        </fx:Declarations>
        <fx:Script>
            <![CDATA[
                import components.CalendarDay;
                import components.TruckDriver;
                import components.calendarDay;
                import events.CancelChangeDriversEvent;
                import events.ChangeDriversEvent;
                import events.EditDriverEvent;
                import mx.collections.ArrayCollection;
                import mx.collections.ArrayList;
                import mx.containers.Form;
                import mx.controls.Alert;
                import mx.controls.CalendarLayout;
                import mx.core.FlexGlobals;
                import mx.core.IVisualElement;
                import mx.core.WindowedApplication;
                import mx.printing.FlexPrintJob;
                import mx.rpc.events.FaultEvent;
                import mx.rpc.events.ResultEvent;
                import mx.rpc.xml.SimpleXMLEncoder;
                import spark.components.Application;
                import utilities.FormatUtil;
                import utilities.ObjectToXML;
                /* public var prefsFile:File; */ // The preferences prefsFile
                [Bindable] public var driversXML:XML; // The XML data
                public var stream:FileStream; // The FileStream object used to read and write prefsFile data.
                public var fileName:String="driversArrayCollection";
                public var directory:String = "AceTrackerData";
                public var dataFile:File = File.documentsDirectory.resolvePath(directory + "\\" + fileName);
                [Bindable]
                public var drivers:ArrayCollection=new ArrayCollection();
                private var fileStream:FileStream;
                [Bindable]
                public var calendarDayArray:ArrayCollection = new ArrayCollection;
                public var i:int;
                [Bindable]
                public var weekOneTitle:String;
                [Bindable]
                public var weekTwoTitle:String;
                [Bindable]
                public var weekThreeTitle:String;
                [Bindable]
                public var weekFourTitle:String;
                public var day:Object;
                protected function readDataFile():void
                    if(dataFile.exists)
                        fileStream = new FileStream();
                        fileStream.open(dataFile, FileMode.READ);
                        drivers = fileStream.readObject() as ArrayCollection;
                        fileStream.close();
                    else
                        drivers = new ArrayCollection();
                        var driver:TruckDriver = new TruckDriver("New", "Driver", 000);
                        drivers.addItem(driver);
                        saveData(drivers);
                    buildCalendarArray();
                protected function buildCalendarArray():void
                    calendarDayArray.removeAll();
                    for (i=0; i<28; i++)
                        var cd:calendarDay = new calendarDay;
                        cd.dateOffset= i-7
                        cd.drivers=drivers;
                         cd.addEventListener("editDriverEvent",editDriverEvent_Handler);
                        calendarDayArray.addItem(cd);
              private function saveData(obj:Object):void//this is called on the postDriversList result handler to create and write XML data to the file
                    var fs:FileStream = new FileStream();
                    fs.open(dataFile, FileMode.WRITE);
                    /* fs.writeUTFBytes(myXML); */
                    fs.writeObject(drivers);
                    fs.close();
                protected function driverschedule1_changeDriversHandler(event:ChangeDriversEvent):void
                    saveData(drivers); 
                    readDataFile();//i read the drivers file again, this refreshes my data, and removes any temporary data that may have been stored in the drivers array
                    buildCalendarArray();
                    currentState = 'State1';//this hides the driversdetail window after we've clicked save
                    /* postDriversList.send(event.driverInfo); */  //this needs to be different
                    /* Alert.show("TEST"); */
                protected function driverschedule1_cancelChangeDriversHandler(event:CancelChangeDriversEvent):void
                    /* Alert.show("Changes have been canceled."); */
                    readDataFile();//this re-reads the saved data file so that the changes that were made in the pop up window
                    // are no longer reflected if you reopen the window
                    buildCalendarArray();
                    currentState = 'State1';  //this hides the driversdetail window after we've clicked cancel
                protected function buildRowTitles():void
                    var calendarDay0:Object;
                    var calendarDay6:Object;
                    calendarDay0=calendarDayArray.getItemAt(0);
                    calendarDay6=calendarDayArray.getItemAt(6);
                    weekOneTitle = calendarDay0.getDayString() + " - " + calendarDay6.getDayString();
                    weekTwoTitle=calendarDayArray.getItemAt(7).getDayString()+ " - " + calendarDayArray.getItemAt(13).getDayString();
                    weekThreeTitle=calendarDayArray.getItemAt(14).getDayString()+ " - " + calendarDayArray.getItemAt(20).getDayString();
                    weekFourTitle=calendarDayArray.getItemAt(21).getDayString()+ " - " + calendarDayArray.getItemAt(27).getDayString();
            ]]>
        </fx:Script>
        <s:Group height="100%" width="100%">
            <s:layout>
                <s:BasicLayout/>  <!--This is the outermost layout for the main application MXML-->
            </s:layout>
        <s:Scroller width="95%" height="100%"  >
        <s:Group height="100%" width="100%"  ><!--this groups the vertically laid out row titles hoizontally with the large group of calendar days and day titles-->
            <s:layout>
                <s:HorizontalLayout/>
            </s:layout>
        <s:Group height="95%" width="50" ><!--this is the group of row titles layed out vertically-->
            <s:layout>
                <s:VerticalLayout paddingLeft="40" paddingTop="35"/>
            </s:layout>
            <s:Label text="{weekOneTitle}"
                     rotation="-90"
                     backgroundColor="#989393"
                     height="25%" width="115"
                     fontWeight="normal" fontSize="15"
                     paddingTop="4" textAlign="center"  />
            <s:Label text="{weekTwoTitle}"
                     rotation="-90"
                     backgroundColor="#989393"
                     height="25%" width="115"
                     fontWeight="normal" fontSize="15"
                     paddingTop="4" textAlign="center" />
            <s:Label text="{weekThreeTitle}"
                     rotation="-90"
                     backgroundColor="#989393"
                     height="25%" width="115"
                     fontWeight="normal" fontSize="15"
                     paddingTop="4" textAlign="center"  />
            <s:Label text="{weekFourTitle}"
                     rotation="-90"
                     backgroundColor="#989393"
                     height="25%" width="115"
                     fontWeight="normal" fontSize="15"
                     paddingTop="4" textAlign="center"  />
        </s:Group>
        <s:Group height="100%" width="100%" >
            <!--this vertically groups together the horizontal day names group and the tile layout datagroup of calendar days-->
            <s:layout>
                <s:VerticalLayout paddingLeft="5"/>
            </s:layout>
        <s:Group width="100%" >
            <s:layout><!--this group horizontal layout is for the Day names at the top-->
                <s:HorizontalLayout paddingTop="10"/>
            </s:layout>
            <s:Label id="dayNames" text="Sunday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
            <s:Label text="Monday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
            <s:Label text="Tuesday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
            <s:Label text="Wednesday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
            <s:Label text="Thursday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
            <s:Label text="Friday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
            <s:Label text="Saturday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
        </s:Group>
            <!--<s:SkinnableContainer width="16%">-->
                <s:DataGroup id="calendarDataGroup"
                             dataProvider="{calendarDayArray}"
                             itemRenderer="{null}"  resizeMode="scale"
                              height="100%" width="100%"
                              >  <!--  I had to use a null renderer because otherwise each instance is added in a group container renderers.DriverScheduleRenderer-->
                    <s:layout >
                        <s:TileLayout requestedColumnCount="7" />
                    </s:layout>
                </s:DataGroup>
            <!--</s:SkinnableContainer>-->
        <!--<mx:FormItem label="Today's Date:">
            <s:TextInput id="dateToday"
                         text="{myDateFormatter.format(testDate)}"/>
        </mx:FormItem>-->
        <!--<components:DriverSchedule drivers="{drivers}"
                                   changeDriversEvent="driverschedule1_changeDriversHandler(event)"/>-->
            <s:HGroup>  <!--this groups together my drivers button and my print button at the bottom of the calendar-->
            <s:Button id="showDriverDetailButton"
                      label="Driver List"
                      click="currentState = 'driverDetailState'">
                <!--</s:Button>
                <s:Button id="printButton"
                    label="Print"
                    >  click="printButton_clickHandler(event)"-->
                </s:Button>
            </s:HGroup>    <!--this is the end of the small hgroup which pairs my drivers button with the print button-->                  
        </s:Group><!--this ends the vertical grouping of the day names and the tile layout calendar-->   
    </s:Group>        <!--this ends the horizontal grouping of the calendar (names and days) with the week labels at the left-->
        </s:Scroller>
            <s:SkinnableContainer includeIn="driverDetailState"
                                  width="95%" height="95%"  horizontalCenter="0" verticalCenter="0"
                                  backgroundColor="#989898" backgroundAlpha="0.51">
                <s:BorderContainer horizontalCenter="0" verticalCenter="0">
                <components:DriverSchedule id="driverSchedule"
                                            drivers="{drivers}"
                                           changeDriversEvent="driverschedule1_changeDriversHandler(event)"
                                           cancelChangeDriversEvent="driverschedule1_cancelChangeDriversHandler(event)"
                                           />
                </s:BorderContainer>
            </s:SkinnableContainer>
        </s:Group>  <!--end of basic layout group-->
    </s:WindowedApplication>
    </code>
    calendarDay.mxml code:
    <code>
    <?xml version="1.0" encoding="utf-8"?>
    <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
             xmlns:s="library://ns.adobe.com/flex/spark"
             xmlns:mx="library://ns.adobe.com/flex/mx"
             creationComplete="initDay()"
              width="100%">  <!--width="16%" height="25%"  width="160" height="112"-->
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
            <mx:DateFormatter id="myDateFormatter"
                              formatString="MMM D"/>
        </fx:Declarations>
        <fx:Metadata>
            [Event(name = "editDriverEvent", type="events.EditDriverEvent")]
        </fx:Metadata>
        <fx:Script>
            <![CDATA[
                import components.CalendarDay;
                import components.DriverDetailComponent;
                import events.EditDriverEvent;
                import mx.collections.ArrayCollection;
                import mx.collections.ArrayList;
                import mx.controls.CalendarLayout;
                import mx.controls.DateField;
                [Bindable]
                public var todayCollection:ArrayCollection = new ArrayCollection;
                [Bindable]
                public var todayList:ArrayList=new ArrayList; //arraylist created as data provider for dataGroup, this is where all drivers with an arrival date of today are added
                [Bindable]
                public var currDate:Date =new Date; //this will be used to contain the current real world date
                [Bindable]
                public var calDate:Date = new Date; //this is used below to determine the date of the calender day that is being created
                [Bindable] 
                public var todaysDate:CalendarDay;
                [Bindable]
                public var currDay:int;
                [Bindable]
                public var dateOffset:int;
                public var drivers:ArrayCollection= new ArrayCollection();
                   public var driver:Object;  
                public var rowLabel:String;
                public function initDay():void
                    todaysDate  = new CalendarDay(currDate, currDate.day, dateOffset)//currDate represents the day the operating system says today is
                        currDay=todaysDate.returnDate().getDate();//currDay is an int representing the day of the month
                        calDate=todaysDate.returnDate();//calDate represents the actual date on the calendar (MM-DD-YYY) that is currently being evaluated
                        /* if (currDay ==currDate.getDate()) //i want to highlight the day if it is in fact today
                            cont.styleName="Today";
                            if (calDate.getDate() == currDate.getDate())
                            calDayBorder.setStyle("backgroundColor", "#FFFF00");
                        else
                            calDayBorder.setStyle("backgroundColor", "#EEEEEE");
                         addDrivers(); 
                    return;
                  public function addDrivers():void
                       var count:int = 0;
                      /*var driverDetail:DriverDetailComponent;
                      var driver =  */
                    for each (driver in drivers)
                    {//i check the date value based on data entry of mm-dd-yy format against the calculated date for the day
                        //the calender is building and if it is equal the drivers information is added to this day of the calendar
                        if (DateField.stringToDate(driver.arrivalDate,"MM/DD/YYYY").getDate() == calDate.getDate())
                                var driverDetail:DriverDetailComponent = new DriverDetailComponent; //i create a new visual component that adds the id and destination to the calendar day
                                driverDetail.driverid = drivers[count].id; //i feed the id property which is the truck# - firstName
                                driverDetail.driverToLoc=drivers[count].toLoc; //i feed the toLoc which is the current destination of the driver
                                driverDetail.driverArrayLocation=count;   //here i feed the location of this driver in the "drivers" array so i know where it's at for the click listener
                                todayList.addItem(driverDetail);
                            //this concatenates the drivers truck number first name and destination to display in the calendar day
                                /* todayList.addItem(driver.truckNumber + " - " + driver.firstName + " - " + driver.toLoc); */
                    count ++;
                public function getDayString():String
                    rowLabel =myDateFormatter.format(calDate);
                    return rowLabel;
            ]]>
        </fx:Script>
        <s:BorderContainer id="calDayBorder" width="160" styleName="Today" cornerRadius="2" dropShadowVisible="true" height="100%">
            <s:layout>
                <s:BasicLayout/>   
            </s:layout>
            <!--I need to make a custom item renderer for my calendar days that limits the height and width of the day, and also puts the items
            closer together so i can fit maybe 5 drivers on a single day-->
            <s:DataGroup dataProvider="{todayList}"
                         itemRenderer="spark.skins.spark.DefaultComplexItemRenderer"
                         bottom="-2"
                         width="115" left="2">  <!--width="94%"  width="100"  width="16%"-->
                <s:layout >
                    <s:VerticalLayout gap="-4"/> <!--The reduced gap pushes the drivers together if there are serveral on one day. This helps cleanly show several drivers on one day-->
                </s:layout>
            </s:DataGroup >
            <s:Label  text="{currDay}" right="3" top="2" fontSize="14" fontWeight="bold"/>
        </s:BorderContainer>
    </s:Group>
    </code>
    DriverDetailComponent code:
    <code><?xml version="1.0" encoding="utf-8"?>
    <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
             xmlns:s="library://ns.adobe.com/flex/spark"
             xmlns:mx="library://ns.adobe.com/flex/mx">
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
        <fx:Metadata>
            [Event(name = "editDriverEvent", type="events.EditDriverEvent")]
        </fx:Metadata>
        <fx:Script>
            <![CDATA[
                import events.EditDriverEvent;
                import mx.controls.Alert;
                [Bindable]
                public var driverid:String;
                [Bindable]
                public var driverArrayLocation:int;
                [Bindable]
                public var driverToLoc:String;
                protected function label1_doubleClickHandler(event:MouseEvent):void
                    Alert.show("You have selected " +driverid +" at location "  + driverArrayLocation.toString() +" in the drivers ArrayCollection.");
                    var eventObject:EditDriverEvent = new EditDriverEvent("editDriverEvent",driverArrayLocation);
                    dispatchEvent(eventObject);
            ]]>
        </fx:Script>
        <s:Label id="driverDetailLabel" text="{driverid} - {driverToLoc}"  doubleClick="label1_doubleClickHandler(event)" doubleClickEnabled="true"/>
    </s:Group>
    </code>

    lkb3 wrote:
    I'm trying to add a listener to [this JOptionPane pane dialog box|http://beidlers.net/photos/d/516-1/search_screenshot.JPG|my dialog box], so that when it pops up, the cursor is in the text box, but then if the user clicks a button other than the default, the cursor reverts back into the text box.
    The code I have is this:
      // BUILD DIALOG BOX
    JLabel option_label = new JLabel("Select a search option:");
    // Create the button objects
    JRadioButton b1 = new JRadioButton("Search PARTS by name");
    JRadioButton b2 = new JRadioButton("Search ASSEMBLIES by name");
    JRadioButton b3 = new JRadioButton("Search DRAWINGS by name");
    JRadioButton b4 = new JRadioButton("Search all by DESCRIPTION");
    b1.setSelected(true);
    // Tie them together in a group
    ButtonGroup group = new ButtonGroup();
    group.add(b1);
    group.add(b2);
    group.add(b3);
    group.add(b4);
    // Add them to a panel stacking vertically
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
    panel.add(b1);
    panel.add(b2);
    panel.add(b3);
    panel.add(b4);
    JLabel name_label = new JLabel("Enter a search term (add *'s as required)");
    JTextField name = new JTextField(30);
    name.addComponentListener(new ComponentListener() {
    public void componentHidden(ComponentEvent ce) { }
    public void componentMoved(ComponentEvent ce) { }
    public void componentResized(ComponentEvent ce) {
    ce.getComponent().requestFocus();
    public void componentShown(ComponentEvent ce) { }
    Object[] array = { option_label, panel, name_label, name };
    // GET INPUT FROM USER
    int res = JOptionPane.showConfirmDialog(null, array, "Select", JOptionPane.OK_CANCEL_OPTION);
    String searchTerm = name.getText();This sucessfully has the focus in the text box when opened; is there a way to get the focus to go back into the text box after the user clicks a radio button?
    Thanks!
    [this JOptionPane pane dialog box|http://beidlers.net/photos/d/516-1/search_screenshot.JPG|dialog Joption]
    you will need to add ItemListener to the JRadioButtons

  • Main method not found and how to put event handlers in an inner class

    How would I put all the event handling methods in an inner class and I have another class that just that is just a main function, but when i try to run the project, it says main is not found. Here are the two classes, first one sets up everything and the second one is just main.
    mport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
    private JLabel dateLabel = new JLabel("Date: ");
    private JTextField dateField = new JTextField(20);
    private JPanel datePanel = new JPanel(new FlowLayout());
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel radioPanel = new JPanel();
    JPanel statusPanel = new JPanel();
    JPanel textAreaPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    GridLayout gridLayout1 = new GridLayout();
    FlowLayout flowLayout1 = new FlowLayout();
    GridLayout gridLayout2 = new GridLayout();
    GridLayout gridLayout3 = new GridLayout();
    JRadioButton personalButton = new JRadioButton();
    JRadioButton businessButton = new JRadioButton();
    JLabel status = new JLabel();
    JTextArea entryArea = new JTextArea();
    JButton clearButton = new JButton();
    JButton saveButton = new JButton();
    ButtonGroup entryType = new ButtonGroup();
    public JournalFrame(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void initWidgets(){
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(borderLayout1);
    radioPanel.setLayout(gridLayout1);
    statusPanel.setLayout(flowLayout1);
    textAreaPanel.setLayout(gridLayout2);
    buttonPanel.setLayout(gridLayout3);
    personalButton.setSelected(true);
    personalButton.setText("Personal");
    personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
    businessButton.setText("Business");
    status.setText("");
    entryArea.setText("");
    entryArea.setColumns(10);
    entryArea.setLineWrap(true);
    entryArea.setRows(30);
    entryArea.setWrapStyleWord(true);
    clearButton.setPreferredSize(new Dimension(125, 25));
    clearButton.setText("Clear Journal Entry");
    clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
    saveButton.setText("Save Journal Entry");
    saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
    this.setTitle("Journal");
    gridLayout3.setColumns(1);
    gridLayout3.setRows(0);
    this.getContentPane().add(datePanel, BorderLayout.NORTH);
    this.getContentPane().add(radioPanel, BorderLayout.WEST);
    this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.EAST);
    entryType.add(personalButton);
    entryType.add(businessButton);
    datePanel.add(dateLabel);
    datePanel.add(dateField);
    radioPanel.add(personalButton, null);
    radioPanel.add(businessButton, null);
    textAreaPanel.add(entryArea, null);
    buttonPanel.add(clearButton, null);
    buttonPanel.add(saveButton, null);
    this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
    statusPanel.add(status, null);
    this.pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    private void saveEntry() throws IOException{
    if( personalButton.isSelected())
    String file = "Personal.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    entryArea.getText();
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    else if (businessButton.isSelected())
    String file = "Business.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    void clearButton_actionPerformed(ActionEvent e) {
    dateField.setText("");
    entryArea.setText("");
    status.setText("");
    void saveButton_actionPerformed(ActionEvent e){
    try{
    saveEntry();
    }catch(IOException error){
    status.setText("Error: Could not save journal entry");
    void personalButton_actionPerformed(ActionEvent e) {
    class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.personalButton_actionPerformed(e);
    public class JournalApp {
    public static void main(String args[])
    JournalFrame journal = new JournalFrame();
    journal.setVisible(true);
    }

    Bet you're trying "java JournalFrame" when you need to "java JournalApp".
    Couple pointers toward good code.
    1) Use white space (extra returns) to separate your code into logical "paragraphs" of thought.
    2) Add comments. At a minimum a comment at the beginning should name the file, state its purpose, identify the programmer and date written. A comment at the end should state that you've reached the end. In the middle, any non-obvious code should be commented and closing braces or parens should have a comment stating what they close (if there is non-trivial separation from where they open).
    Here's a sample:
    // JournalFrame.java - this does ???
    // saisoft, 4/18/03
    // constructor
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        radioPanel.setLayout(gridLayout1);
        statusPanel.setLayout(flowLayout1);
        textAreaPanel.setLayout(gridLayout2);
        buttonPanel.setLayout(gridLayout3);
        personalButton.setSelected(true);
        personalButton.setText("Personal");
        personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
        businessButton.setText("Business");
        status.setText("");
        entryArea.setText("");
        entryArea.setColumns(10);
        entryArea.setLineWrap(true);
        entryArea.setRows(30);
        entryArea.setWrapStyleWord(true);
    } // end constructor
    // end JournalFrame.java3) What would you expect to gain from that inner class? It might be more cool, but would it be more clear? I give the latter (clarity) a lot of importance.

  • Main method not found and how to implement events in an inner class

    How would I put all the event handling methods in an inner class and I have another class that just that is just a main function, but when i try to run the project, it says main is not found. Here are the two classes, first one sets up everything and the second one is just main.
    mport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
    private JLabel dateLabel = new JLabel("Date: ");
    private JTextField dateField = new JTextField(20);
    private JPanel datePanel = new JPanel(new FlowLayout());
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel radioPanel = new JPanel();
    JPanel statusPanel = new JPanel();
    JPanel textAreaPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    GridLayout gridLayout1 = new GridLayout();
    FlowLayout flowLayout1 = new FlowLayout();
    GridLayout gridLayout2 = new GridLayout();
    GridLayout gridLayout3 = new GridLayout();
    JRadioButton personalButton = new JRadioButton();
    JRadioButton businessButton = new JRadioButton();
    JLabel status = new JLabel();
    JTextArea entryArea = new JTextArea();
    JButton clearButton = new JButton();
    JButton saveButton = new JButton();
    ButtonGroup entryType = new ButtonGroup();
    public JournalFrame(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void initWidgets(){
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(borderLayout1);
    radioPanel.setLayout(gridLayout1);
    statusPanel.setLayout(flowLayout1);
    textAreaPanel.setLayout(gridLayout2);
    buttonPanel.setLayout(gridLayout3);
    personalButton.setSelected(true);
    personalButton.setText("Personal");
    personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
    businessButton.setText("Business");
    status.setText("");
    entryArea.setText("");
    entryArea.setColumns(10);
    entryArea.setLineWrap(true);
    entryArea.setRows(30);
    entryArea.setWrapStyleWord(true);
    clearButton.setPreferredSize(new Dimension(125, 25));
    clearButton.setText("Clear Journal Entry");
    clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
    saveButton.setText("Save Journal Entry");
    saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
    this.setTitle("Journal");
    gridLayout3.setColumns(1);
    gridLayout3.setRows(0);
    this.getContentPane().add(datePanel, BorderLayout.NORTH);
    this.getContentPane().add(radioPanel, BorderLayout.WEST);
    this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.EAST);
    entryType.add(personalButton);
    entryType.add(businessButton);
    datePanel.add(dateLabel);
    datePanel.add(dateField);
    radioPanel.add(personalButton, null);
    radioPanel.add(businessButton, null);
    textAreaPanel.add(entryArea, null);
    buttonPanel.add(clearButton, null);
    buttonPanel.add(saveButton, null);
    this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
    statusPanel.add(status, null);
    this.pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    private void saveEntry() throws IOException{
    if( personalButton.isSelected())
    String file = "Personal.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    entryArea.getText();
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    else if (businessButton.isSelected())
    String file = "Business.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    void clearButton_actionPerformed(ActionEvent e) {
    dateField.setText("");
    entryArea.setText("");
    status.setText("");
    void saveButton_actionPerformed(ActionEvent e){
    try{
    saveEntry();
    }catch(IOException error){
    status.setText("Error: Could not save journal entry");
    void personalButton_actionPerformed(ActionEvent e) {
    class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.personalButton_actionPerformed(e);
    public class JournalApp {
    public static void main(String args[])
    JournalFrame journal = new JournalFrame();
    journal.setVisible(true);
    }

    Here is the complete code (with crappy indentation) :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
        private JLabel dateLabel = new JLabel("Date: ");
        private JTextField dateField = new JTextField(20);
        private JPanel datePanel = new JPanel(new FlowLayout());
        BorderLayout borderLayout1 = new BorderLayout();
        JPanel radioPanel = new JPanel();
        JPanel statusPanel = new JPanel();
        JPanel textAreaPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
        GridLayout gridLayout1 = new GridLayout();
        FlowLayout flowLayout1 = new FlowLayout();
        GridLayout gridLayout2 = new GridLayout();
        GridLayout gridLayout3 = new GridLayout();
        JRadioButton personalButton = new JRadioButton();
        JRadioButton businessButton = new JRadioButton();
        JLabel status = new JLabel();
        JTextArea entryArea = new JTextArea();
        JButton clearButton = new JButton();
        JButton saveButton = new JButton();
        ButtonGroup entryType = new ButtonGroup();
        public JournalFrame(){
            try {
                jbInit();
            catch(Exception e){
                e.printStackTrace();
        private void initWidgets(){
        private void jbInit() throws Exception {
            this.getContentPane().setLayout(borderLayout1);
            radioPanel.setLayout(gridLayout1);
            statusPanel.setLayout(flowLayout1);
            textAreaPanel.setLayout(gridLayout2);
            buttonPanel.setLayout(gridLayout3);
            personalButton.setSelected(true);
            personalButton.setText("Personal");
            personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
            businessButton.setText("Business");
            status.setText("");
            entryArea.setText("");
            entryArea.setColumns(10);
            entryArea.setLineWrap(true);
            entryArea.setRows(30);
            entryArea.setWrapStyleWord(true);
            clearButton.setPreferredSize(new Dimension(125, 25));
            clearButton.setText("Clear Journal Entry");
            clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
            saveButton.setText("Save Journal Entry");
            saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
            this.setTitle("Journal");
            gridLayout3.setColumns(1);
            gridLayout3.setRows(0);
            this.getContentPane().add(datePanel, BorderLayout.NORTH);
            this.getContentPane().add(radioPanel, BorderLayout.WEST);
            this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
            this.getContentPane().add(buttonPanel, BorderLayout.EAST);
            entryType.add(personalButton);
            entryType.add(businessButton);
            datePanel.add(dateLabel);
            datePanel.add(dateField);
            radioPanel.add(personalButton, null);
            radioPanel.add(businessButton, null);
            textAreaPanel.add(entryArea, null);
            buttonPanel.add(clearButton, null);
            buttonPanel.add(saveButton, null);
            this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
            statusPanel.add(status, null);
            this.pack();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        private void saveEntry() throws IOException{
            if( personalButton.isSelected()){
                String file = "Personal.txt";
                BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
                entryArea.getText();
                bw.write("Date: " + dateField.getText());
                bw.newLine();
                bw.write(entryArea.getText());
                bw.newLine();
                bw.flush();
                bw.close();
                status.setText("Journal Entry Saved");
            else if (businessButton.isSelected()){
                String file = "Business.txt";
                BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
                bw.write("Date: " + dateField.getText());
                bw.newLine();
                bw.write(entryArea.getText());
                bw.newLine();
                bw.flush();
                bw.close();
                status.setText("Journal Entry Saved");
        void clearButton_actionPerformed(ActionEvent e) {
            dateField.setText("");
            entryArea.setText("");
            status.setText("");
        void saveButton_actionPerformed(ActionEvent e){
            try{saveEntry();}catch(IOException error){
                status.setText("Error: Could not save journal entry");
        void personalButton_actionPerformed(ActionEvent e) {
        class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.personalButton_actionPerformed(e);
    }BadLands

  • Help on Multiple Event Listeners

    Hi:
    How do you implement both ItemListener and ListSelectionListener in the same interface? In another word, how do I put JRadioButton, JList, JComboBox...etc,each one with its own listener in init() method? I came up with the following program. Anyone have any idea fixing the problem?
    import javax.swing.*;
    import java.awt.*; //for border layout
    import javax.swing.event.*; //for ListSelectionListener
    import java.awt.event.*;
    public class TextFormatter03 extends JApplet implements ActionListener
    private Container masterPane, slavePane, bottomPane;
    private JTextArea textPanel;
    private JScrollPane textScrollPane;
    private JRadioButton courierButton, serifButton, arialButton;
    private JList sizeList;
    private JCheckBox boldStyle,italicStyle;
    private JComboBox fontColor;
    private String colorItems[]={"Cyan","Green","Red","Blue","Magenta"};
    private String sizeItems[]={"30","28","26","24","22"};
    private String custFont;
    private int custStyle, custSize;
    public void init()
    //get the content pane to add component on to
    masterPane = this.getContentPane();
    //deal with font
    serifButton = new JRadioButton("Serif");
    serifButton.setSelected(true);
    courierButton = new JRadioButton("Courier");
    courierButton.setSelected(false);
    arialButton = new JRadioButton("Arial");
    arialButton.setSelected(false);
    //group the radio buttons
    ButtonGroup group= new ButtonGroup();
    group.add(serifButton);
    group.add(courierButton);
    group.add(arialButton);
    //register a listener for the radio buttons
    serifButton.addActionListener(this);
    courierButton.addActionListener(this);
    arialButton.addActionListener(this);
    masterPane.add(group, BorderLayout.NORTH);
    //deal with font size
    sizeList = new JList (sizeItems);
    sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    sizeList.addListSelectionListener(this);
    slavePane = new JScrollPane(sizeList,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    masterPane.add(slavePane, BorderLayout.WEST);
    //display text
    textPanel= new JTextArea();
    textPanel.setText("Select options to modify this text.");
    textPanel.setBackground(Color.WHITE);
    textPanel.setLineWrap(true);
    textScrollPane = new JScrollPane(textPanel);
    masterPane.add(textScrollPane, BorderLayout.CENTER);
    textPanel.setFont(new Font("Serif",3,15));
    //deal with font color
    fontColor= new JComboBox(colorItems);
    masterPane.add(fontColor);
    //deal with font style
    boldStyle = new JCheckBox("Bold");
    boldStyle.setSelected(false);
    boldStyle.addItemListener(this);
    bottomPane.add(boldStyle);
    italicStyle = new JCheckBox("Italic");
    italicStyle.setSelected(false);
    italicStyle.addItemListener(this);
    bottomPane.add(italicStyle);
    add(bottomPane, BorderLayout.SOUTH);      
    public void actionPerformed(ActionEvent e)
         String Selected = "result";
         //set the font
         if(serifButton.isSelected())
              custFont="Serif";
         if(arialButton.isSelected())
              custFont="Arial";
         if(courierButton.isSelected())
              custFont="Courier";
         //set font style
         if(boldStyle.isSelected())
              custStyle = Font.BOLD;
         if(italicStyle.isSelected())
              custStyle = Font.ITALIC;
         if(boldStyle.isSelected()&&italicStyle.isSelected())
              custStyle = Font.BOLD + Font.ITALIC;
    public void valueChanged(ListSelectionEvent event)
         String response = "";
         //set the font size
         if(sizeList.getSelectedIndex()!=-1)
              switch (sizeList.getSelectedIndex())
                   case 0:
                        custSize = 30;
                        break;
                   case 1:
                        custSize = 28;
                        break;
                   case 2:
                   custSize = 26;
                   break;     
                   case 3:
                   custSize = 24;
                   break;     
                   case 4:
                   custSize = 22;
                   break;     
                   textPanel.setFont(new Font (custFont, custStyle,custSize));
         //set font color
         if(fontColor.getSelectedItem()=="Cyan")
              textPanel.setForeground(Color.CYAN);
         if(fontColor.getSelectedItem()=="Cyan")
              textPanel.setForeground(Color.CYAN);
         if(fontColor.getSelectedItem()=="Cyan")
              textPanel.setForeground(Color.CYAN);
         if(fontColor.getSelectedItem()=="Green")
              textPanel.setForeground(Color.GREEN);
         if(fontColor.getSelectedItem()=="Red")
              textPanel.setForeground(Color.RED);
         if(fontColor.getSelectedItem()=="Blue")
              textPanel.setForeground(Color.BLUE);
         if(fontColor.getSelectedItem()=="Magenta")
              textPanel.setForeground(Color.MAGENTA);
    }

    Help. The program didn't compile. I followed what you suggested. Here are the program and the error message.
    import javax.swing.*;
    import java.awt.*; //for border layout
    import javax.swing.event.*; //for ListSelectionListener
    import java.awt.event.*;
    public class TextFormatter03 extends JApplet implements ActionListener, ItemListener,ListSelectionListener
    private Container masterPane, slavePane, bottomPane;
    private JTextArea textPanel;
    private JScrollPane textScrollPane;
    private JRadioButton courierButton, serifButton, arialButton;
    private JList sizeList;
    private JCheckBox boldStyle,italicStyle;
    private JComboBox fontColor;
    private String colorItems[]={"Cyan","Green","Red","Blue","Magenta"};
    private String sizeItems[]={"30","28","26","24","22"};
    private String custFont;
    private int custStyle, custSize;
    public void init()
    //get the content pane to add component on to
    masterPane = this.getContentPane();
    //deal with font
    serifButton = new JRadioButton("Serif");
    serifButton.setSelected(true);
    courierButton = new JRadioButton("Courier");
    courierButton.setSelected(false);
    arialButton = new JRadioButton("Arial");
    arialButton.setSelected(false);
    //group the radio buttons
    ButtonGroup group= new ButtonGroup();
    group.add(serifButton);
    group.add(courierButton);
    group.add(arialButton);
    //register a listener for the radio buttons
    serifButton.addActionListener(this);
    courierButton.addActionListener(this);
    arialButton.addActionListener(this);
    masterPane.add(group, BorderLayout.NORTH);
    //deal with font size
    sizeList = new JList (sizeItems);
    sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    sizeList.addListSelectionListener(this);
    slavePane = new JScrollPane(sizeList,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    masterPane.add(slavePane, BorderLayout.WEST);
    //display text
    textPanel= new JTextArea();
    textPanel.setText("Select options to modify this text.");
    textPanel.setBackground(Color.WHITE);
    textPanel.setLineWrap(true);
    textScrollPane = new JScrollPane(textPanel);
    masterPane.add(textScrollPane, BorderLayout.CENTER);
    textPanel.setFont(new Font("Serif",3,15));
    //deal with font color
    fontColor= new JComboBox(colorItems);
    masterPane.add(fontColor);
    //deal with font style
    boldStyle = new JCheckBox("Bold");
    boldStyle.setSelected(false);
    boldStyle.addItemListener(this);
    bottomPane.add(boldStyle);
    italicStyle = new JCheckBox("Italic");
    italicStyle.setSelected(false);
    italicStyle.addItemListener(this);
    bottomPane.add(italicStyle);
    add(bottomPane, BorderLayout.SOUTH);      
    public void actionPerformed(ActionEvent e)
         String Selected = "result";
         //set the font
         if(serifButton.isSelected())
              custFont="Serif";
         if(arialButton.isSelected())
              custFont="Arial";
         if(courierButton.isSelected())
              custFont="Courier";
         //set font style
         if(boldStyle.isSelected())
              custStyle = Font.BOLD;
         if(italicStyle.isSelected())
              custStyle = Font.ITALIC;
         if(boldStyle.isSelected()&&italicStyle.isSelected())
              custStyle = Font.BOLD + Font.ITALIC;
    public void valueChanged(ListSelectionEvent event)
         String response = "";
         //set the font size
         if(sizeList.getSelectedIndex()!=-1)
              switch (sizeList.getSelectedIndex())
                   case 0:
                        custSize = 30;
                        break;
                   case 1:
                        custSize = 28;
                        break;
                   case 2:
                   custSize = 26;
                   break;     
                   case 3:
                   custSize = 24;
                   break;     
                   case 4:
                   custSize = 22;
                   break;     
                   textPanel.setFont(new Font (custFont, custStyle,custSize));
         //set font color
         if(fontColor.getSelectedItem()=="Cyan")
              textPanel.setForeground(Color.CYAN);
         if(fontColor.getSelectedItem()=="Cyan")
              textPanel.setForeground(Color.CYAN);
         if(fontColor.getSelectedItem()=="Cyan")
              textPanel.setForeground(Color.CYAN);
         if(fontColor.getSelectedItem()=="Green")
              textPanel.setForeground(Color.GREEN);
         if(fontColor.getSelectedItem()=="Red")
              textPanel.setForeground(Color.RED);
         if(fontColor.getSelectedItem()=="Blue")
              textPanel.setForeground(Color.BLUE);
         if(fontColor.getSelectedItem()=="Magenta")
              textPanel.setForeground(Color.MAGENTA);
    TextFormatter03.java:6: TextFormatter03 should be declared abstract; it does not define itemStateChanged(java.awt.event.ItemEvent) in TextFormatter03
    public class TextFormatter03 extends JApplet implements ActionListener, ItemListener,ListSelectionListener
    ^
    java:44: cannot resolve symbol
    symbol : method add (javax.swing.ButtonGroup,java.lang.String)
    location: class java.awt.Container
    masterPane.add(group, BorderLayout.NORTH);
    ^
    2 errors
    Process completed.

  • JTabbedpane with JRadiobutton?

    I have a JTabbedpane with 2 tabs (tab1, tab2).
    I have 2 radiobutton (JRadioButton).
    So for now, i want to when i click on radiobutton1 it will be show tab1
    when i click on radiobutton2 it will be show tab2.
    Here is my source code, please help me to slove it:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    public class JTablePaneTest extends JFrame implements ActionListener{
    private JTabbedPane pane;
    private JRadioButton radioButton1 = new JRadioButton("Radiobutton1", true);
    private JRadioButton radioButton2 = new JRadioButton("Radiobutton2", false);
    JPanel radioPanel =null;
    public JTablePaneTest() {
    super("TEST");
    this.setLayout(new BorderLayout());
    this.setSize(new Dimension(300,300));
    this.getContentPane().add(this.getAllRadioButton(), BorderLayout.SOUTH);
    this.getContentPane().add(this.getPane(), BorderLayout.CENTER);
    this.pack();
    this.setVisible(true);
    private JPanel getAllRadioButton(){
    if(radioPanel==null){
    radioPanel = new JPanel();
    radioPanel.setLayout(new FlowLayout());
    radioPanel.setBorder(BorderFactory.createEmptyBorder());
    ButtonGroup bg = new ButtonGroup();
    bg.add(radioButton1);
    bg.add(radioButton2);
    radioPanel.add(radioButton1);
    radioPanel.add(radioButton2);
    return radioPanel;
    private JTabbedPane getPane(){
    if(pane == null){
    pane = new JTabbedPane();
    pane.addTab("Tab1", null, panel1(), "Tab1");
    pane.addTab("Tab2", null, panel2(), "Tab2");
    return pane;
    private JPanel panel1(){
    JPanel panel1 = new JPanel();
    panel1.setLayout(new GridBagLayout());
    panel1.add(new JButton("TEST1"));
    return panel1;
    private JPanel panel2(){
    JPanel panel2 = new JPanel();
    panel2.setLayout(new GridBagLayout());
    panel2.add(new JTextField(12));
    return panel2;
    public static void main(String[] args) {
    new JTablePaneTest();
    @Override
    public void actionPerformed(ActionEvent e) {
    if(e.getSource() == radioButton1){
    //show tab1
    if(e.getSource() == radioButton2){
    //show tab2
    }Thanks you very much.
    Edited by: ecard104 on Sep 1, 2008 10:01 AM

    ecard104 wrote:
    can you tell me the method you want to say?I'd prefer to have you look at the API and the tutorial. It would be better for you in the long run. It's spelled out in the tutorial.
    [http://java.sun.com/docs/books/tutorial/uiswing/components/tabbedpane.html]
    [http://java.sun.com/javase/6/docs/api/javax/swing/JTabbedPane.html]
    Edited by: Encephalopathic on Sep 1, 2008 10:17 AM

  • Using JOptionPane in a non-event dispatching thread

    I am currently working on a screen that will need to called and displayed from a non-event dispatching thread. This dialog will also capture a user's selection and then use that information for later processing. Therefore, the dialog will need to halt the current thread until the user responds.
    To start, I tried using the JOptionPane.showInputDialog() method and set the options to a couple of objects. JOptionPane worked as advertised. It placed the objects into a combobox and allowed the user to select one of them. However, it also gave me something unexpected. It actually paused the non-event handling thread until the user had made a selection. This was done without the JOptionPane code being wrapped in a SwingUtilities.invokeLater() or some other device that would force it to be launched from an Event Handling Thread.
    Encouraged, I proceeded to use JOptionPane.showInputDialog() substituting the "message" Object with a fairly complex panel (JRadioButtons, JLists, JTextFields, etc.) that would display all of the variety of choices for the user. Now, when the screen pops up, it doesn't paint correctly (like what commonly occurs when try to perform a GUI update from a non-event dispatching thread) and the original thread continues without waiting for a user selection (which could be made if the screen painted correctly).
    So, here come the questions:
    1) Is what I am trying to do possible? Is it possible to create a fairly complex GUI panel and use it in one of the static JOptionPane.showXXXDialog() methods?
    2) If I can't use JOptionPane for this, should I be able to use JDialog to perform the same type function?
    3) If I can use JDialog or JFrame and get the threading done properly, how do I get the original thread to wait for the user to make a selection before proceeding?
    I have been working with Java and Swing for about 7-8 years and have done some fairly complex GUIs, but for some reason, I am stumped here. Any help would be appreciated.
    Thanks.

    This seems wierd that it is functioning this way. Generally, this is what is supposed to happen. If you call a JOptionPane.show... from the Event Dispatch Thread, the JOptionPane will actually begin processing events that normally the Event Dispatch Thread would handle. It does this until the user selects on options.
    If you call it from another thread, it uses the standard wait and notify.
    It could be that you are using showInputDialog for this, try showMessageDialog and see if that works. I believe showInputDialog is generally used for a single JTextField and JLabel.

  • How to detect if text has been clipped in a JRadioButton ?

    Hi,
    Is there any way to test if the text in a JRadioButton (same holds e.g. for a JCheckBox) has been clipped and contains ellipses ... at the end. For a JLabel, knowing the FontMetrics one can use SwingUtilities.computeStringWidth(). I found the method SwingUtilities.layoutCompoundLabel() but it needs to know also the icon, which is not available by getIcon(), if not explicitly set with setIcon() in the JRadioButton.
    So, is there any way to get info about the default icon used by the current UI in a JRadioButton or JCheckBox ?
    Or better, is there any convenience method I've overseen which may lead to the goal.
    Background info:
    The text for the JRadioButtons (or JCheckBoxes) are read from a database and Tooltips should only be generated, when clipping occured, as a popup with the same text as in the base component doesn't provide so much new information.
    Thanks for your help
    ThomasGrewe

    Hi,
    your problem could be have a solution when you use a right layout manager. You have to use a layout manager wich use the preferredSize from the objects.
    I tryed this code and work, with a BoxLayout. I dont understand yor Problem, maybe you have to write your code here (if it is not too long ;) )
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    public class Test extends JFrame{
      private String[] text;
      private int index = 0;
      private MyRadioButton rb;
      public Test(){
        text = new String[]{"Loooooooooooooooong", "mittttel", "Small", "1"};
        JButton changeText = new JButton("Change Text");
        rb = new MyRadioButton("Radio Button");
        changeText.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
            if(index >= text.length)
              index = 0;
            rb.setText(text[index++]);
            rb.invalidate();
        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
        getContentPane().add(changeText);
        getContentPane().add(rb);
      public static void main(String args[]){
        Test f = new Test();
        f.setSize(100,100);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    class MyRadioButton extends JRadioButton{
      public MyRadioButton(String text) {
        super(text);
      // your business methods...
      // set preferred, min, max size
      public Dimension getPreferredSize(){
        // let the UI compute the preferredSize
        return getUI().getPreferredSize(this);
      public Dimension getMinimumSize(){
        return getPreferredSize();
      public Dimension getMaximumSize(){
        return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
    }

  • Stopped dead with event handling

    ive made a program that has one button, two radio buttons, and a text field....when u click on the radio button is either paints a square or a circle to the screen...im having problems with tieing the textfield and the button..which is called "Enter" together....the point is to read numbers out of the textfield..and change the image size when the user hits enter...ive been working on this for some time...if anyone can possibly help me out, point me in a direction..anything, id be in your debt. Thanks...
    /***************************first part - main execution of applet******/
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Medium extends JApplet {
         private JButton enterButton;
         private JTextField textField;
         private JPanel buttonPanel;
         ButtonGroup group;
         JRadioButton circle;
         JRadioButton square;
         Label textfieldLabel;
         private DrawPanel drawingPanel;
         public void init() {
              drawingPanel = new DrawPanel();
              drawingPanel.setBackground( Color.black );
              enterButton = new JButton( "Enter" );
              enterButton.setBackground( Color.red );
              enterButton.addActionListener(
                   new ActionListener() {
                        public void actionPerformed( ActionEvent event ) {
                             drawingPanel.enterButtonMethod();
              textField = new JTextField( 10 );
              textField.setBackground( Color.red );
              textField.addActionListener (
                   new ActionListener() {
                        public void actionPerformed( ActionEvent event ) {
                             if( event.getText() ==
              circle = new JRadioButton( "Circle" );
              circle.setMnemonic( KeyEvent.VK_C );
              circle.addItemListener(
                   new ItemListener() {
                        public void itemStateChanged( ItemEvent event ) {
                             if( event.getStateChange() == ItemEvent.SELECTED )
                                  drawingPanel.showCircle();
                             else     if( event.getStateChange() == ItemEvent.DESELECTED )
                                       drawingPanel.selectorEqualsFalse();
              square = new JRadioButton( "Square" );
              square.setMnemonic( KeyEvent.VK_S );
              square.addItemListener(
                   new ItemListener() {
                        public void itemStateChanged( ItemEvent event ) {
                             if( event.getStateChange() == ItemEvent.SELECTED )                    
                                  drawingPanel.showSquare();
                             else     if( event.getStateChange() == ItemEvent.DESELECTED )
                                       drawingPanel.selectorEqualsFalse();
              textfieldLabel = new Label( "Change Object Size:" );
              textfieldLabel.setBackground( Color.red );
              group = new ButtonGroup();
              group.add( square );
              group.add( circle );          
              buttonPanel = new JPanel();
              buttonPanel.setLayout( new GridLayout( 2, 3 ) );
              buttonPanel.add( enterButton );
              buttonPanel.add( textfieldLabel );
              buttonPanel.add( textField );
              buttonPanel.add( circle );
              buttonPanel.add( square );
              Container container = getContentPane();
              container.add( buttonPanel, BorderLayout.SOUTH );
              container.add( drawingPanel, BorderLayout.CENTER );
              setSize( 400, 400 );
              setVisible( true );
    /*************************DrawPanel.java - 2nd part of applet******/
    import java.awt.*;
    import javax.swing.*;
    class DrawPanel extends JPanel {
         private int selector = 0;
         private int SQUARE = 1, CIRCLE = 2;
         private int sizeModifier = 50;
         public void paintComponent( Graphics g ) {
              super.paintComponent( g );
              if( selector == SQUARE ) {
                   g.setColor( Color.red );
                   g.fillRect( 50, 10, sizeModifier, sizeModifier );
              else     if( selector == CIRCLE ) {
                        g.setColor( Color.green );
                        g.fillOval( 50, 10, sizeModifier, sizeModifier );
              else     if( selector == 0 ) {
                        g.setColor( Color.white );
                        g.drawString( "Yo Yo, Brotha, do some selections man!", 50, 50 );
         public void enterButtonMethod() {          
              this.repaint();
         public void textFieldMethod() {
              this.repaint();
         public void showCircle() {
              selector = 2;
              this.repaint();
         public void showSquare() {
              selector = 1;
              this.repaint();          
         public void selectorEqualsFalse() {
              selector = 0;
              this.repaint();
    }

    nevermind i figured it out...it seems that i had to get ride of the second class and add it to the first file...then u wouldn't have to send an object to receive methods from DrawPanel...and the enter button just had to called with the sizemodifier to change the size and also to setText() in the textField area......"Its the small things in life that kill u......"
    if anyone has any feed back on my code please feel free to rip it open..

Maybe you are looking for

  • Error Generating Chart on Windows XP professional

    Good day all, I do not understand why I can not create charts, I can view the data in tables and perform other operations but I cal not view charts using the available data. Any time i try it, the error comes up Error Generating Chart An error occurr

  • Create Installer and disable reboot now

    I'm building a couple of installers, and both of them ask me to restart after I install them on a non-LabVIEW computer. They contain the LabVIEW RTE as well as NI-VISA runtime components. I've noticed that I can install them and click "Restart Later"

  • IPhoto Book turnaround time & sharing question

    I can't seem to find where it says what the turnaround time is for the iPhoto book. Does anyone know where this information is? Or, can I just order it 2 day delivery & it will be here in 2 days? Also, we are making one for my mother's 65th bday but

  • Unable to calculate text snippet height

    Hello, I am trying to dinamically adjust the size (height) of a container so a text snippet doesn't move to the next container. In other words I try to make sure that this exact snippet belongs to only one container. The way I try to achieve it is by

  • Veiwing mailbox sizes in exchange 2007

    Is it me or is Exchange 2007 missing mailbox size? i cant anywhere to veiw the size of a users mailbox.