greenorange
greenorange

Reputation: 13

I need help on putting functions on Java GUIs

I'm a student that's new to Java programming since we used C in our previous courses. I recently learned how to make GUIs using the builder design in Netbeans and Eclipse, however i still don't know how to put functions on each of the buttons and fields yet even though i already have a separate working code for the functions. I've been working on a Base Converter and this is the code for my UI and the separate code for the Functions.

public class BaseConverter extends javax.swing.JFrame {

/**
 * Creates new form BaseConverter
 */
public BaseConverter() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jComboBox1 = new javax.swing.JComboBox<>();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

    jComboBox1.setFont(new java.awt.Font("Tempus Sans ITC", 1, 14)); // NOI18N
    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Decimal", "Binary", "Octal", "Hexadecimal" }));
    getContentPane().add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(56, 40, 150, 40));

    jTextField1.setFont(new java.awt.Font("Tempus Sans ITC", 1, 14)); // NOI18N
    jTextField1.setText("Enter number");
    getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 40, 180, 40));

    jButton1.setFont(new java.awt.Font("Tempus Sans ITC", 1, 14)); // NOI18N
    jButton1.setText("Convert");
    getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 40, 90, 40));

    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);

    getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 120, 440, 180));

    jLabel1.setFont(new java.awt.Font("Tempus Sans ITC", 1, 14)); // NOI18N
    jLabel1.setText("Result:");
    getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 100, -1, -1));

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(BaseConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(BaseConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(BaseConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(BaseConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new BaseConverter().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration                   

}

And here's my separate code for the functions.

import java.util.Scanner;

public class BaseConverter {

public static void main(String[] args) {
        //declaring a scanner
        Scanner input = new Scanner(System.in);
        String ans = input.nextLine();
        System.out.println("Would you like to calculate for Decimal, Binary, Octal and Hexadecimal?");

         while ((ans.equals ("Yes")))
        {
            int c;
            //asks the user what is the value type
            System.out.println("What is the value type?");
            System.out.println("1 - Hexadecimal");
            System.out.println("2 - Decimal");
            System.out.println("3 - Octal");
            System.out.println("4 - Binary");
            c = input.nextInt();

            switch(c){

                //if the user inputs 1
                case 1:
                System.out.println("Please enter the Hexadecimal value: "); //prompts the user to enter the hexadecimal value
                String hexadecimal = input.next(); //scanning the hexadecimal
                System.out.println("The Hexadecimal number is: " + hexadecimal); //shows the givenn hexadecimal value
                int decimal = Integer.parseInt(hexadecimal, 16); //converts hexadecimal to decimal
                System.out.println("Decimal: " + decimal ); //shows the converted decimal
                String binary = Integer.toBinaryString(decimal); //converting the converted decimal to binary
                System.out.printf("Binary:  " + binary ); //shows the converted binary
                String octal = Integer.toOctalString(decimal); //converts the decimal to octal
                System.out.printf("Octal: " + octal ); //shows the converted octal
                break; //break

                //if the user inputs 2
                case 2:
                System.out.println("Please enter the Decimal Number: "); //prompts the user to enter the decimal number
                int dec = input.nextInt(); //scanning the decimal
                System.out.println("The Decimal number is: " + dec ); //shows the decimal
                String bin = Integer.toBinaryString(dec); //converting the decimal to binary
                System.out.println("Binary: " + bin ); //shows the equivalent in binary
                String oct = Integer.toOctalString(dec); //converting decimal to octal
                System.out.println("Octal: " + oct); //shows the equivalent octal number
                String hex = Integer.toHexString(dec); //converting decimal to hexadecimal
                System.out.println("Hexadecimal: " + hex); //shows the hexadecimal equivalent
                break; //break

                //if the user inputs 3
                case 3:
                System.out.println("Please enter the Octal Number: "); //prompts the user to input the octal number
                String octa = input.next(); //scans the octal number
                int de = Integer.parseInt(octa, 8); //converts octal to decimal
                System.out.println("Decimal: " + de); //shows the decimal equivalent
                String bi = Integer.toBinaryString(de); //converts the decimal to binary
                System.out.println("Binary: " + bi); //shows the binary equivalent
                String he = Integer.toHexString(de); //converts the decimal to hexadecimal
                System.out.println("Hexadecimal: " + he); //shows the hexadecimal equivalent
                break; //break

                //if the user inputs 4
                case 4:
                System.out.println("Please enter the Binary number: "); //prompts the user to enter the binary number
                String q = input.next(); //scans the binary number
                int r = Integer.parseInt(q, 2); //converts binary to decimal
                System.out.println("Decimal: " + r); //shows the decimal equivalent
                String oc = Integer.toOctalString(r); //converts decimal to octal
                System.out.println("Octal: " + r); //displays the octal value
                String l = Integer.toHexString(r); //converts decimal to hex
                System.out.println("Hexadecimal: " + l); //displays the hex value
                break;
            }
        }
          while((ans.equals("No")))
          {
              System.out.println("You have successfully exit!");
              break;
           }
        }
      }

Is there anyone that can teach me how to put these functions into the GUI that i created?

enter image description here

Upvotes: 1

Views: 936

Answers (3)

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

Some hints to get you starting. Right after the line initComponents(); insert something like this:

    jButton1.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent e) {
         // Get values from jComboBox1.get???() and jTextField1.get???()
         // Do your calculations
         // Show the result with jTextArea1.set???(???)
       }
    });

Upvotes: 0

user3437460
user3437460

Reputation: 17454

Actually, I would rather you read up on the tutorial first as this place is not a replacement for your tutorial class.

JButton Tutorial: How to use buttons

To learn how to use JCombobox: How to use ActionListener on a ComboBox

Anyway, this is how it goes..

class MainPanel extends JPanel //in your case, you extends to JFrame
{
    private JButton btn;

    public MainPanel(){
        //other initializations
        btn.add(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                //invoke your conversion method here..
                //e.g: 
                //txtResult.setText(convert(txtInput.getText()));
            }
        });
    }
}

Note that if you implementing a GUI, you are not going to use Scanner(System.in) to receive input anymore. All input & interactions with the user will go to the JComponents such as textboxes and buttons.

Upvotes: 1

user7291698
user7291698

Reputation: 1990

to set an action on a JButton, use code like this:

    JButton button = new JButton("click me");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("clicked");
        }
    });

Upvotes: 0

Related Questions