Document Details

Uploaded by Deleted User

Tags

java swing java gui java programming computer programming

Summary

This document is a presentation about Introduction to Java Swing, covering topics including Java Swing, Java AWT, and examples of Java Swing programs. It also discusses creating a simple calculator using Java and JFrame.

Full Transcript

INTRODUCTION TO JAVA SWING 3RD QUARTER IDENTIFY THE GIVEN IMAGES. IDENTIFY THE GIVEN IMAGES. INTRODUCTION TO JAVA SWING Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit [AWT]. Java Swing offers much-improved function...

INTRODUCTION TO JAVA SWING 3RD QUARTER IDENTIFY THE GIVEN IMAGES. IDENTIFY THE GIVEN IMAGES. INTRODUCTION TO JAVA SWING Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new components, expanded components features, and excellent event handling with drag-and-drop support. DIFFERENCE BETWEEN JAVA SWING AND JAVA AWT EXAMPLE OF JAVA SWING PROGRAMS EXAMPLE 1: DEVELOP A PROGRAM USING LABEL (SWING) TO DISPLAY THE MESSAGE “TLE9 WEB SITE CLICK”: Project Name: tle9 package tle9; import java.io.*; import javax.swing.*; // Main class public class TLE9 { // Made the class public // Main driver method public static void main(String[] args) { // Creating instance of JFrame JFrame frame = new JFrame(); // Creating instance of JButton JButton button = new JButton(" GFG WebSite Click"); // x axis, y axis, width, height button.setBounds(150, 200, 220, 50); // Adding button in JFrame frame.add(button); // 400 width and 500 height frame.setSize(500, 600); // Using no layout managers frame.setLayout(null); // Making the frame visible frame.setVisible(true); } } Code Breakdown Package Declaration: package tle9; Indicates that the class TLE9 belongs to the package named tle9. Packages are used in Java to group related classes and to avoid naming conflicts. Import Statements: import java.io.*; import javax.swing.*; java.io.* - is typically used for input and output operations. javax.swing.* - imports the Swing components used for creating the GUI, including JFrame and JButton Code Breakdown Class Definition: public class TLE9; This line defines the class TLE9. The keyword public indicates that this class can be accessed from other classes and packages. Main Method: Public static void main(String[] args { This is the main entry point of the Java application. The main method is where the program starts execution. The String[] args parameter allows command-line arguments to be passed to the program. Code Breakdown Creating the JFrame: JFrame frame = new Jframe(); An instance of JFrame is created. JFrame is a top-level container that represents a window where components can be added. Creating a JButton: Jbutton button = new Jbutton(“ GFG WebSite Click); A JButton is created with the label "GFG WebSite Click". This button can be clicked by the user. Code Breakdown Setting Button Bounds: button.setBounds(150, 200, 220, 50); This line specifies the position and size of the button within the frame. The parameters are: 150: x-coordinate (horizontal position) of the button from the left. 200: y-coordinate (vertical position) of the button from the top. 220: width of the button. 50: height of the button. Adding Button to the Frame: Frame.add(button); The button is added to the JFrame. This makes the button part of the window that will be displayed. Code Breakdown Setting Frame Size: frame.setSize(500,600); This line sets the dimensions of the JFrame to 500 pixels wide and 600 pixels tall. Setting Layout: frame.setLayout(null); The layout manager is set to null, which means that the programmer will manually specify the positions and sizes of the components (like the button). This gives more control over the component layout. Code Breakdown Making the Frame Visible: frame.setVisible(true); This line makes the JFrame visible on the screen. By default, a JFrame is not visible until this method is called. EXAMPLE 2: WRITE A PROGRAM TO CREATE THREE BUTTONS WITH CAPTION OK, SUBMIT, CANCEL. Project Name: buttonExample import java.awt.*; import java.awt.event.*; // Add a window listener to handle window closing f.addWindowListener(new WindowAdapter() { public class ButtonExample { public void windowClosing(WindowEvent // Constructor to set up the frame and buttons e) { f.dispose(); // Close the frame and ButtonExample() { exit the application // Create a frame } Frame f = new Frame("Button Example"); }); // Button 1: OK button // Set frame properties Button b1 = new Button("OK"); f.setSize(300, 300); b1.setBounds(100, 50, 80, 30); f.setLayout(null); f.add(b1); f.setVisible(true); } // Button 2: Submit button Button b2 = new Button("SUBMIT"); // Main method b2.setBounds(100, 100, 80, 30); public static void main(String[] args) { f.add(b2); new ButtonExample(); } // Button 3: Cancel button } Button b3 = new Button("CANCEL"); b3.setBounds(100, 150, 80, 30); f.add(b3); Continuation of the code… Code Breakdown Import Statements: Import java.awt.*; Import java.awt.event.*; These lines import classes needed to create the graphical elements (like windows and buttons) and to handle events (like clicking buttons). Constructor: ButtonExample() { This is a special method that runs when we create a new ButtonExample object. It sets up everything needed for the GUI. Code Breakdown Creating a Frame: Frame f = new Frame(“Button Example”); This line creates a new window (called a frame) with the title "Button Example". This is where our buttons will be displayed. Creating Buttons: Button b1 = new Button("OK"); b1.setBounds(100, 50, 80, 30); f.add(b1); Here, a button labeled "OK" is created. The setBounds method sets its position and size (x, y, width, height). This button is added to the frame. Code Breakdown Handling Window Closing: f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { f.dispose(); } }); This part adds a listener that waits for the window to close. When the user tries to close the window, the windowClosing method is triggered, which runs f.dispose(). This closes the window and frees up the resources. Code Breakdown Setting Frame Properties: f.setSize(300, 300); f.setLayout(null); f.setVisible(true); setSize(300, 300): This sets the size of the window to 300 pixels wide and 300 pixels tall. setLayout(null): This means we will manually position the buttons without using any automatic layout. setVisible(true): This makes the window visible on the screen. EXAMPLE 3: PROGRAM TO ADD CHECKBOX IN THE FRAME. Project Name: mainClass package main.pkgclass; // Package // Checkbox created declaration Checkbox c3 = new Checkbox("English"); c3.setBounds(100, 200, 80, 50); import java.awt.*; // Import for AWT f.add(c3); components // Checkbox created // Main class Checkbox c4 = new Checkbox("Marathi"); public class MainClass { c4.setBounds(100, 250, 80, 50); // Inner class Lan f.add(c4); class Lan { // Constructor to set up the UI // Frame properties Lan() { f.setSize(500, 500); // Frame created f.setLayout(null); Frame f = new Frame(); f.setVisible(true); } // Label created } Label l1 = new Label("Select known Languages"); // Main method l1.setBounds(100, 50, 150, 50); public static void main(String[] args) { f.add(l1); // Creating an instance of MainClass to instantiate Lan // Checkbox created MainClass mainInstance = new MainClass(); Checkbox c2 = new mainInstance.new Lan(); Checkbox("Hindi"); } c2.setBounds(100, 150, 50, 50); } f.add(c2); Continuation of the code… Code Breakdown Inner Class Declaration: Class Lan { This declares an inner class named Lan within MainClass. Inner classes are used to logically group classes that are only used in one place. Constructor of the Inner Class: Lan() { This is the constructor for the Lan class, which is called when an instance of Lan is created. It sets up the user interface. Code Breakdown Creating a Label: Label 11 = new Label(“Select known Language”); l1.setBounds(100, 50, 150, 50); f.add(l1); A label with the text "Select known Languages" is created. The setBounds method positions the label at (100, 50) and sets its width to 150 pixels and height to 50 pixels. The label is then added to the frame. Creating Checkboxes: Checkbox c2 = new Checkbox("Hindi"); c2.setBounds(100, 150, 50, 50); f.add(c2); A checkbox labeled "Hindi" is created and positioned at (100, 150) with a width of 50 pixels and height of 50 pixels. It is added to the frame. Code Breakdown Creating an Instance of MainClass: MainClass mainInstance = new MainClass(); mainInstance.new Lan(); An instance of MainClass is created. This is necessary because the inner class Lan can only be instantiated through an instance of MainClass. The line mainInstance.new Lan(); creates a new instance of the Lan class, which calls its constructor and sets up the user interface with the frame and checkboxes. THANKS! DO YOU HAVE ANY QUESTIONS? BUILDING YOUR FIRST JAVA GUI APPLICATION WITH JFRAME AND NETBEANS Java is one of the most popular programming languages, and it’s well- known for its cross-platform capabilities and robustness. When it comes to building graphical user interfaces (GUIs) in Java, JFrame is often the go-to choice. Combining this with NetBeans, a powerful and user- friendly Integrated Development Environment (IDE), makes GUI development straightforward and efficient. WHY USE JFRAME? JFrame is part of Java's Swing library, which is a set of APIs designed for building graphical user interfaces. It provides the essential functionality needed to create windows for your application, including the title bar, borders, and close buttons. CREATING A NEW PROJECT IN 1.Start NetBeans and go to File > New NETBEANS Project. 2.Select Java in the Categories section and Java Application in the Projects section, then click Next. 3.Name your project (e.g., JFrameDemo) and choose a location to save it. Ensure that the "Create Main Class" checkbox is selected. ADDING A JFRAME TO YOUR PROJECT 1.Right-click on the Source Packages in your Project window, then choose New > JFrame Form. 2.Name your JFrame (e.g., MainWindow) and click Finish. You should now see a new JFrame form open up in the NetBeans editor. The editor allows you to drag and drop components, making it easy to design your GUI. DESIGNING THE GUI NetBeans offers a Palette with a variety of components like buttons, labels, text fields, etc. Simply drag and drop the components onto your JFrame to design your GUI. Sample design Buttons (JButton): For performing actions. Labels (JLabel): For displaying text or images. Text Fields (JTextField): For user input. For example, let’s add a label, a text field, and a button to your JFrame: 1.Drag a JLabel from the Palette and drop it onto the JFrame. Change its text property to "Enter your name:". 2.Drag a JTextField next to the label. 3.Drag a JButton below the text field and change its text to "Submit". WRITING THE CODE Now that your GUI is designed, it’s time to add some functionality. Double-click on the Submit button to open the code editor. NetBeans automatically generates an ActionListener for the button, where you can write your custom code. RUNNING To YOUR APPLICATION run your application, simply click the Run button in the toolbar, or press F6. Your JFrame window should appear, allowing you to interact with the GUI. Creating a GUI application in Java using JFrame and NetBeans is a powerful way to develop user-friendly interfaces. With the drag-and-drop features of NetBeans and the flexibility of JFrame, you can quickly build and prototype applications. Experiment with different components and layouts to familiarize yourself with the tools. As you grow more comfortable, you can start adding more complex functionality, such as event handling, custom painting, and integrating external libraries. THANKS! DO YOU HAVE ANY QUESTIONS? SIMPLE CALCULATOR We will work through the layout and design of a GUI and add a few buttons and text fields. The text fields will be used for receiving user input and also for displaying the program output. The button will initiate the functionality built into the front end. The application we create will be a simple but functional calculator. EXERCISE 1: CREATING A PROJECT The first step is to create an IDE project for the application that we are going to develop. We will name our project NumberAddition. 1.Choose File > New Project. Alternatively, you can click the New Project icon in the IDE toolbar. 2.In the Categories pane, select Java with Ant. In the Projects pane, choose Java Application. Click Next. 3.Type NumberAddition in the Project Name field and specify a path, for example, in your home directory, as the project location. 4.(Optional) Select the Use Dedicated Folder for Storing Libraries checkbox and specify the location for the libraries folder. 5.Select the Create Main Class checkbox if it is selected. 6.Click Finish. EXERCISE 2: BUILDING THE FRONT END To proceed with building our interface, we need to create a Java container within which we will place the other required GUI components. In this step we’ll create a container using the JFrame component. We will place the container in a new package, which will appear within the Source Packages node. Create a JFrame container 1.In the Projects window, right-click the NumberAddition node and choose New > Other. 2.In the New File dialog box, choose the Swing GUI Forms category and the JFrame Form file type. Click Next. 3.Enter NumberAdditionUI as the class name. 4.Enter my.numberaddition as the package. 5.Click Finish. The IDE creates the NumberAdditionUI form and the NumberAdditionUI class within the NumberAddition application, and opens the NumberAdditionUI form in the GUI Builder. The my.NumberAddition package replaces the default package. ADDING COMPONENTS: MAKING THE FRONT END Next we will use the Palette to populate our application’s front end with a JPanel. Then we will add three JLabels, three JTextFields, and three JButtons. Once you are done dragging and positioning the aforementioned components, the JFrame should look something like the following screenshot. ADDING COMPONENTS: MAKING THE FRONT END If you do not see the Palette window in the upper right corner of the IDE, choose Window > Palette. 1.Start by selecting a Panel from the Swing Containers category on Palette and drop it onto the JFrame. 2.While the JPanel is highlighted, go to the Properties window and click the ellipsis (…​) button next to Border to choose a border style. 3.In the Border dialog, select TitledBorder from the list, and type in Number Addition in the Title field. Click OK to save the changes and exit the dialog. 4.You should now see an empty titled JFrame that says Number Addition like in the screenshot. Look at the screenshot and add three JLabels, three JTextFields and three JButtons as you see above. RENAMING THE COMPONENTS In this step we are going to rename the display text of the components that were just added to the JFrame. 1.Double-click jLabel1 and change the text property to First Number:. 2.Double-click jLabel2 and change the text to Second Number:. 3.Double-click jLabel3 and change the text to Result:. 4.If you want the labels right aligned, as the those in the image are, expand the width of the two shorter labels so that they are all the same width. Then open the Properties dialog for each one, and change the Horizontal Alignment property to RIGHT. 5.Delete the sample text from jTextField1. You can make the display text editable by right-clicking the text field and choosing Edit Text from the popup menu. You may have to resize the jTextField1 to its original size. Repeat this step for jTextField2 and jTextField3. 6.Rename the display text of jButton1 to Clear. (You can edit a button’s text by right- clicking the button and choosing Edit Text. Or you can click the button, pause, and then click again.) 7.Rename the display text of jButton2 to Add. 8.Rename the display text of jButton3 to Exit. YOUR FINISHED GUI SHOULD NOW LOOK LIKE THE FOLLOWING SCREENSHOT: EXERCISE 3: ADDING FUNCTIONALITY In this exercise we are going to give functionality to the Add, Clear, and Exit buttons. The jTextField1 and jTextField2 boxes will be used for user input and jTextField3 for program output - what we are creating is a very simple calculator. Let’s begin. MAKING THE EXIT BUTTON WORK In order to give function to the buttons, we have to assign an event handler to each to respond to events. In our case we want to know when the button is pressed, either by mouse click or via keyboard. So we will use ActionListener responding to ActionEvent. 1.Right click the Exit button. From the pop-up menu choose Events > Action > actionPerformed. Note that the menu contains many more events you can respond to! When you select the actionPerformed event, the IDE will automatically add an ActionListener to the Exit button and generate a handler method for handling the listener’s actionPerformed method. 2.The IDE will open up the Source Code window and scroll to where you implement the action you want the button to do when the button is pressed (either by mouse click or via keyboard). Your Source Code window should contain the following lines: private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { //TODO add your handling code here: } MAKING THE EXIT BUTTON WORK 1.We are now going to add code for what we want the Exit Button to do. Replace the TODO line with System.exit(0);. Your finished Exit button code should look like this: private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); } MAKING THE CLEAR BUTTON WORK 1.Click the Design tab at the top of your work area to go back to the Form Design. 2.Right click the Clear button (jButton1). From the pop-up menu select Events > Action > actionPerformed. 3.We are going to have the Clear button erase all text from the jTextFields. To do this, you will add some code like above. Your finished source code should look like this: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){ jTextField1.setText(""); jTextField2.setText(""); jTextField3.setText(""); } The above code changes the text in all three of our JTextFields to nothing, in essence it is overwriting the existing Text with a blank. MAKING THE ADD BUTTON WORK The Add button will perform three actions. 1.It is going to accept user input from jTextField1 and jTextField2 and convert the input from a type String to a float. 2.It will then perform addition of the two numbers. 3.And finally, it will convert the sum to a type String and place it in jTextField3. Lets get started! 4.Click the Design tab at the top of your work area to go back to the Form Design. 2.Right-click the Add button (jButton2). From the pop-up menu, select Events > Action > actionPerformed. 3.We are going to add some code to have our Add button work. The finished source code shall look like this: MAKING THE ADD BUTTON WORK 3.We are going to add some code to have our Add button work. The finished source code shall look like this: private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){ // First we define float variables. float num1, num2, result; // We have to parse the text to a type float. num1 = Float.parseFloat(jTextField1.getText()); num2 = Float.parseFloat(jTextField2.getText()); // Now we can perform the addition. result = num1+num2; // We will now pass the value of result to jTextField3. // At the same time, we are going to // change the value of result from a float to a string. jTextField3.setText(String.valueOf(result)); } Our program is now complete we can now build and run it to see it in EXERCISE 4: RUNNING THE PROGRAM To run the program in the IDE: Choose Run > Run Project (Number Addition) (alternatively, press F6). If you get a window informing you that Project NumberAddition does not have a main class set, then you should select my.NumberAddition.NumberAdditionUI as the main class in the same window and click the OK button. RECAP WHAT IS JAVA GUI? JAVA GUI GUI stands for Graphical User Interface, a term used not only in Java but in all programming languages that support the development of GUIs. A program's graphical user interface presents an easy-to-use visual display to the user. WHAT IS JAVA GUI USED FOR? It creates graphical units like buttons, labels, windows, etc. via which users can connect with an application. WHAT IS JAVA SWING? JAVA SWING Swing is a newer set of tools that builds on AWT. It’s part of the Java Foundation Classes (JFC) and provides a more powerful way to create GUIs. It is a more modern and flexible way to build graphical applications in Java compared to AWT. It allows developers to create richer and more interactive user interfaces with less effort. WHAT IS JPANEL AND JFRAME IN JAVA? JPANEL AND JFRAME IN JAVA Basically, a JFrame represents a framed window and a JPanel represents some area in which controls (e.g., buttons, checkboxes, and textfields) and visuals (e.g., figures, pictures, and even text) can appear. HOW TO FIT AN IMAGE WITHIN A JLABEL (SCAFFOLD 2) package loginimage; import java.awt.Image; import javax.swing.ImageIcon; public class NewJFrame extends javax.swing.JFrame { public void scaleimg(){ ImageIcon icon = new ImageIcon(“File location\\Filename.png or.jpg"); Image img = icon.getImage(); Image imgscl = img.getScaledInstance(jLabel1.getWidth(), jLabel1.getHeight(), Image.SCALE_SMOOTH); ImageIcon sclit = new ImageIcon(imgscl); jLabel1.setIcon(sclit); } public NewJFrame() { initComponents(); scaleimg(); } HOW TO OPEN NEW WINDOW ON BUTTON CLICK private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) { NewWindow pi = new NewWindow(); pi.setVisible(true); } LOGIN SYSTEM WITH FUNCTIONALITY (SCAFFOLD 3) package test; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; public class NewJFrame extends javax.swing.JFrame { public NewJFrame() { initComponents(); } @SuppressWarnings("unchecked") private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // Ensure addActionListener is called only once for (ActionListener al : jButton1.getActionListeners()) { jButton1.removeActionListener(al); } // Add action listener for login button jButton1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username = jTextField1.getText(); String password = new String(jPasswordField1.getPassword()); // Check credentials if (username.equals("user") && password.equals("pass")) { JOptionPane.showMessageDialog(null, "Login Successful!"); NewJFrame1 next = new NewJFrame1();//destination page next.setVisible(true); dispose(); // Close the current frame } else { JOptionPane.showMessageDialog(null, "Invalid Username or Password."); // Clear fields jTextField1.setText(""); jPasswordField1.setText(""); } } }); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPasswordField jPasswordField1; private javax.swing.JTextField jTextField1; // End of variables declaration }

Use Quizgecko on...
Browser
Browser