Swing Components in Java: Part 1

Today in this article I will show you the basic Swing components of JAVA language. How to handle these components and how to work with these components. In this article we will cover these components.

Today in this article I will show you the basic Swing components of the Java language, including how to handle these components and how to work with these components. In this article we will cover the following components.

  • Frame

  • Buttons

  • Combo Box

  • Check Box

  • Radio Button

  • Menu Bar

  • Open File Dialog Box

  • Save File Dialog Box

  • Password Field

  • Text Field

  • Text Area

  • Progress Bar

Start

  • First  seelct "File" >> "New project" then select Java application and then "OK".

  • Then right-click on your package and click "Add new item" then add a new Frame from there.

  •  Drag the Menu bar from the pallet and right-click on the file then click "Add" from the pallet then click menu item.

  •  Drag a combo box from the pallet on the frame and go to the properties of the component and edit its models property and write like I C#, Java, PHP and so on.

  • Drag two buttons from the pallet as in the diagram below.

  • Drag a text field and text area from the pallet.

  • Drag check boxes and radio buttons from the pallet on the Frame.

  • Drag a File Chooser from the pallet on Frame.

  • Double-click on the component then its action performed event will be generated.

MenuBar Item Event

Menu Bar Item events

Open File Dialog

jMenuItem1 event

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt)

{   

    //here filechooser method open dialog calls and open it.

    int returnVal = jFileChooser1.showOpenDialog( this ); 

    if (returnVal == JFileChooser.APPROVE_OPTION) // here check that user press ok/yes button

    {

        File file = jFileChooser1.getSelectedFile( );//here get path of the file.

        String file_name = file.toString( );

        try

        {

            FileReader FR=new FileReader(file_name);//file reader object receive the path of the file.

            jTextArea1.read(FR, evt);//here assign the FR object to the jTextArea1.

        }

        catch(Exception e)

        {

      

        }

    }

}

Save File Dialog Box

jMenuItem2 event

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt)

{

    int returnVal = jFileChooser1.showSaveDialog( this );//open save file dialog box

    if (returnVal == JFileChooser.APPROVE_OPTION) 

    {

        File file = jFileChooser1.getSelectedFile( );

        String file_name = file.toString( );

        try

        {

            FileWriter FW=new FileWriter(file_name,false);//file writer object for writing the file.

            String AllText=jTextArea1.getText();

            FW.write(jTextArea1.getText());

            FW.write(AllText);//here will save your file

            FW.flush();

            FW.close();

        }

        catch(Exception e)

        {

      

        }

    }

}

Combo Box

jButton1 event.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)

{

    String s=(String)jComboBox1.getSelectedItem();// here we get the selected item from combo box

    jTextField1.setText(s);//assign to text field

}

Check Box and Radio Buttons

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)

{

    String s1="";

    String s2="";

    //Here we check check box is selected or not. 

    if(jCheckBox1.isSelected())

    {

        s1=s1+""+jCheckBox1.getText()+"\n";//here assign the check box value to the string.

    }

    if(jCheckBox2.isSelected())

    {

        s1=s1+""+jCheckBox2.getText()+"\n";

    }

    if(jCheckBox3.isSelected())

    {

        s1=s1+""+jCheckBox3.getText()+"\n";

    }

    if(jCheckBox4.isSelected())

    {

        s1=s1+""+jCheckBox4.getText()+"\n";

    }

}

jTextArea1.setText(s1);//here assign the all check box which are selected to the text area.

//here we check  same for the Radio buttons.

Note: In Java if we select multiple radio buttons then it will also select, although its task is that only one item is selected from multiple radio buttons so for this we will use a Button Group and add all the radio buttons to it.

Add the following code to your code.

jButton2 event.

private void groupButton()

{

    ButtonGroup bg1 = new ButtonGroup( );

    bg1.add(jRadioButton1);

    bg1.add(jRadioButton2);

    bg1.add(jRadioButton3);

}

 

    if(jRadioButton1.isSelected())

    {

        s2=jRadioButton1.getText();

    }

    if(jRadioButton2.isSelected())

    {

        s2=jRadioButton2.getText();

    }

    if(jRadioButton3.isSelected())

    {

        s2=jRadioButton3.getText();

    }

    JOptionPane.showMessageDialog( null, s2 );

    

}

Progress Bar

Sample of JProgressBar

private void progresbar()

{

    // create frame dynamicaly

    JFrame f = new JFrame("JProgressBar Sample");

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container content = f.getContentPane();

    //create prograss bar object   

    JProgressBar progressBar = new JProgressBar();

    progressBar.setValue(31);

    progressBar.setStringPainted(true);

    Border border = BorderFactory.createTitledBorder("Reading...");

    progressBar.setBorder(border);

    content.add(progressBar, BorderLayout.NORTH);

    f.setSize(300, 100);

    f.setVisible(true);

}

Password Field

Password Field

private void passwordfield()

{

  final JFrame frame = new JFrame("JPassword Usage Demo");

    JLabel jlbPassword = new JLabel("Enter the password: ");

    JPasswordField jpwName = new JPasswordField(10);//password field object and its length

    jpwName.setEchoChar('*');//sets the pass character

    //add action listener by code.                    

    jpwName.addActionListener(new ActionListener() 

    {

        public void actionPerformed(ActionEvent e) 

        {

            JPasswordField input = (JPasswordField) e.getSource();

            char[] password = input.getPassword();

            if (isPasswordCorrect(password)) 

            {

                JOptionPane.showMessageDialog(frame,"Correct  password.");

            }

            else 

            {

                JOptionPane.showMessageDialog(frame,"Sorry. Try again.""Error Message", JOptionPane.ERROR_MESSAGE);

            }

        }

    });

 

    JPanel jplContentPane = new JPanel(new BorderLayout());

    jplContentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    jplContentPane.add(jlbPassword, BorderLayout.WEST);

    jplContentPane.add(jpwName, BorderLayout.CENTER);

    frame.setContentPane(jplContentPane);

    frame.addWindowListener(new WindowAdapter() 

    {

        public void windowClosing(WindowEvent e) 

        {

            System.exit(0);

        }

    });

    frame.pack();

    frame.setVisible(true);

}

Function to check password is correct.

private static boolean isPasswordCorrect(char[] inputPassword) 

{

    char[] actualPassword = { 'e''h''t''e''s''h''a','m' };

    if (inputPassword.length != actualPassword.length)

        return false// Return false if lengths are unequal

        for (int i = 0; i < inputPassword.length; i++)

            if (inputPassword[i] != actualPassword[i])

                return false;

            return true;

}

Main Function

public static void main(String[] args) 

{

    FP1 fp1=new FP1();        

    fp1.progresbar();

    fp1.passwordfield();

}