JRadioButton.setSelected( false ) ?

First of all, I just read the thread "Secret source of answers to your problems...." and want to assure anyone reading this that I have been looking at the Java API all morning and I'm ready to rip this Java textbook into shreds.
I have a homework assignment and while I am not asking anyone to do my homework for me, I have run up against a brick wall. I have two sets of JRadioButtons (using two ButtonGroups). I also have two JButtons - one of which I want to use to clear the form, including clearing the JRadioButton selections.
According to the API - I should be able to set a radio button's "selected" to false. But it isn't working for me.
Here is the snippet of code I am using in my ActionListener event handler for the Clear button. All of it works except for the setSelected method call:
if ( event.getSource() == clearButton )
    tempField.setText( "" );            // clear text field
    inCelButton.setSelected( false );  // clear radio button
    inFahButton.setSelected( false );  // selections
    inKelButton.setSelected( false );  // inButton Group
    inCelButton.setVisible( true );    // set radio buttons
    inFahButton.setVisible( true );    // to visible
    inKelButton.setVisible( true );
    outCelButton.setSelected( false ); // clear radio button
    outFahButton.setSelected( false ); // selections
    outKelButton.setSelected( false ); // outButton Group
    outCelButton.setVisible( true );   // set radio buttons
    outFahButton.setVisible( true );   // to visible
    outKelButton.setVisible( true );
    results="";                        // clear results string
    resultsLabel.setText("");          // clear results label
}TIA
Sheryl McKenna

It's not necessarily true that you have to have a button selected. It only works this way when you use a buttongroup. The buttongroup insists that one button be selected when all others are off. This is the API information (Which it sounds like you are already familiar with)
"Initially, all buttons in the group are unselected. Once any button is selected, one button is always selected in the group. There is no way to turn a button programmatically to "off", in order to clear the button group. To give the appearance of "none selected", add an invisible radio button to the group and then programmatically select that button to turn off all the displayed radio buttons. For example, a normal button with the label "none" could be wired to select the invisible radio button."
I just wrote a simple app to test this and it worked fine for me. The button group ensures you can't select multiple buttons. After you select one, all others are automatically de-selected. If you are really set on using a group of buttons, without the buttonGroup then I would add a panel, set the layout to null and then just add the buttons. Netbeans is a great way to test your UI without writing a lot of code and see the end results quickly. It's free and it's available at:
http://www.netbeans.org.

Similar Messages

  • JRadioButton.setSelected(false) doesn't work?

    Hey there. I usually answer questions in this forum but this time I have a question myself. I'm trying to de-select JRadioButtons in a ButtonGroup but it's not working. I've searched the forum but didn't find anything. Here's the very simple code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ButtonTest extends JFrame {
      JRadioButton rb1 = new JRadioButton("button1", true);
      JRadioButton rb2 = new JRadioButton("button2");
      ButtonGroup bgroup = new ButtonGroup();
      JButton b = new JButton("clear");
      ButtonTest() {
        b.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            clearbuttons();
        bgroup.add(rb1);
        bgroup.add(rb2);
        Container c = getContentPane();
        c.setLayout(new GridLayout(2,2));
        c.add(rb1);
        c.add(rb2);
        c.add(b);
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
      void clearbuttons() {
        Component [] components = getContentPane().getComponents();
        for (int i = 0; i < components.length; i++) {
          Component c = components[ i ];
    System.out.println(c);
          if (c instanceof JRadioButton) {
            JRadioButton rb = (JRadioButton) c;
            rb.setSelected(false);  // once.
            bgroup.setSelected(rb.getModel(), false);  // twice.
    System.out.println("\ncalled setSelected\n");
      public static void main (String[]a) {
        ButtonTest b = new ButtonTest();
        b.setSize(200,100);
        b.setVisible(true);
    }Anybody know why the selected button remains selected?

    The ButtonGroup ensures that one JRadioButton is always selected, at least after the first one is initially selected. The workaround to fix this is to add an additional "dummy" JRadioButton to the ButtonGroup, and have your code select it when you want to deselect the rest of the buttons. The dummy JRadioButton doesn't need to be added to the GUI or displayed, or anything.

  • JRadioButton setSelected problem

    Hi,
    I am trying to change the status of my JRadio buttons to false, but they do not get updated. One of them still remains selected.
    Any ideas?
    radioButton1.setSelected(false);
    radioButton2.setSelected(false);

    devboris wrote:
    I am trying to change the status of my JRadio buttons to false, but they do not get updated. One of them still remains selected.
    Any ideas?
    radioButton1.setSelected(false);
    radioButton2.setSelected(false);
    This should be posted in the Swing forum, not the Java 2D forum.
    Regardless, if you are using Java 1.6, then I recommend that you call clearSelection on the ButtonGroup object. If you are not using Java 1.6, then you can always add to your button group another invisible jradiobutton and set its selected property to true.

  • JRadioButton setEnable(false) not refreshing correctly

    I have a JFrame class that implements customerConfigurationPanel with a ComboBox with 2 Radio Buttons in a button group. I have created a CustomerConfiguration class that represents the cutomerConfigurationPanel. The JFrame class is an Observer of the CustomerConfiguration class. Here is where it gets tricky, I use the JComboBox to set the CustomerConfiguration class and when I do a setVar() it notifies the JFrame class that it has been updated. At this point I enable or disable the RadioButton based on the CustomerConfiguration class. The issue is that the RadioButtons do not grey out correctly or in any pattern that I can tell. I have tried repaint on the JFrame and the panel, I have tried validate(), invalidate(), and revalidate() to stop and start the panel while I am updating the JRadio Buttons. I need to stop the JFrame or Panel, set the state of the JRadio Buttons, and start the panel again. I have a lot of code in place so its not very easy to put an example in place but Ill start working on it to give an example.
    The problem in its most basic form is that I have a JRadio Button in a button group that doenst grey out correctly.

    Here is a sample of the code I am using: I have a button that may or may not be setSelected in a previous state. So I want to clear the button state and reset it to the new state. In this example I have a radioButton group Truck/Trailer and I want to clear both buttons, set Trailer so it is not selected and then not enabled and then set Enable Truck and select truck. I belive the code is correct but the behavior is not. I have this same code just 10 lines later in my program and it works everytime. I think its a timing issue with repainting of the container somehow. Also if I use isVisible() instead of setEnabled() it works everytime.
    jrbTrailer.setEnabled(true);
    jrbTrailer.setSelected(false);
    jrbTrailer.setEnabled(false);
    jrbTruck.setSelected(true);
    // None of these work
    //jrbTrailer.repaint()
    //jrbTrailer.revalidate()
    //jrbTrailer.validate()

  • Need help on JRadioButton

    Hi,
    I'd like to change the state of a JRadioButton by code and I don't know how to do. I've watched the API for JRadioButton and there's no method like a jrb.setState( true ), or something like that.
    I don't really understand if I have to use the getAccessibleContext to set a property, and if I have to I don't know how, so would you please help me a bit ???
    Thanks in advance !!!

    try this method:jRadioButton.setSelected(false); // or true cheers,
    kelysar

  • Please help me with centering a component and clearing a JRadioButton

    Hi, could someone help me to cener the label and clear the selected JRadioButton?
    I have put a comment beside the problematic place. Thanks a lot! ann
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class ButtonAction extends JPanel implements ActionListener {
         private JRadioButton button1, button2;
         private JButton send, clear;
         private JTextField text;
         private JLabel label;
         private ButtonGroup group;
         public ButtonAction() {
              setPreferredSize(new Dimension(300, 200));
              setLayout(new GridLayout(0, 1, 5, 5));
            setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            setBorder(BorderFactory.createLineBorder(Color.blue));
            JPanel p1 = new JPanel();
            button1 = new JRadioButton("Button One");
              button2 = new JRadioButton("Button Two");
              group = new ButtonGroup();
              group.add(button1);
              group.add(button2);
              p1.add(button1);
              p1.add(button2);
              JPanel p2 = new JPanel();
              send = new JButton("Send");
              clear = new JButton("Clear");
              label = new JLabel(" ");
              label.setAlignmentX(Component.CENTER_ALIGNMENT);    //this doesn't work
              send.addActionListener(this);
              clear.addActionListener(this);
              p2.add(send);p2.add(clear);
              add(p1); add(p2); add(label);
         public void DisplayGUI(){
              JFrame frame = new JFrame();
              frame.getContentPane().add(this);
              frame.pack();
              frame.setVisible(true);
         public String getButton(){
              String result = "";
              if (button1.isSelected())
                   result += "\t You have clicked the first button";
              else if (button2.isSelected())
                   result += "\t You have clicked the second button";
              return result;
         public void setButton(){                  // this method doesn't work
              if (button1.isSelected() == true)
                   button1.setSelected(false);
              else if (button2.isSelected() == true)
                   button2.setSelected(false);
         public void actionPerformed (ActionEvent e) {
              if (e.getSource() == send) {
                   label.setText(getButton());
              else if (e.getSource() == clear) {
                   setButton();
                   label.setText("no button is selected");
         public static void main(String[] args) {
              ButtonAction ba = new ButtonAction();
              ba.DisplayGUI();
    }

    setHorizontalAlignmentX(Component.CENTER_ALIGNMENT) is a container method and I don't think it does what you think. Try this instead:label = new JLabel("Some text");
    //label.setHorizontalAlignmentX(Component.CENTER_ALIGNMENT);    //this doesn't work
    label.setHorizontalAlignment(SwingConstants.CENTER);When you alter the state of a radio button you should probably use the group methods - because the group "coordinates" the state of the buttons as a whole. Note that setSelection() isn't quite like a user click in that it doesn't fire a method. Now, in your case you are essentially clearing the selection of the group and ButtonGroup provides a method for that.     public void setButton(){                  // this method doesn't work
        if (button1.isSelected() == true)
        button1.setSelected(false);
        else if (button2.isSelected() == true)
        button2.setSelected(false);
        group.clearSelection();
    }Note we don't usually write if(foo == true), it's enough to say if(foo).
    You will get better and faster help from the Swing forum and it helps everyone if posts are made to the right place. http://forum.java.sun.com/forum.jspa?forumID=57

  • True or False using RadioCheckbox - need help ASAP

    So I've been working my way through java with self-study. Our teacher gave us knoweldge not applicable to what he's asked us for our project (except logic). Basically, he wants us to present questions, have the user answer them, then show the number of correct answers.
    I'm now using checkboxes in a True or False 10-item test. I once used buttons, but I gave up and went to checkboxes. I managed to display them using this:
    Parameters:
    tofp = true or false panel
    tofql = true or false question label
    tofqp = true or false question panel
         if(e.getActionCommand().equals("True or False"))
              f2.hide();
              JPanel tofp = new JPanel();
              JPanel tofp2 = new JPanel();
              JPanel tofqp = new JPanel();
              JPanel tofqp2 = new JPanel();
              JPanel tofqp3 = new JPanel();
              JPanel tofqp4 = new JPanel();
              JPanel tofqp5 = new JPanel();
              JPanel tofqp6 = new JPanel();
              JPanel tofqp7 = new JPanel();
              JPanel tofqp8 = new JPanel();
              JPanel tofqp9 = new JPanel();
              JPanel tofqp10 = new JPanel();
              FormPanel3 = new JPanel();
              JLabel tof = new JLabel("<html><Font size=5>TRUE OR FALSE</font> </html>");
              JLabel tofql1 = new JLabel("<html>1. CFC, found in refrigerator and <P> aircons , means Chlorofluorinechloride.</html>");
              JLabel tofql2 = new JLabel("<html>2. Endangered species are species <P> that are less in number and are nearly extinct.</html>");
              JLabel tofql3 = new JLabel("<html>3. The smallest fish in the world <P>is the sardines. </html>");
              JLabel tofql4 = new JLabel("<html>4. The agents of soil erosion are <P>wind, water, and human.</html>");
              JLabel tofql5 = new JLabel("<html>5. One way of conversing energy is <P> by using fluorescent light.</html>");
              JLabel tofql6 = new JLabel("<html>6. The use of dynamite is a legal method <P> of fishing.</html>");
              JLabel tofql7 = new JLabel("<html>7. Windmill is an example of a potential <P>energy.</html>");
              JLabel tofql8 = new JLabel("<html>8. Tamaraws are found in Mindanao.</html>");
              JLabel tofql9 = new JLabel("<html>9. Mining causes minimum destruction to <P> our environment.</html>");
              JLabel tofql10 = new JLabel("<html>10. The Philippines is called the Pacific <P>Ring of Fire because of the many <P> volcanoes surrounding it.</html>");
                b4 = new JButton("Submit");
                b4.addActionListener(this);
              tofp.setPreferredSize(new Dimension(400,550));
              tofqp.add(tofql1);
              tofqp2.add(tofql2);
              tofqp3.add(tofql3);
              tofqp4.add(tofql4);
              tofqp5.add(tofql5);
              tofqp6.add(tofql6);
              tofqp7.add(tofql7);
              tofqp8.add(tofql8);
              tofqp9.add(tofql9);
              tofqp10.add(tofql10);
              tofp.add(tof);
              tofp.setBackground(Color.yellow);
              tofp.add(tofqp);
              tofp.add(tofqp2);
              tofp.add(tofqp3);
              tofp.add(tofqp4);
              tofp.add(tofqp5);
              tofp.add(tofqp6);
              tofp.add(tofqp7);
              tofp.add(tofqp8);
              tofp.add(tofqp9);
              tofp.add(tofqp10);
              tofp.add(b4);
         JRadioButton True = new JRadioButton("True");
             True.setActionCommand("True");
             True.setSelected(false);
         JRadioButton False = new JRadioButton("False");
             False.setActionCommand("False");
             False.setSelected(false);      
             ButtonGroup group = new ButtonGroup();
             group.add(True);
             group.add(False);
             JRadioButton True2 = new JRadioButton("True");
             True.setActionCommand("True");
             True.setSelected(false);
         JRadioButton False2 = new JRadioButton("False");
             False.setActionCommand("False");
             False.setSelected(false);      
             ButtonGroup group2 = new ButtonGroup();
             group2.add(True2);
             group2.add(False2);
             tofqp.add(True);
             tofqp.add(False);
               tofqp2.add(True2);
             tofqp2.add(False2);
              FormPanel3.add(tofp);
              FormPanel3.add(tofp2);
              FormPanel3.add(tofp2);
              f3.setContentPane(FormPanel3);
              f3.pack();
              f3.show();     
              f3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f3.setResizable(false);I intentionally just have 2 groups of radio button displayed to test if I could tally the right answer. No luck.
    I'm a complete beginner to this sort of thing, as in starting from scratch. But if I were to apply what our teacher taught us, this would be a simple boolean program. Unfortunately, this kind of thing isn't too simple for me.
    So how do I tally the right answer upon clicking 'submit'. I know you have to have a new frame for that, but it's about tallying. Like the right answer for number 1 is false, for number 2 is true. If you click Submit, I should be able to show "You got 1 correct answer".

    Tan-Tan wrote:
    I'm now using checkboxes in a True or False 10-item test. I once used buttons, but I gave up and went to checkboxes. I managed to display them using this:I'm confused. So does your code use JRadioButtons (like your code says), or JCheckBoxes (like this sentence says)?
    I intentionally just have 2 groups of radio button displayed to test if I could tally the right answer. No luck.How did you attempt to tally the right answer? How do you have the right answers stored? How were you getting the status of each JRadioButton?
    So how do I tally the right answer upon clicking 'submit'. I know you have to have a new frame for that, but it's about tallying. Like the right answer for number 1 is false, for number 2 is true. If you click Submit, I should be able to show "You got 1 correct answer".Worry about how you display the tally later. For now just use a System.out.println. I'd use a for loop to get the status of each JRadioButton or JCheckBox, and check that against an array of correct answers.

  • After DND AbstractButton, setSelected not work

    Recently, I got problem in DND with AbstractButton
    and would like to share my finding
    After DND an AbstractButton,
    Within the DragSourceListener.dragDropEnd
    I get the dragged AbstractButton and invoke its
    AbstractButton.setSelected(false);
    The selection still visible, nothing have been changed
    Therefore, I println the AbstractButton.isSelected();
    And the console shows "false"
    Then, I tried to invoke invalidate, revalidate, doLayout, repaint
    but the result is the same
    Finally, I called setEnabled( ! isEnabled() ) twice and it work correctly

    So you're the one who took my crystal ball, Kaj!One doesn't need any fancy gadgets to see that it's
    201 in Person.Nope, but with this crystal ball I can see that the OP
    will ask for more help, and an explanation of the
    answer. So now I'm prepared :)
    /KajUhm..... yep, that's an advantage :)

  • 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

  • SetSelected does not generate itemStateChanged event

    Hi!
    In 1.4 setSelected, on e.g. a JCheckbox, does not generate a itemStateChanged event if you set the value to the same as the checkbox already has. So if I do a setSelected(false) method call on a newly created JCheckBox instance (I have added an ItemListener), no event is generated. This is a change since 1.3.
    I have a lot of update methods that sets the initial state of my checkboxes and this changed behaviour puts me in trouble. Is there anyone that knows of a solution to this problem. One obvious one is to set every checkbox to its opposite value before setting it to its right one, but then the code gets ugly. Is there a way to make the checkbox not remember its current value.
    Thanks in advance!
    Best regards
    Lars

    Hell, how I could overseen that! Thx alot!
    I could stare for years and didn't find it :|

  • Help with JRadioButton

    Could someone help me with trying to have an image rather than text on a radio button. I can make a radio button with text, but when I try to use an Icon rather than text for a label there is no button created. My code is below. Thanks.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class appTag extends JApplet
         JLabel     serviceInfoL,
              welcomeLabel,
              nameLabel,
              addressLabel,
              cityLabel,
              stateLabel,
              zipLabel,
              emailLabel,
              phoneNoLabel,
              cctypeLabel1,
              cctypeLabel2,
              cctypeLabel3,
              cctypeLabel4,
              ccNoLabel,
              ccExpLabel,
         ConnectL,
                   sIconL1,
                   sIconL2,
         sIconL3;
    JTextField nameTf,
                   addressTf,
                        cityTf,
                        stateTf,
                        zipTf,
                        emailTf,
                        phoneNoTf;
         JPasswordField ccNo,
                        expDate;
         JButton orderButton,
                        clearButton;
         JCheckBox service1,
                        service2,
                        service3;
         ButtonGroup radioGroup;
         JRadioButton Discovertype,
                        Visatype,
                        MCtype,
                        AEtype;
         JComboBox compTypePC,
                        compTypeApple,
                        compTypeLinux;
    Icon          EagleNet,
                   service1Icon,
                   service2Icon,
                   service3Icon,
                   ccIcon1,
                   ccIcon2,
                   ccIcon3,
                   ccIcon4;
    //Icon Connect;
    public void init ()
         // define GUI components
         JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.BOTTOM);
         JPanel pane = new JPanel ();
         JPanel secondPane = new JPanel();
         JPanel thirdPane = new JPanel();
         JPanel fourthPane = new JPanel();
         EagleNet = new ImageIcon("hosting2.jpg");
         service1Icon = new ImageIcon("connect.gif");
         service2Icon = new ImageIcon("2_computers.gif");
         service3Icon = new ImageIcon("WWW.gif");
         ccIcon1 = new ImageIcon("visa.jpg");
         ccIcon2 = new ImageIcon("mastercard.jpg");
         ccIcon3 = new ImageIcon("americanexpress.jpg");
         ccIcon4 = new ImageIcon("discovernovus.jpg");
         //needs to be resized to fit applet
         nameTf = new JTextField(12);
         addressTf = new JTextField(12);
         cityTf = new JTextField(12);
         stateTf = new JTextField(2);
         zipTf = new JTextField(5);
         emailTf = new JTextField(15);
         phoneNoTf = new JTextField(10);
         ccNo = new JPasswordField(16);
         expDate = new JPasswordField(4);
         ccNo.setEchoChar('#');
         expDate.setEchoChar('#');
         Discovertype = new JRadioButton(ccIcon1,false);
         Visatype = new JRadioButton(ccIcon2,false);
         MCtype = new JRadioButton(ccIcon3,false);
         AEtype = new JRadioButton(ccIcon4,false);
         radioGroup = new ButtonGroup ();
         radioGroup.add(Discovertype);
         radioGroup.add(Visatype);
         radioGroup.add(MCtype);
         radioGroup.add(AEtype);
         cctypeLabel1 = new JLabel(ccIcon1);
         cctypeLabel2 = new JLabel(ccIcon2 );
         cctypeLabel3 = new JLabel(ccIcon3);
         cctypeLabel4 = new JLabel(ccIcon4);
         sIconL1 = new JLabel(service1Icon);
         sIconL2 = new JLabel(service2Icon);
         sIconL3 = new JLabel(service3Icon);
         ConnectL = new JLabel(EagleNet);
         welcomeLabel = new JLabel("We are located @ 9A N. Zetterowe Avenue Statesboro, GA 30458");
         serviceInfoL = new JLabel("Please pick the service(s) you are interested in purchasing.");
         // build the GUI layout
         pane.add(ConnectL);
         pane.add(welcomeLabel);
         //pane.add (Connect);
         //build second Pane
         tabbedPane.add("Welcome to EagleNet",pane);
         tabbedPane.add("Services", secondPane);
         tabbedPane.add("Customer Info", thirdPane);
         tabbedPane.add("Receipt", fourthPane);
         this.setContentPane (tabbedPane);
         //adding menubar
         JMenuBar menuBar = new JMenuBar();
         JMenu fileMenu = new JMenu("File");
         JMenu editMenu = new JMenu("Edit");
         JMenu toolMenu = new JMenu("Tool");
         JMenu helpMenu = new JMenu("Help");
         JMenuItem openItem = new JMenuItem("Open");
         JMenuItem saveItem = new JMenuItem("Save");
         JMenuItem quitItem = new JMenuItem("Quit");
         JMenuItem clearItem = new JMenuItem("Clear");
         JMenuItem versionItem = new JMenuItem("Version");
         fileMenu.add(openItem);
         fileMenu.add(saveItem);
         fileMenu.add(quitItem);
         editMenu.add(clearItem);
         helpMenu.add(versionItem);
         menuBar.add(fileMenu);
         menuBar.add(editMenu);
         menuBar.add(toolMenu);
         menuBar.add(helpMenu);
         setJMenuBar(menuBar);
         //make secondPane
         secondPane.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 20));
         secondPane.add(serviceInfoL);
         //secondPane.
         secondPane.add(sIconL1);
         secondPane.add(service1 = new JCheckBox("Internet Access @ $18.95/month"));
         secondPane.add(sIconL2);
         secondPane.add(service2 = new JCheckBox("Wireless Network @ $150.00"));
    secondPane.add(sIconL3);
         secondPane.add(service3 = new JCheckBox("Web_Hosting @ $50.00/month"));
         //make third pane
         thirdPane.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 20));
         //thirdPane.setLayout(new BorderLayout(5,10));
         thirdPane.add(welcomeLabel);
         thirdPane.add(addressTf);
         thirdPane.add(cityTf);
         thirdPane.add(stateTf);
         thirdPane.add(zipTf);
         thirdPane.add(emailTf);
         thirdPane.add(phoneNoTf);
         thirdPane.add(ccNo);
         thirdPane.add(expDate);
         thirdPane.add(Discovertype);
         thirdPane.add(Visatype);
         thirdPane.add(MCtype);
         thirdPane.add(AEtype);
    }

    A button is actually getting created, just not the way you would assume. The documentation isn't very clear on this matter. A JRadioButton (and JCheckBox too) actually consist of two (optional) parts: an icon and text. The icon is the little cirle that is either selected or unselected, depending on the state of the button and the text is whatever text you wish to accompany the button describing its purpose. So, when you specify an Icon, you are actually replacing the default unselected icon (the little unselected circle). If you do this, you also need to call setSelectedIcon() and specify an icon to replace the default selected icon (the little selected circle). This is a bit silly, but that's the API.
    To accomplish what you want, I'd suggest placing a JRadioButton and a JLabel (containing the Icon) next to one another.
    HTHs,
    Jamie

  • Error when running mortgage calc program from DOS prompt

    I have a GUI Mortgage Calculator program. It probably isn't the most efficient use of code, but it gets the job done. I am running java SDK 1.6.0_06. This is a class assignment. We are to compile the code and post the .class file for our team members to run. I am trying to get the .class file to run after I compile it with javac. I used jCreator LE to create it... it compiles and runs there just fine. The program will compile at the DOS prompt, but will not run properly. The following is the error I get (any help would be appreciated):
    Exception in thread "mani" java.lang.NoClassDefFoundError: manchorMortgage3
    Caused by: java.lang.ClassNotFoundException: manchorMortgage3
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader1.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    Below is my code:
    * manchorMortgage3.java
    * Created on July 10, 2008
    * This program calculates and displays the mortgage amount
    * from user input of the amount of the mortgage and the user's
    * selection from a menu of available mortgage loans.
    import java.math.*; //*loan calculator
    import java.text.*; //*formats numbers
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class manchorMortgage3 extends javax.swing.JFrame {
        /** Creates new form manchorMortgage3 */
             public manchorMortgage3() {
             initComponents();
             setLocation(300,200);
        /** This method is called from within the constructor to
         * initialize the form.
        // Begin Initialize Components
        private void initComponents() {
            mortgageAmount = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            termAndInterest = new javax.swing.JLabel();
            jRadioButton1 = new javax.swing.JRadioButton();
            jRadioButton2 = new javax.swing.JRadioButton();
            jRadioButton3 = new javax.swing.JRadioButton();
            calcButton = new javax.swing.JButton();
            enterAmount = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            jButton2 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Manchor - Mortgage Calculator - Week 3");
            mortgageAmount.setText("Enter the Mortgage Amount:");
            termAndInterest.setText("Select Your Term and Interest Rate:");
            jRadioButton1.setText("7 years at 5.35%");
            jRadioButton1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jRadioButton1.setMargin(new java.awt.Insets(0, 0, 0, 0));
            jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jRadioButton1ActionPerformed(evt);
            jRadioButton2.setText("15 years at 5.5%");
            jRadioButton2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jRadioButton2.setMargin(new java.awt.Insets(0, 0, 0, 0));
            jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jRadioButton2ActionPerformed(evt);
            jRadioButton3.setText("30 years at 5.75%");
            jRadioButton3.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jRadioButton3.setMargin(new java.awt.Insets(0, 0, 0, 0));
            jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jRadioButton3ActionPerformed(evt);
            calcButton.setText("Calculate");
            calcButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    calcButtonActionPerformed(evt);
            jTextArea1.setColumns(20);
            jTextArea1.setEditable(false);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
            jButton2.setText("Quit");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(26, 26, 26)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap())
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(enterAmount)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 222, Short.MAX_VALUE)
                                .addComponent(calcButton)
                                .addGap(75, 75, 75))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jRadioButton3)
                                    .addComponent(jRadioButton2)
                                    .addComponent(jRadioButton1)
                                    .addComponent(termAndInterest)
                                    .addComponent(mortgageAmount)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(224, Short.MAX_VALUE)))))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(277, Short.MAX_VALUE)
                    .addComponent(jButton2)
                    .addGap(70, 70, 70))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(31, 31, 31)
                    .addComponent(mortgageAmount)
                    .addGap(14, 14, 14)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(20, 20, 20)
                    .addComponent(termAndInterest)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jRadioButton1)
                    .addGap(15, 15, 15)
                    .addComponent(jRadioButton2)
                    .addGap(19, 19, 19)
                    .addComponent(jRadioButton3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(calcButton)
                        .addComponent(enterAmount))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton2)
                    .addGap(20, 20, 20))
            pack();
        }// End initialize components
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//event_jButton2ActionPerformed
            System.exit(1);
        }//event_jButton2ActionPerformed
        static NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
        static NumberFormat np = NumberFormat.getPercentInstance();
        static NumberFormat ni = NumberFormat.getIntegerInstance();
        static BufferedReader br;
        private void calcButtonActionPerformed(java.awt.event.ActionEvent evt) {//event_calcButtonActionPerformed
            enterAmount.setText(null);
            jTextArea1.setText(null);
            double monthlyPayment;
            double interest;
            double amount ;       
            int years ;
            double monthlyInterest, monthlyPrinciple, principleBalance;
            int paymentsRemaining, lineCount;
            np.setMinimumFractionDigits(2);
        br = new BufferedReader(new InputStreamReader(System.in));
      lineCount = 0;
            try
                    amount=Double.parseDouble(jTextField1.getText());
            catch (Exception e)
                enterAmount.setText("Please Enter Mortgage Amount");
                return;
            if(jRadioButton1.isSelected())
                interest=0.0535;
                years=7;
            else if(jRadioButton2.isSelected())
                interest=0.055;
                years=15;
            else if(jRadioButton3.isSelected())
                interest=0.0575;
                years=30;
            else
                enterAmount.setText("Please Select Your Term and Interest Rate");
                return;
        jTextArea1.append(" For a mortgage of " + nf.format(amount)+"\n"+" With a Term of " + ni.format(years) + " years"+"\n"+" And an Interest rate of " + np.format(interest)+"\n"+" The Payment Amount is " + nf.format(getMortgagePmt(amount, years, interest)) + " per month."+"\n"+"\n");
        principleBalance = amount - ((getMortgagePmt(amount, years, interest)) - (amount*(interest/12)));
        paymentsRemaining = 0;
        do
            monthlyInterest = principleBalance * (interest/12);//*Current monthly interest
             monthlyPrinciple = (getMortgagePmt(amount, years, interest)) - monthlyInterest;//*Principal payment each month minus interest
            paymentsRemaining = paymentsRemaining + 1;
            principleBalance = principleBalance - monthlyPrinciple;//*New balance of loan
            jTextArea1.append(" Principal on payment  " + ni.format(paymentsRemaining) + " is " + nf.format(monthlyPrinciple)+"\n");
                    jTextArea1.append(" Interest on payment  " + ni.format(paymentsRemaining) + " is " + nf.format(monthlyInterest)+"\n");
                    jTextArea1.append(" New loan balance on payment  " + ni.format(paymentsRemaining) + " is " + nf.format(principleBalance)+"\n"+"\n"+"\n");
         while (principleBalance > 1);
        }//Begin event_jRadioBtton1Action Performed
        public static double getMortgagePmt(double balance, double term, double rate)
                double monthlyRate = rate / 12;
                double monthlyPayment = (balance * monthlyRate)/(1-Math.pow(1+monthlyRate, - term * 12));
                return monthlyPayment;
        private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {//Begin event_jRadioButton3ActionPerformed
             if(jRadioButton2.isSelected())
                jRadioButton2.setSelected(false);
             if(jRadioButton1.isSelected())
                jRadioButton1.setSelected(false);
        }//End event_jRadioButton3ActionPerformed
        private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//Begin event_jRadioButton2ActionPerformed
             if(jRadioButton1.isSelected())
                jRadioButton1.setSelected(false);
             if(jRadioButton3.isSelected())
                jRadioButton3.setSelected(false);
        }//End event_jRadioButton2ActionPerformed
        private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
            if(jRadioButton2.isSelected())
                jRadioButton2.setSelected(false);
            if(jRadioButton3.isSelected())
                jRadioButton3.setSelected(false);
        }//End event_jRadioButton1ActionPerformed
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new manchorMortgage3().setVisible(true);
        // Begin variables declaration
        private javax.swing.JButton calcButton;
        private javax.swing.JButton jButton2;
        private javax.swing.JLabel mortgageAmount;
        private javax.swing.JLabel termAndInterest;
        private javax.swing.JLabel enterAmount;
        private javax.swing.JRadioButton jRadioButton1;
        private javax.swing.JRadioButton jRadioButton2;
        private javax.swing.JRadioButton jRadioButton3;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JTextField jTextField1;
        // End  variables declaration
    }

    The class is not in your classpath. Likely you blew away your classpath with some silly environment variable.
    If you are in the directory where your class file is then execute
    java -cp . manchorMortgage3and it will work. (Note the -cp . which tells java to include the current directory in the runtime classpath)

  • Error Check does not work

    Hi, I'm having a problem with the following code, when I add alphabetic characters or even nothing at all in the principal amt text field, I expect to get an error message, but I do not. This happens no matter which method I choose to compute the mortgage.
    //Import required libraries
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.text.*;
    import java.math.*;
    import java.util.*;
    public class pos407checkbox extends JFrame implements ActionListener
         // implements ActionListener, ItemListener
         NumberFormat formatter = new DecimalFormat ("$###,###.00");
         //Common Variables
         String ErrorMsg;
         double principal;
         double IntRate;
         int Term;
         double monthlypymt;
         double EndBalance =0;
         double FirstEndBalance =0;
         double interestpmt = 0 ;
         double principlepmt = 0;
         int choice = 0;
         //Components for Menu items
         private JMenuBar menuBar;    
         private JMenuItem exitMenuItem; 
         private JMenu fileMenu; 
         //create the common components
         private JPanel jPanelRadioButton = new JPanel();
         private JPanel jPanelActionButtons = new JPanel();
         JRadioButton jRadiochoice1 = new JRadioButton("I want to enter my own principal, rate and term",false);
         JRadioButton jRadiochoice2 = new JRadioButton("I will enter my own principal, and choose rate and term",false);
         private JButton buttonCompute;
         private JButton buttonNew; 
         private JButton buttonClose;
         //create the components required for jRadiochoice1
         private JPanel jPanelUserEnterAllValues = new JPanel();
         private JLabel jLabelMortgageAmt = new JLabel("Principal Amt(No decimals or commas)");
         private JLabel jLabelMortgageAmt2 = new JLabel("Principal Amt(No decimals or commas)");   
         private JLabel jLabelIntRate = new JLabel("Interest Rate"); 
         private JLabel jLabelTerm = new JLabel("Term - In Years"); 
         private JTextField jTextFieldMortgageAmt = new JTextField();
         private JTextField jTextFieldMortgageAmt2 = new JTextField();
         private JTextField jTextFieldIntRate= new JTextField();
         private JTextField jTextFieldTerm = new JTextField();
         //create the components required for jRadiochoice2
         private JPanel jPanelRateAndTermSelection;
         private JLabel jLabelChooseRateAndTerm; 
         private JComboBox TermAndRate;
         //create the output area
         private JPanel jPanelAmoritizationSchedule;
         private JTextArea jTextAreaAmoritization;
         public pos407checkbox() {            
              super("Mortgage Application");      
               initComponents();      
          private void initComponents()
              setSize(800,460);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
              setVisible(true);           
              Container pane = getContentPane();
              //GridLayout grid = new GridLayout(5, 1);      
              FlowLayout grid = new FlowLayout();      
              pane.setLayout(grid);
              //**********************************MENU BAR**************************//
              menuBar = new JMenuBar();
              fileMenu = new JMenu();
              fileMenu.setText("File");        
              exitMenuItem = new JMenuItem(); 
               exitMenuItem.setText("Exit");
              fileMenu.add(exitMenuItem); 
              menuBar.add(fileMenu);
              //pane.add(menuBar);       
              setJMenuBar(menuBar);
              //*****************************RADIO BUTTON PANEL***************************//
              jPanelRadioButton = new JPanel();
              GridLayout Radio = new GridLayout(1,2);
              jPanelRadioButton.setLayout(Radio);
              ButtonGroup RadioButtons = new ButtonGroup();
              RadioButtons.add(jRadiochoice1);
              RadioButtons.add(jRadiochoice2);
              jPanelRadioButton.add(jRadiochoice1); 
              jPanelRadioButton.add(jRadiochoice2);       
              pane.add(jPanelRadioButton);
              //***********************USER INTERFACE FOR CHOICE 1*******************//
              GridLayout userchoice = new GridLayout(3,2);
              //FlowLayout userchoice = new FlowLayout();           
              jPanelUserEnterAllValues.setLayout(userchoice);
              jPanelUserEnterAllValues.add(jLabelMortgageAmt); 
              jPanelUserEnterAllValues.add(jTextFieldMortgageAmt);       
              jPanelUserEnterAllValues.add(jLabelIntRate);
              jPanelUserEnterAllValues.add(jTextFieldIntRate);       
              jPanelUserEnterAllValues.add(jLabelTerm);
              jPanelUserEnterAllValues.add(jTextFieldTerm); 
              jPanelUserEnterAllValues.setVisible(false);
              pane.add(jPanelUserEnterAllValues);
              //***********************USER INTERFACE FOR CHOICE 2*******************//
              // Create a label that will advise user to enter a principle amount
              jPanelRateAndTermSelection = new JPanel();
              TermAndRate = new JComboBox();
              //Add the selections to the combo box
              TermAndRate.addItem("7 years at 5.35%");
              TermAndRate.addItem("15 years at 5.5%");
              TermAndRate.addItem("30 years at 5.75%");
              //FlowLayout RateAndTerm = new FlowLayout(FlowLayout.CENTER);
              GridLayout RateAndTerm = new GridLayout(2,2);
              jPanelRateAndTermSelection.setLayout(RateAndTerm);
              jPanelRateAndTermSelection.add(jLabelMortgageAmt2);
              jPanelRateAndTermSelection.add(jTextFieldMortgageAmt2);   
              jLabelChooseRateAndTerm = new JLabel("Choose the Rate and Term");
              jPanelRateAndTermSelection.add(jLabelChooseRateAndTerm);
              jPanelRateAndTermSelection.add(TermAndRate);
              jPanelRateAndTermSelection.setVisible(false);
              pane.add(jPanelRateAndTermSelection);
              //------------------THIRD PANEL CHOOSE ACTION----------------------
              jPanelActionButtons = new JPanel();
              buttonCompute = new JButton("Compute Mortgage");
              buttonNew = new JButton("New Mortgage");
              buttonClose = new JButton("Close");
              FlowLayout Actionbuttons = new FlowLayout(FlowLayout.CENTER);
              jPanelActionButtons.setLayout(Actionbuttons);
              jPanelActionButtons.add(buttonCompute);
              jPanelActionButtons.add(buttonNew);
              jPanelActionButtons.add(buttonClose);
              jPanelActionButtons.setVisible(false);
              pane.add(jPanelActionButtons);
              //*******************ADD THE TEXT AREA FOR OUTPUT TO THE GUI******************//
              jPanelAmoritizationSchedule = new JPanel();
              jTextAreaAmoritization = new JTextArea(26,50);
              JScrollPane scrollBar = new JScrollPane(jTextAreaAmoritization, 
              JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              scrollBar.setPreferredSize(new Dimension(500,250));
              FlowLayout Amoritization = new FlowLayout();
              jPanelAmoritizationSchedule.setLayout(Amoritization);
              // add scroll pane to output text area
              jPanelAmoritizationSchedule.add(scrollBar);
              jPanelAmoritizationSchedule.setVisible(false);
                pane.add(jPanelAmoritizationSchedule);
              setContentPane(pane);
              //pack();
              // Add Action Listeners
              exitMenuItem.addActionListener(this);
              buttonCompute.addActionListener(this);         
              buttonNew.addActionListener(this);
              buttonClose.addActionListener(this);
              TermAndRate.addActionListener(this);
              jRadiochoice1.addActionListener(this);
              jRadiochoice2.addActionListener(this);
    //create a method that will clear all fields when the New Mortgage button is chosen
    private void clearFields()
         jRadiochoice1.setSelected(false);
         jRadiochoice2.setSelected(false);
         jTextAreaAmoritization.setText("");
         jPanelAmoritizationSchedule.setVisible(false);
         jPanelActionButtons.setVisible(false);
         jTextFieldMortgageAmt.setText("");
         jTextFieldMortgageAmt2.setText("");
         jPanelRadioButton.setVisible(true);
         jPanelUserEnterAllValues.setVisible(false);
         jPanelRateAndTermSelection.setVisible(false);
      public void actionPerformed(ActionEvent e)
              Object source = e.getSource();  
              if (source == exitMenuItem)
                       System.exit(0);
              if(source == buttonClose)
                   System.exit(0);
              if (source == buttonNew)
                   clearFields();
              if (source == jRadiochoice1)
                   jPanelActionButtons.setVisible(true);
                   jPanelRadioButton.setVisible(false);
                   jPanelUserEnterAllValues.setVisible(true);
                   principal = Double.parseDouble(jTextFieldMortgageAmt.getText());
                   choice  = 1;
              }//End if for checkbox1
              if (source == jRadiochoice2)
                   jPanelRateAndTermSelection.setVisible(true);
                   jPanelAmoritizationSchedule.setVisible(true);
                   jPanelActionButtons.setVisible(true);
                   jPanelRadioButton.setVisible(false);
                   choice = 2;
              if (source == buttonCompute)
                   jPanelAmoritizationSchedule.setVisible(true);
                   //Make sure the user entered valid numbers for the principal
                   if (choice ==2)
                        int[] term = {7,15,30};
                        double[] rate = {5.35,5.50,5.75};
                        try
                             principal = Double.parseDouble(jTextFieldMortgageAmt2.getText());
                        catch(NumberFormatException nfe)
                             ErrorMsg = (" You Entered an invalid Mortgage amount"
                                  + " Please try again. Please do not use commas or decimals");
                             jTextAreaAmoritization.setText(ErrorMsg);
                        int loan = TermAndRate.getSelectedIndex();
                        Term = term[loan];
                        IntRate = rate[loan];
                   else
                        try
                             principal = Double.parseDouble(jTextFieldMortgageAmt.getText());
                        catch(NumberFormatException nfe)
                             ErrorMsg = (" You Entered an invalid Mortgage amount"
                                  + " Please try again. Please do not use commas or decimals");
                             jTextAreaAmoritization.setText(ErrorMsg);
                        try
                             IntRate = Double.parseDouble(jTextFieldIntRate.getText());
                        catch(NumberFormatException nfe)
                             ErrorMsg = (" You entered an invalid Interest Rate");
                             jTextAreaAmoritization.setText(ErrorMsg);
                        try
                             Term = Integer.parseInt(jTextFieldTerm.getText());
                        catch(NumberFormatException nfe)
                             ErrorMsg = (" You entered an invalid Term value");
                             jTextAreaAmoritization.setText(ErrorMsg);
                   jTextAreaAmoritization.setText(" Loan amount of " + formatter.format(principal) );
                   double intdecimal = intdecimal = IntRate/(12 * 100);
                   int months = Term * 12;
                   int paymentNum = months;
                   double monthlypayment = principal *(intdecimal / (1- Math.pow((1 + intdecimal),-months)));
                   //Display the Amoritization schedule header info
                   jTextAreaAmoritization.setText(" Loan amount of " + formatter.format(principal)
                                                    + "\n"
                                                    + " Interest Rate is " +  IntRate + "%"
                                            + "\n"
                                            + " Term in Years "  + Term
                                            + " Monthly payment "+  formatter.format(monthlypayment)
                                            + "\n"
                                            + "  Amoritization is as follows:  "
                                            + "\n"
                                            + "****************************************************************************************************"
                                            + "\n"
                                            + "PAYMENT # " + "\t" + "UNPAIDBALANCE"
                                            + "\t" + "PRINCIPLE PAID" + "\t" + "INTEREST PMT" + "\n\n");
         public static void main(String[]args) { 
              pos407checkbox gui = new pos407checkbox(); 
    }

    it does actually get set.
    the problem is your actionperformed() falls throught to the final
    jTextAreaAmoritization.setText(" Loan amount of " + formatter.format(principal) etc etc
    at every error handler you need to exit the method
    catch()
    ErrorMsg = (" You entered an invalid Interest Rate");
    jTextAreaAmoritization.setText(ErrorMsg);
    return;//<-------------------
    }

  • Who can help me :)--a problem with java program(reset problem in java )

    I do not know how to make the button reset,my program only could reset diagram but button.If any one who could help me to solve this problem.The problem is When the reset button is pressed, the image should immediately revert to the black square, and the 4 widgets listed above should show values that
    correspond to the black square.The code like this,first one is shapes:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class shapes extends JFrame {
         private JPanel buttonPanel; // panel for buttons
         private DrawPanel myPanel;  // panel for shapes
         private JButton resetButton;
        private JComboBox colorComboBox;
         private JRadioButton circleButton, squareButton;
         private ButtonGroup radioGroup;
         private JCheckBox filledButton;
        private JSlider sizeSlider;
         private boolean isShow;
         private int shape;
         private boolean isFill=true;
        private String colorNames[] = {"black", "blue", "cyan", "darkGray", "gray",
                                   "green", "lightgray", "magenta", "orange",
                                   "pink", "red", "white", "yellow"};   // color names list in ComboBox
        private Color colors[] = {Color.black, Color.blue, Color.cyan, Color.darkGray,
                              Color.gray, Color.green, Color.lightGray, Color.magenta,
                              Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
         public shapes() {
             super("Draw Shapes");
             // creat custom drawing panel
            myPanel = new DrawPanel(); // instantiate a DrawPanel object
            myPanel.setBackground(Color.white);
             // set up resetButton
            // register an event handler for resetButton's ActionEvent
            resetButton = new JButton ("reset");
             resetButton.addActionListener(
              // anonymous inner class to handle resetButton events
                 new ActionListener() {
                       // draw a black filled square shape after clicking resetButton
                     public void actionPerformed (ActionEvent event) {
                             // call DrawPanel method setShowStatus and pass an parameter
                          // to decide if show the shape
                         myPanel.setShowStatus(true);
                             isShow = myPanel.getShowStatus();
                             shape = DrawPanel.SQUARE;
                         // call DrawPanel method setShape to indicate shape to draw
                             myPanel.setShape(shape);
                         // call DrawPanel method setFill to indicate to draw a filled shape
                             myPanel.setFill(true);
                         // call DrawPanel method draw
                             myPanel.draw();
                             myPanel.setFill(true);
                             myPanel.setForeground(Color.black);
                   }// end anonymous inner class
             );// end call to addActionListener
            // set up colorComboBox
            // register event handlers for colorComboBox's ItemEvent
            colorComboBox = new JComboBox(colorNames);
            colorComboBox.setMaximumRowCount(5);
            colorComboBox.addItemListener(
                 // anonymous inner class to handle colorComboBox events
                 new ItemListener() {
                     // select shape's color
                     public void itemStateChanged(ItemEvent event) {
                         if(event.getStateChange() == ItemEvent.SELECTED)
                             // call DrawPanel method setForeground
                             // and pass an element value of colors array
                             myPanel.setForeground(colors[colorComboBox.getSelectedIndex()]);
                        myPanel.draw();
                }// end anonymous inner class
            ); // end call to addItemListener
            // set up a pair of RadioButtons
            // register an event handler for RadioButtons' ItemEvent
             squareButton = new JRadioButton ("Square", true);
             circleButton = new JRadioButton ("Circle", false);
             radioGroup = new ButtonGroup();
             radioGroup.add(squareButton);
             radioGroup.add(circleButton);
            squareButton.addItemListener(
                // anonymous inner class to handle squareButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                           if (isShow==true) {
                                 shape = DrawPanel.SQUARE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                   }// end anonymous inner class
             );// end call to addItemListener
             circleButton.addItemListener(
                   // anonymous inner class to handle circleButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                             if (isShow==true) {
                                 shape = DrawPanel.CIRCLE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                             else
                                 System.out.println("Please click Reset button first");
                   }// end anonymous inner class
             );// end call to addItemListener
             // set up filledButton
            // register an event handler for filledButton's ItemEvent
            filledButton = new JCheckBox("Filled", true);
             filledButton.addItemListener(
              // anonymous inner class to handle filledButton events
            new ItemListener() {
                  public void itemStateChanged (ItemEvent event) {
                    if (isShow==true) {
                            if (event.getStateChange() == ItemEvent.SELECTED) {
                                  isFill=true;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                            else {
                                isFill=false;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                    else
                        System.out.println("Please click Reset button first");
              }// end anonymous inner class
             );// end call to addItemListener
            // set up sizeSlider
            // register an event handler for sizeSlider's ChangeEvent
            sizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
            sizeSlider.setMajorTickSpacing(10);
            sizeSlider.setPaintTicks(true);
            sizeSlider.addChangeListener(
                 // anonymous inner class to handle sizeSlider events
                 new ChangeListener() {
                      public void stateChanged(ChangeEvent event) {
                          myPanel.setShapeSize(sizeSlider.getValue());
                             myPanel.draw();
                 }// end anonymous inner class
             );// end call to addChangeListener
            // set up panel containing buttons
             buttonPanel = new JPanel();
            buttonPanel.setLayout(new GridLayout(4, 1, 0, 50));
             buttonPanel.add(resetButton);
             buttonPanel.add(filledButton);
            buttonPanel.add(colorComboBox);
            JPanel radioButtonPanel = new JPanel();
            radioButtonPanel.setLayout(new GridLayout(2, 1, 0, 20));
            radioButtonPanel.add(squareButton);
            radioButtonPanel.add(circleButton);
            buttonPanel.add(radioButtonPanel);
            // attach button panel & draw panel to content panel
            Container container = getContentPane();
            container.setLayout(new BorderLayout(10,10));
            container.add(myPanel, BorderLayout.CENTER);
             container.add(buttonPanel, BorderLayout.EAST);
            container.add(sizeSlider, BorderLayout.SOUTH);
            setSize(500, 400);
             setVisible(true);
         public static void main(String args[]) {
             shapes application = new shapes();
             application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }second one is drawpanel:
    import java.awt.*;
    import javax.swing.*;
    public class DrawPanel extends JPanel {
         public final static int CIRCLE = 1, SQUARE = 2;
         private int shape;
         private boolean fill;
         private boolean showStatus;
        private int shapeSize = 100;
        private Color foreground;
         // draw a specified shape
        public void paintComponent (Graphics g){
              super.paintComponent(g);
              // find center
            int x=(getSize().width-shapeSize)/2;
              int y=(getSize().height-shapeSize)/2;
              if (shape == CIRCLE) {
                 if (fill == true){
                     g.setColor(foreground);
                      g.fillOval(x, y, shapeSize, shapeSize);
                else{
                       g.setColor(foreground);
                    g.drawOval(x, y, shapeSize, shapeSize);
              else if (shape == SQUARE){
                 if (fill == true){
                     g.setColor(foreground);
                        g.fillRect(x, y, shapeSize, shapeSize);
                else{
                        g.setColor(foreground);
                    g.drawRect(x, y, shapeSize, shapeSize);
        // set showStatus value
        public void setShowStatus (boolean s) {
              showStatus = s;
         // return showstatus value
        public boolean getShowStatus () {
              return showStatus;
         // set fill value
        public void setFill(boolean isFill) {
              fill = isFill;
         // set shape value
        public void setShape(int shapeToDraw) {
              shape = shapeToDraw;
        // set shapeSize value
        public void setShapeSize(int newShapeSize) {
              shapeSize = newShapeSize;
        // set foreground value
        public void setForeground(Color newColor) {
              foreground = newColor;
         // repaint DrawPanel
        public void draw (){
              if(showStatus == true)
              repaint();
    }If any kind people who can help me.
    many thanks to you!

    4 widgets???
    maybe this is what you mean.
    add this inside your actionPerformed method for the reset action
    squareButton.setSelected(true);
    colorComboBox.setSelectedIndex(0);
    if not be more clear in your post.

  • Urgent need of help with a chat application!

    Hi,
    I'm writing a Chat Application and I want to add Emoticon, I did so by adding buttons but I don't know how to send the gif to my JTextField and to my JTextArea.
    Here is part of my code can someone can help me PLEASE!!!
    JPanel chatPane = new JPanel(new BorderLayout());
    JPanel emoticon = new JPanel(new GridLayout(2, 5));
    b1 = new JButton (sourrire);
    b1.setToolTipText("Un Sourire");
    // b1.addActionListener();
    emoticon.add(b1);
    b2 = new JButton (gsourrire);
    b2.setToolTipText("Un Grand Sourire");
    // b2.addActionListener();
    emoticon.add(b2);
    b3 = new JButton (triste);
    b3.setToolTipText("Triste");
    // b3.addActionListener();
    emoticon.add(b3);
    b4 = new JButton (grimace);
    b4.setToolTipText("Grimace");
    // b4.addActionListener();
    emoticon.add(b4);
    b5 = new JButton (pleure);
    b5.setToolTipText("Pleure");
    // b5.addActionListener();
    emoticon.add(b5);
    b6 = new JButton (bec);
    b6.setToolTipText("Un bec");
    // b6.addActionListener();
    emoticon.add(b6);
    b7 = new JButton (coeur);
    b7.setToolTipText("Un coeur pour toi");
    // b7.addActionListener();
    emoticon.add(b7);
    b8 = new JButton (fache);
    b8.setToolTipText("Fache");
    // b8.addActionListener();
    emoticon.add(b8);
    b9 = new JButton (lunettes);
    b9.setToolTipText("Je suis Cool");
    // b9.addActionListener();
    emoticon.add(b9);
    b10 = new JButton (clinoeil);
    b10.setToolTipText("Clin d'Oeil");
    //b10.addActionListener(new ActionAdapter2());
    emoticon.add(b10);
    Thanks a lot!
    Isabelle

    Hi anoopjain13
    what I did is that each button is an IconImage and I was trying to send the Icon to the textfield.
    here is the complete code of my chat, you'll understand better what I tried to do.
    //Naziha Berrassil et Isabelle Gosselin
    //Travail Pratique #1
    //remis � Said Senhaji
    //Developpement d'une application CHAT
    //package chatv2.a
    import java.lang.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    public class TCPChat2a implements Runnable {
    // Constantes de l'etat de la connection
    public final static int NULL = 0;
    public final static int DISCONNECTED = 1;
    public final static int DISCONNECTING = 2;
    public final static int BEGIN_CONNECT = 3;
    public final static int CONNECTED = 4;
    // Declaration d'un tableau de chaines
    public final static String statusMessages[] = {
    " Erreur! Aucune connexion possible!", " Deconnexion",
    " Deconnexion en cours...", " Connexion en cours...", " Connexion"
    //Instentiation de la classe
    public final static TCPChat2a tcpObj = new TCPChat2a();
    // Indique la fin d'une session
    public final static String END_CHAT_SESSION =
    new Character((char)0).toString();
    // Informations sur l'etat de la connexion
    public static String hostIP = "localhost";
    public static String user = "";
    public static String s1;
    public static int port = 1234;
    public static int connectionStatus = DISCONNECTED;
    public static boolean isHost = true;
    public static String statusString = statusMessages[connectionStatus];
    public static StringBuffer toAppend = new StringBuffer("");
    public static StringBuffer toSend = new StringBuffer("");
    // Declaration des composantes GUI et initialisation
    public final static ImageIcon sourrire = new ImageIcon ("icons/sourrire.gif");
    public static JButton b1;
    public final static ImageIcon gsourrire = new ImageIcon ("icons/grand_sourrire.gif");
    public static JButton b2;
    public final static ImageIcon triste = new ImageIcon ("icons/triste.gif");
    public static JButton b3;
    public final static ImageIcon pleure = new ImageIcon ("icons/pleure.gif");
    public static JButton b4;
    public final static ImageIcon coeur = new ImageIcon ("icons/coeur.gif");
    public static JButton b5;
    public final static ImageIcon grimace = new ImageIcon ("icons/grimace.gif");
    public static JButton b6;
    public final static ImageIcon lunettes = new ImageIcon ("icons/lunettes.gif");
    public static JButton b7;
    public final static ImageIcon fache = new ImageIcon ("icons/fache.gif");
    public static JButton b8;
    public final static ImageIcon bec = new ImageIcon ("icons/bec.gif");
    public static JButton b9;
    public final static ImageIcon clinoeil = new ImageIcon ("icons/clinoeil.gif");
    public static JButton b10;
    public static JFrame mainFrame = null;
    public static JTextArea chatText = null;
    public static JTextField chatLine = null;
    public static JPanel statusBar = null;
    public static JLabel statusField = null;
    public static JTextField statusColor = null;
    public static JTextField ipField = null;
    public static JTextField username = null;
    public static JTextField portField = null;
    public static JRadioButton hostOption = null;
    public static JRadioButton guestOption = null;
    public static JButton connectButton = null;
    public static JButton disconnectButton = null;
    // Declaration des composantes TCP
    public static ServerSocket hostServer = null;
    public static Socket socket = null;
    public static BufferedReader in = null;
    public static PrintWriter out = null;
    //Methode qui retourne le premier pannel(optionsPane),ce dernier
    //se compose de 5 panneaux
    private static JPanel initOptionsPane() {
    //pannel pane qui sera ajout� au pannel optionsPane
    JPanel pane = null;
    //initiation de la classe ActionAdapteur qui implemente ActionListner
    ActionAdapter buttonListener = null;
    // Creation du pannel optionsPane
    JPanel optionsPane = new JPanel(new GridLayout(5, 1));
    // 1er pannel pane pour label et textfield de l'adresse IP
    pane = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    pane.add(new JLabel("Serveur IP:"));
    ipField = new JTextField(10);
    ipField.setBackground(new Color(0.98f, 0.97f, 0.85f));
    ipField.setText(hostIP);
    ipField.setEnabled(false);
    //evenement generer par Component avec la methode addFocusListener
    //en cas d'obtention ou perte du focus par un composant
    ipField.addFocusListener(new FocusAdapter() {
    public void focusLost(FocusEvent e) {
    ipField.selectAll();
    //Editable seulement en mode deconnexion
    if (connectionStatus != DISCONNECTED) {
    changeStatusNTS(NULL, true);
    else {
    hostIP = ipField.getText();
    pane.add(ipField);
    optionsPane.add(pane);
    // 2eme pannel pane pour label et textfield du port
    pane = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    pane.add(new JLabel("Port:"));
    portField = new JTextField(10);
    portField.setBackground(new Color(0.98f, 0.97f, 0.85f));
    portField.setEditable(true);
    portField.setText((new Integer(port)).toString());
    portField.addFocusListener(new FocusAdapter() {
    public void focusLost(FocusEvent e) {
    //Textfield du port modifiable si on est en mode deconnexion
    if (connectionStatus != DISCONNECTED) {
    changeStatusNTS(NULL, true);
    else {
    int temp;
    try {
    temp = Integer.parseInt(portField.getText());
    port = temp;
    catch (NumberFormatException nfe) {
    portField.setText((new Integer(port)).toString());
    mainFrame.repaint();
    pane.add(portField);
    optionsPane.add(pane);
    // 3eme pannel pour label et textfield du nom d'utilisateur
         pane = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              pane.add(new JLabel("Nom: "));
              username = new JTextField(10);
    username.setBackground(new Color(0.98f, 0.97f, 0.85f));
              username.setText(user);
              username.setEnabled(true);
              username.addFocusListener(new FocusAdapter() {
              public void focusLost(FocusEvent e) {
              // username.selectAll();
              // Should be editable only when disconnected
              if (connectionStatus != DISCONNECTED) {
              changeStatusNTS(NULL, true);
              else {
              user = username.getText();
              pane.add(username);
    optionsPane.add(pane);
    // Host/guest option
    buttonListener = new ActionAdapter() {
    public void actionPerformed(ActionEvent e) {
    if (connectionStatus != DISCONNECTED) {
    changeStatusNTS(NULL, true);
    else {
    isHost = e.getActionCommand().equals("host");
    // Cannot supply host IP if host option is chosen
    if (isHost) {
    ipField.setEnabled(false);
    ipField.setText("localhost");
    hostIP = "localhost";
    else {
    ipField.setEnabled(true);
    //creation de boutton groupe radio(serveur et invite)
    ButtonGroup bg = new ButtonGroup();
    hostOption = new JRadioButton("Serveur", true);
    hostOption.setMnemonic(KeyEvent.VK_S);
    hostOption.setActionCommand("host");
    hostOption.addActionListener(buttonListener);
    guestOption = new JRadioButton("Invite", false);
    guestOption.setMnemonic(KeyEvent.VK_I);
    guestOption.setActionCommand("invite");
    guestOption.addActionListener(buttonListener);
    bg.add(hostOption);
    bg.add(guestOption);
    // 4eme pannel pane pour les 2 bouttons radio
    pane = new JPanel(new GridLayout(1, 2));
    pane.add(hostOption);
    pane.add(guestOption);
    optionsPane.add(pane);
    // 5eme pannel buttonPane pour les bouttons de connexion et deconnexion
    JPanel buttonPane = new JPanel(new GridLayout(1, 2));
    buttonListener = new ActionAdapter() {
    public void actionPerformed(ActionEvent e) {
    // requete pou debut d'une connexion
    if (e.getActionCommand().equals("connect")) {
    changeStatusNTS(BEGIN_CONNECT, true);
    // Deconnexion
    else {
    changeStatusNTS(DISCONNECTING, true);
    //creation des bouttons dans le pannel et l'ajout au premier pannel
    //(optionsPane)
    connectButton = new JButton("Connexion");
    connectButton.setMnemonic(KeyEvent.VK_C);
    connectButton.setActionCommand("connect");
    connectButton.addActionListener(buttonListener);
    connectButton.setEnabled(true);
    disconnectButton = new JButton("Deconnexion");
    disconnectButton.setMnemonic(KeyEvent.VK_D);
    disconnectButton.setActionCommand("disconnect");
    disconnectButton.addActionListener(buttonListener);
    disconnectButton.setEnabled(false);
    buttonPane.add(connectButton);
    buttonPane.add(disconnectButton);
    optionsPane.add(buttonPane);
    return optionsPane;
    // Initialisation de toutes les composantes GUI et affichage du frame
    private static void initGUI() {
    // Configuration du status bar
    // cr�ation d'un autre pannel statusBar qui se compose d'un petit carr�
    // color� et un label indiquant le mode de connexion
    statusField = new JLabel(); //Label indiquant l'�tat de la connexion
    statusField.setText(statusMessages[DISCONNECTED]);
    statusColor = new JTextField(1); //carr� color� indiquant l'�tat de la connection grace a des couleurs
    statusColor.setBackground(Color.red);
    statusColor.setEditable(false);
    statusBar = new JPanel(new BorderLayout());
    statusBar.add(statusColor, BorderLayout.WEST);
    statusBar.add(statusField, BorderLayout.CENTER);
    // Configuration du pannel optionsPane en appelant la methode d'initiation
    // de ce dernier
    JPanel optionsPane = initOptionsPane();
    // Creation et configuration du pannel chatPane qui contient un
    // textarea au centre avec une barre defilante verticale et un textfield
    // au sud pour faire rentrer les messages
    JPanel chatPane = new JPanel(new BorderLayout());
         JPanel emoticon = new JPanel(new GridLayout(2, 5));
    b1 = new JButton (sourrire);
    b1.setToolTipText("Un Sourire");
    // b1.addActionListener();
    emoticon.add(b1);
    b2 = new JButton (gsourrire);
    b2.setToolTipText("Un Grand Sourire");
    // b2.addActionListener();
    emoticon.add(b2);
    b3 = new JButton (triste);
    b3.setToolTipText("Triste");
    // b3.addActionListener();
    emoticon.add(b3);
    b4 = new JButton (grimace);
    b4.setToolTipText("Grimace");
    // b4.addActionListener();
    emoticon.add(b4);
    b5 = new JButton (pleure);
    b5.setToolTipText("Pleure");
    // b5.addActionListener();
    emoticon.add(b5);
    b6 = new JButton (bec);
    b6.setToolTipText("Un bec");
    // b6.addActionListener();
    emoticon.add(b6);
    b7 = new JButton (coeur);
    b7.setToolTipText("Un coeur pour toi");
    // b7.addActionListener();
    emoticon.add(b7);
    b8 = new JButton (fache);
    b8.setToolTipText("Fache");
         // b8.addActionListener();
         emoticon.add(b8);
    b9 = new JButton (lunettes);
    b9.setToolTipText("Je suis Cool");
    // b9.addActionListener();
    emoticon.add(b9);
    b10 = new JButton (clinoeil);
    b10.setToolTipText("Clin d'Oeil");
    //b10.addActionListener(new ActionAdapter2());
    emoticon.add(b10);
    emoticon.addActionListener(new ActionAdapter() {
    public void actionPerformed(ActionEvent e) {
                             String image = chatLine.setImage().toString();
                             appendToChatBox(image);
                             chatLine.selectAll();
                             sendString(image)
                             chatLine.setText(" ");
    emoticon.setVisible(true);
    //b1 = setVisible(true);
    chatText = new JTextArea(10, 100);
    chatText.setBackground(new Color(0.98f, 0.97f, 0.85f));
    chatText.setLineWrap(true);
    chatText.setEditable(false);
    chatText.setForeground(Color.blue);
    JScrollPane chatTextPane = new JScrollPane(chatText,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    chatLine = new JTextField(10);
    chatLine.setBackground(new Color(0.98f, 0.97f, 0.85f));
    chatLine.setForeground(Color.blue);
    chatLine.setEnabled(false);
    chatLine.addActionListener(new ActionAdapter() {
    public void actionPerformed(ActionEvent e) {
    String s = chatLine.getText();
    if (!s.equals("")) {
    appendToChatBox(user=username.getText()+" dit : \n" + s + "\n");
    chatLine.selectAll();
    // Envoi de la chaine entr�e
    sendString(s);
    chatLine.setText("");
    chatPane.add(chatLine, BorderLayout.SOUTH);
    chatPane.add(chatTextPane, BorderLayout.NORTH);
    chatPane.setPreferredSize(new Dimension(300, 300));
         chatPane.add(emoticon, BorderLayout.CENTER);
    // Ajout des pannels dans le pannel principal (mainPane)
    JPanel mainPane = new JPanel(new BorderLayout());
    mainPane.add(statusBar, BorderLayout.SOUTH);
    mainPane.add(optionsPane, BorderLayout.WEST);
    mainPane.add(chatPane, BorderLayout.CENTER);
    // Configuration du frame (mainFrame)
    mainFrame = new JFrame("Chat");
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // la m�thode setDefaultCloseOperation(int)provient de la classe javax.swing.JDialog
         // Elle specifi l'op�ration qui sera ex�cut�e par d�fault lorsque
         // l'utilisateur initialisera une fermeture de session
    mainFrame.setContentPane(mainPane);
    mainFrame.setSize(mainFrame.getPreferredSize());
         // la m�thode getPreferredSize() provient de la classe java.awt
         // Retourne la grosseur "pr�f�r�e" du container.
    mainFrame.setLocation(200, 200);
    // la m�thode setLocation(double, double) provient de la classe java.awt.Point
         // elle permet de specifiez un emplacement d'un point a des coordonn�es de type Float
    mainFrame.pack();
    // la m�thode pack() provient de la class AWT.Window, elle permet a la fenetre
    // d'�tre ajuster a la grosseur et a la mise en page des sous-composantes de celle-ci
    mainFrame.setVisible(true);
    // Le thread qui permet le changement des composantes GUI pendant le
    // changement de l'etat
    private static void changeStatusTS(int newConnectStatus, boolean noError) {
    // Changer l'etat si valide
    if (newConnectStatus != NULL) {
              connectionStatus = newConnectStatus;
    // S'il n'y a aucunes erreur, afficher le bon message de l'etat
    if (noError) {
    statusString = statusMessages[connectionStatus];
    // Autrement, afficher le message d'erreur
    else {
    statusString = statusMessages[NULL];
    System.out.println("Echec lors de la connexion");
    // Appel a la routine de run()(Runnable interface) sur la gestion des erreurs
    // et la mise a jours des composantes GUI grace au thread
    SwingUtilities.invokeLater(tcpObj);
    // Le changement des composantes GUI sans aucun pendant le
    // changement de l'etat
    private static void changeStatusNTS(int newConnectStatus, boolean noError) {
    // Changer l'etat si valide
    if (newConnectStatus != NULL) {
    connectionStatus = newConnectStatus;
    // S'il n'y a aucunes erreur, afficher le bon message de l'etat
    if (noError) {
    statusString = statusMessages[connectionStatus];
    // Autrement, afficher le message d'erreur
    else {
    statusString = statusMessages[NULL];
    // Appel a la routine de run()(Runnable interface) sur la gestion des erreurs
    // en utilisant le thread
    tcpObj.run();
    // L'ajout au chat box avec l'utilisation du Thread
    private static void appendToChatBox(String s) {
    synchronized (toAppend) {
    toAppend.append(s);
    System.out.println(s);
    // Ajouter le text au "send-buffer"
    private static void sendString(String s) {
    synchronized (toSend) {
    toSend.append(user=username.getText()+ " dit : \n" + s + "\n");
    // Nettoyage pour le debranchement
    private static void cleanUp() {
    try {
    if (hostServer != null) {
    hostServer.close();
    hostServer = null;
    catch (IOException e) { hostServer = null; }
    try {
    if (socket != null) {
    socket.close();
    socket = null;
    catch (IOException e) { socket = null; }
    try {
    if (in != null) {
    in.close();
    in = null;
    catch (IOException e) { in = null; }
    if (out != null) {
    out.close();
    out = null;
    // Verification de l'etat courrant et ajustement de "enable/disable"
    // en fonction de l'etat
    public void run() {
    switch (connectionStatus) {
    case DISCONNECTED:
    connectButton.setEnabled(true);
    disconnectButton.setEnabled(false);
    ipField.setEnabled(true);
    portField.setEnabled(true);
    username.setEnabled(true);
    hostOption.setEnabled(true);
    guestOption.setEnabled(true);
    chatLine.setText("");
    chatLine.setEnabled(false);
    statusColor.setBackground(Color.red);
    break;
    case DISCONNECTING:
    connectButton.setEnabled(false);
    disconnectButton.setEnabled(false);
    ipField.setEnabled(false);
    portField.setEnabled(false);
    hostOption.setEnabled(false);
    guestOption.setEnabled(false);
    chatLine.setEnabled(false);
    statusColor.setBackground(Color.orange);
    break;
    case CONNECTED:
    connectButton.setEnabled(false);
    disconnectButton.setEnabled(true);
    ipField.setEnabled(false);
    portField.setEnabled(false);
    hostOption.setEnabled(false);
    username.setEnabled(false);
    guestOption.setEnabled(false);
    chatLine.setEnabled(true);
    statusColor.setBackground(Color.green);
    break;
    case BEGIN_CONNECT:
    connectButton.setEnabled(false);
    disconnectButton.setEnabled(false);
    ipField.setEnabled(false);
    portField.setEnabled(false);
    hostOption.setEnabled(false);
    username.setEnabled(false);
    guestOption.setEnabled(false);
    chatLine.setEnabled(true);
    chatLine.grabFocus();
    statusColor.setBackground(Color.orange);
    break;
    // S'assurer que l'etat des champs bouton/texte sont consistent
    // avec l'etat interne
    ipField.setText(hostIP);
    portField.setText((new Integer(port)).toString());
    hostOption.setSelected(isHost);
    guestOption.setSelected(!isHost);
    statusField.setText(statusString);
    chatText.append(toAppend.toString());
    toAppend.setLength(0);
    mainFrame.repaint();
    // Procedure principale
    public static void main(String args[]) {
    String s;
    initGUI();
    while (true) {
    try {
    Thread.sleep(10);
         // Verification a toute les 10 ms
    catch (InterruptedException e) {}
    switch (connectionStatus) {
    case BEGIN_CONNECT:
    try {
    // Essai de configuration du serveur si "host"
    if(user != ""){
         if (isHost) {
         hostServer = new ServerSocket(port);
         socket = hostServer.accept();
         // Si invit�, essai de branchement au serveur
         else {
         socket = new Socket(hostIP, port);
    in = new BufferedReader(new
    InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);
    changeStatusTS(CONNECTED, true);
    System.out.println("Ouverture de la session: \n" + socket);
              else{
              JOptionPane.showMessageDialog(null, "Erreur, vous devez entrer un nom d'utilisateur", "Erreur", JOptionPane.PLAIN_MESSAGE);
                        changeStatusTS(DISCONNECTED, false);
    // Si erreur, nettoyage et envoi du message d'erreur
    catch (IOException e) {
    cleanUp();
    changeStatusTS(DISCONNECTED, false);
    break;
    case CONNECTED:
    try {
    // Envoi de data
    if (toSend.length() != 0) {
    out.print(toSend);
    out.flush();
    toSend.setLength(0);
    changeStatusTS(NULL, true);
    // Reception de data
    if (in.ready()) {
    s = in.readLine();
    if ((s != null) && (s.length() != 0)) {
    // Verification de la fin de la transmission
    if (s.equals(END_CHAT_SESSION)) {
    changeStatusTS(DISCONNECTING, true);
    // Autrement, reception du texte
    else {
    appendToChatBox( s + "\n");
    changeStatusTS(NULL, true);
    catch (IOException e) {
    cleanUp();
    changeStatusTS(DISCONNECTED, false);
    break;
    case DISCONNECTING:
    // Dis aux autres fenetre de chat de se d�brancher aussi
    out.print(END_CHAT_SESSION);
    out.flush();
                   System.out.println("Fermeture de la session");
    // Nettoyage (ferme les streams/sockets)
    cleanUp();
    changeStatusTS(DISCONNECTED, true);
    break;
    default: break; // ne fait rien
    // Certaines interfaces �couteurs sont accompagn�es d'adaptateurs qui
    //implementent toutes les methodes de l'interface et evitent de les lister.
    class ActionAdapter implements ActionListener {
    public void actionPerformed(ActionEvent e) {}
    ////////////////////////////////////////////////////////////////////

Maybe you are looking for