Member Avatar for mehnihma

How can I turn radio button in another class which I cannot change but I need to turn it on from another class?
How can I pass action event to it?

Thanks

Recommended Answers

All 15 Replies

If you can't change the class where the button is defined, and that class doesn't make th button public, and it doesn't provide any public methods to access it, then it's not going to be easy. Maybe you can get access to the frame or window that contains the button, then you can navigate the frame's child objects to find the button. If all else fails you can use java Reflection to access the class's private members
Of course there's no guarantee that simply "turning it on" won't screw up some or all of the private logic in the class.

Member Avatar for mehnihma

I will try something...

also why this is not working?

if (!cmdResponse.equals("OK")) {
                jtaRecvText
                        .setText("Invalid response from server - no text processed.");
                jrbError.setEnabled(true); // enable error button
                s.close();
                return;
            }
Member Avatar for mehnihma

It wonnt turn the button on

Can you post more code that shows where the components are defined and where they are being shown in the GUI?

Member Avatar for mehnihma

I need to enable error button on error

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;



public class CaesarClient extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTextArea jtaSendText;
    private JTextArea jtaRecvText;
    private JPanel jpTextPanel;
    private JButton jbSend;
    private JButton jbExit;
    private JPanel jpButtonPanel;
    private JPanel jpRadioPanel;
    private ButtonGroup bgCmds;
    private JRadioButton jrbEncrypt;
    private JRadioButton jrbDecrypt;
    private JRadioButton jrbError;

    /** Validate command line argument and call create GUI constructor */
    public static void main(String[] args) {
        // test the arguments - need a host to talk to
        if (args.length <= 0) {
            System.out.println("You must specify a host.");
            System.exit(1);
        }

        // create the client
        CaesarClient cc = new CaesarClient(args[0]);
    }

    /* Constructor sets up the GUI */
    public CaesarClient(String host) {
        // setup the frame for the display
        setTitle("Caesar Cipher Client");
        setSize(400, 400);

        // setup the frame components
        // Text areas first
        jtaSendText = new JTextArea("Send text", 10, 50);
        jtaSendText.setBorder(new EtchedBorder());
        jtaRecvText = new JTextArea("Recv text", 10, 50);
        jtaRecvText.setBorder(new EtchedBorder());
        jpTextPanel = new JPanel();
        jpTextPanel.setLayout(new GridLayout(2, 1));
        // place the text areas in JScrollPanes
        JScrollPane jbSendPane = new JScrollPane(jtaSendText);
        JScrollPane recvPane = new JScrollPane(jtaRecvText);
        jpTextPanel.add(jbSendPane);
        jpTextPanel.add(recvPane);

        // Buttons send & next
        jbSend = new JButton("Send");
        jbExit = new JButton("Exit");
        jpButtonPanel = new JPanel();
        jpButtonPanel.add(jbSend);
        jpButtonPanel.add(jbExit);

        // handle the jbExit button
        jbExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });

        // [X] close handler
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });

        // Radiobuttons last
        jrbEncrypt = new JRadioButton("Encrypt");
        jrbDecrypt = new JRadioButton("Decrypt");
        jrbError = new JRadioButton("Error");
        bgCmds = new ButtonGroup();
        bgCmds.add(jrbEncrypt);
        bgCmds.add(jrbDecrypt);
        bgCmds.add(jrbError);
        jpRadioPanel = new JPanel();
        jpRadioPanel.add(jrbEncrypt);
        jpRadioPanel.add(jrbDecrypt);
        jpRadioPanel.add(jrbError);

        // handle the jbSend button
        SendHandler sh = new SendHandler(host, jtaSendText, jtaRecvText,
                jrbEncrypt, jrbDecrypt, jrbError);
        jbSend.addActionListener(sh);
        //jrbError.addActionListener(sh);

        // now add the components to the frame
        add(jpRadioPanel, BorderLayout.NORTH);
        add(jpButtonPanel, BorderLayout.SOUTH);
        add(jpTextPanel, BorderLayout.CENTER);

        setLocationRelativeTo(null);
        setVisible(true);
    }

}

/**
 * This class contains the code that communicates with the server and gets
 * resulting data back. It will be called as a result of the jbSend button being
 * pressed.
 */
class SendHandler implements ActionListener, CaesarConstants {
    String host;
    JTextArea jtaSendText;
    JTextArea jtaRecvText;
    JRadioButton jrbEncrypt;
    JRadioButton jrbDecrypt;
    JRadioButton jrbError;

    /** constructor sets attributes to references to the client */
    public SendHandler(String h, JTextArea st, JTextArea rt, JRadioButton enc,
            JRadioButton dec, JRadioButton jrbError) {
        host = h;
        jtaSendText = st;
        jtaRecvText = rt;
        jrbEncrypt = enc;
        jrbDecrypt = dec;
        this.jrbError = jrbError;
    }

    /** performs all the connection work */
    public void actionPerformed(ActionEvent ae) {
        // setup the socket connection to the host
        Socket s = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            s = new Socket(host, PORT_NUMBER); // Change this to the interface's
                                                // PORT_NUMBER
            in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            out = new PrintWriter(s.getOutputStream());
        } catch (UnknownHostException uhe) {
            jtaRecvText.setText("Unable to connect to host.");
            return;
        } catch (IOException ie) {
            jtaRecvText.setText("IOException communicating with host.");
            this.jrbError.setEnabled(true); // enable error button
            return;
        }

        // Send the command based on the selected radio button option
        try {
            if (jrbEncrypt.isSelected()) {
                out.println("ENCRYPT");
                out.flush();
            }

            if (jrbDecrypt.isSelected()) {
                out.println("DECRYPT");
                out.flush();
            }

            if (jrbError.isSelected()) {
                out.println("ERROR");
                out.flush();
            }

            if (!jrbEncrypt.isSelected() && !jrbDecrypt.isSelected()
                    && !jrbError.isSelected()) {
                jtaRecvText.setText("You must first select a command "
                        + "(Encrypt/Decrypt/Error)");
                jrbError.setEnabled(true); // enable error button
                s.close();
                return;
            }

            // get the results back
            String cmdResponse = in.readLine();
            if (!cmdResponse.equals("OK")) {
                jtaRecvText
                        .setText("Invalid response from server - no text processed.");
                this.jrbError.setEnabled(true); // enable error button
                s.close();
                return;
            }

            // Send over the text
            jtaRecvText.setText(""); // clear text area
            String orig = jtaSendText.getText();
            if (orig.indexOf('\n', 0) == -1) { // no embedded newlines
                out.println(orig);
                out.flush();
                jtaRecvText.append(in.readLine() + "\n");
            } else { // embedded newlines detected
                // loop to jbSend over all text
                int start = 0;
                int location;
                while ((location = orig.indexOf('\n', start)) != -1) {
                    String tmpStr = orig.substring(start, location);
                    out.println(tmpStr);
                    out.flush();
                    jtaRecvText.append(in.readLine() + "\n");
                    start = location + 1;
                }

                if (start < orig.length() - 1) // str does not end in a newline
                {
                    String tmpStr = orig.substring(start);
                    out.println(tmpStr);
                    out.flush();
                    jtaRecvText.append(in.readLine() + "\n");
                }
            }

            // close the connection
            s.close();
        } catch (IOException ie) {
            jtaRecvText.setText("IOException communicating with host.");
            this.jrbError.setEnabled(true); // enable error button
            return;
        }
    }

}

and this

/**
    CaesarConstants - Define constant for the Caesar Cipher client and server.
*/
public interface CaesarConstants {
    int PORT_NUMBER     = 16789;
    int DEFAULT_SHIFT = 3;
}

The code you posted does not compile without errors. I get 63 errors.
For one thing it is missing the import statements.

jrbError is a class variable in the SendHandler class. It is not the same as the same named variable in the CaesarClient class.
If you make SendHandler an inner class to CaesarClient then it will be able to access its variables.

Member Avatar for mehnihma

I have corrected it, it is missing server component but for this is not needed argument can be IP address

Without reading all of the code, you cant change a variable/object from another class when you declare it as 'private'. If you declare it as 'protected' you should be able.

protected JRadioButton jrbError;

How do you execute the code to see the problem?

When I add code to disable the button so it starts disabled and then test by pressing the Send button, the button is enabled and an error message is displayed in the lower text box.
Can you explain what the problem you are having is?

Member Avatar for mehnihma

if there is and error is should select error radio button but it does not to that for me?
Lets say when you frist run the program nothing is selected and you press send it should choose error button

Member Avatar for mehnihma

where do you add to disable it?

jrbError = new JRadioButton("Error");
jrbError.setEnabled(false); //<<<<<<<<<<<<<<<<<<<<

I added the second statement

it should choose error button

Enabling a button is different from selecting it. Which is it you want to do?

Member Avatar for mehnihma

Select it

Look at the API doc for the method to use.

Member Avatar for mehnihma

jrbError.setSelected(true); // enable error button

it works now but it was giving me error before, don t get it why?

I think I did something worng but it works now

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.