AJP_Swing_Introduction (1) (1) (1) (1).ppt
Document Details
Uploaded by TroubleFreeInspiration2837
Tags
Full Transcript
– Swing Introduction Java Swing is used to develop Graphical User Applications (GUI), desktop-based applications. Swing is built solely in Java and built on top of the AWT (abstract windowing toolkit). Swing has benefits over AWT, including that: Its components are lightwei...
– Swing Introduction Java Swing is used to develop Graphical User Applications (GUI), desktop-based applications. Swing is built solely in Java and built on top of the AWT (abstract windowing toolkit). Swing has benefits over AWT, including that: Its components are lightweight and more powerful (tables, lists, color choosers, etc.) Difference Between AWT and Swing AWT AWT stands for Abstract Window Toolkit. It is a platform-dependent API to develop GUI (Graphical User Interface) or window-based applications in Java. It is heavy-weight in use because it is generated by the system’s host operating system. It contains a large number of classes and methods, which are used for creating and managing GUI. Swing: Swing is a lightweight Java graphical user interface (GUI) that is used to create various applications. Swing has platform-independent components. It enables the user to create buttons and scroll bars. Swing includes packages for creating desktop applications in Java. Swing components are written in Java language. It is a part of Java Foundation Classes(JFC). Difference between AWT and Swing: S.NO AWT Swing Swing is a part of Java Java AWT is an API to develop Foundation Classes and is 1. GUI applications in Java used to create various applications. The components of Java AWT The components of Java 2. are heavy weighted. Swing are light weighted. Java AWT has comparatively Java Swing has more 3. less functionality as functionality as compared to compared to Swing. AWT. The execution time of AWT is The execution time of Swing 4. more than Swing. is less than AWT. The components of Java The components of Java AWT 5. Swing are platform are platform dependent. independent. Cont.. AWT Swing MVC pattern is not supported by MVC pattern is supported by 6. AWT. Swing. AWT provides comparatively less Swing provides more powerful 7. powerful components. components. AWT components require Swing components requires 8 java.awt package javax.swing package Swing is much larger swing also AWT is a thin layer of code on 9 has very much richer top of the operating system. functionality. Swing is also called as JFC(java AWT stands for Abstract windows 10 Foundation classes). It is part of toolkit. oracle’s JFC. Using AWT , you have to 11 implement a lot of things Swing has them built in. yourself. What is JFC The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications. Hierarchy of Java Swing classes Swing Components JApplet A Japplet is a Java program written to interact with and run inside of an HTML page. They are run within web browsers and are generally used to add functionality or graphics to a web page. Japplets have full access to a wide range of Java libraries, including AWT and Swing, so they can create sophisticated user interfaces, Cont.. Some of the common uses of Japplets include creating interactive 2D and 3D graphics, playing audio and video files, networking applications, and games. Japplets are also used to create web- based applications, such as online banking, e-commerce, and other web- based services. They can also be used to create web-based tools, such as search engines, web-based JApplet is a part of the Java Swing library. Package: javax.swing JApplet is a class in the Swing library that extends the Applet class and provides support for Swing-based user interface components. It allows applets to take advantage of the advanced features and modern look and feel of Swing components Cont.. JApplet is use to create applets with richer graphical user interfaces. Swing Design Principles GUI is built as containment hierarchy of widgets (i.e. the parent-child nesting relation between them) Event objects and event listeners – Event object: is created when event occurs (e.g. click), contains additional info (e.g. mouse coordinates) – Event listener: object implementing an interface with an event handler method that gets an event object as argument Separation of Model and View: – Model: the data that is presented by a 12 Swing Hello World(For import java.awt.*; Lab) import java.awt.event.*; import javax.swing.*; public class HelloWorld { public static void main(String[] args) { JFrame frame = new JFrame("Hello World!"); frame.setSize(220, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); contentPane.setLayout(null); JButton button = new JButton("Hello World!"); button.setLocation(30, 30); button.setSize(150, 100); contentPane.add(button); frame.setVisible(true); } } 13 Java Components JLabel | Java Swing JLabel is a class of java Swing. JLabel is used to display a short string or an image icon. JLabel can display text, image or both. JLabel is only a display of text or image and it cannot get focus. JLabel is inactive to input events such a mouse focus or keyboard focus. By default labels are vertically centered but the user can change the alignment Constructor are : 1.JLabel() : creates a blank label with no text or image in it. 2.JLabel(String s) : creates a new label with the string specified. 3.JLabel(Icon i) : creates a new label with a image on it. 4.JLabel(String s, Icon i, int align) : creates a new label with a string, an image and a specified horizontal alignment Methods are : 1.getIcon() : returns the image that the label displays 2.setIcon(Icon i) : sets the icon that the label will display to image i 3.getText() : returns the text that the label will display 4.setText(String s) : sets the text that the label will display to string s Program to create a blank label and add text // Java Program to create a to it. // blank label and add text to it. import java.awt.event.*; import java.awt.*; import javax.swing.*; class text extends JFrame { // frame static JFrame f; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args)Cont.. { // create a new frame to store text field and button f = new JFrame("label"); // create a label to display text l = new JLabel(); // add text to label l.setText("label text"); // create a panel JPanel p = new JPanel(); // add label to panel p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } } Java Swing | JTextField TextField is a part of javax.swing package. The class JTextField is a component that allows editing of a single line of text. JTextField inherits the JTextComponent class and uses the interface SwingConstants. The constructor of the class are : 1.JTextField() : constructor that creates a new TextField 2.JTextField(int columns) : constructor that creates a new empty TextField with specified number of columns. 3.JTextField(String text) : constructor that creates a new empty text field initialized with the given string. 4.JTextField(String text, int columns) : constructor that creates a new empty textField with the given string and a specified number of columns 5.JTextField(Document doc, String text, int columns) : constructor that creates a textfield that uses the given text storage model and the given number of columns. Methods of the JTextField are: 1.setColumns(int n) :set the number of columns of the text field. 2.setFont(Font f) : set the font of text displayed in text field. 3.addActionListener(ActionListene r l) : set an ActionListener to the text field. 4.int getColumns() :get the number of columns in the textfield. Java Swing | JComboBox JComboBox is a part of Java Swing package. JComboBox inherits JComponent class. JComboBox shows a popup menu that shows a list and the user can select a option from that specified list. JComboBox can be editable or read- only depending on the choice of the programmer. Constructor of the JComboBox: 1.JComboBox() : creates a new empty JComboBox. 2.JComboBox(ComboBoxModel M) : creates a new JComboBox with items from specified ComboBoxModel 3.JComboBox(E [ ] i) : creates a new JComboBox with items from specified array. 4.JComboBox(Vector items) : creates a new JComboBox with items from the specified vector (Vector items) (Vector is a class that implements the List interface. It is a dynamic array that can grow as needed to accommodate new elements. Commonly used Methods are : 1.addItem(Object item):Adds an item to combo box comboBox.addItem("Item 1"); 2.insertItemAt(Object item, int index): Inserts an item at a specific index in the combo box. comboBox.insertItemAt("Item 2", 1); 3. removeItem(Object item): Removes a specific item from the combo box. 4. removeItemAt(int index):Removes the item at the specified index. comboBox.removeItemAt(1); 5. removeAllItems(): Removes all items from the combo box. comboBox.removeAllItems(); 6.getItemAt(int index): Returns the item at the specified index. Object item = comboBox.getItemAt(0); 7. getSelectedItem(): Returns the currently selected item. Object selectedItem = comboBox.getSelectedItem(); 8. setSelectedItem(Object anObject): Sets the selected item. This can be used to programmatically select an item. comboBox.setSelectedItem("Item 2"); 9. getSelectedIndex(): Returns the index of the currently selected item. int selectedIndex = comboBox.getSelectedIndex(); 10. setEditable(boolean b): Sets whether the combo box is editable. If true, users can enter their own values. comboBox.setEditable(true); 11. isEditable(): Returns whether the combo box is editable. boolean isEditable = comboBox.isEditable(); 12. addActionListener(ActionListener l): Adds an ActionListener to handle action events (e.g., when an item is selected). comboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Selected item: " + comboBox.getSelectedItem()); } }); Java JButton The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. It inherits AbstractButton class. Class Declaration public class JButton extends AbstractButton implements Accessible Class Constructors JButton() Creates a button with no set text or icon. JButton(Action a) Creates a button where properties are taken from the Action supplied. JButton(Icon icon) Creates a button with an icon. JButton(String text) Creates a button with the text. JButton(String text, Icon icon) Creates a button with an initial text and an icon. Class Methods AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JButton. String getUIClassID() Returns a string that specifies the name of the L&F class which renders this component. boolean isDefaultButton() Gets the value of the defaultButton property, which if true means that this button is the current default button for its JRootPane. boolean isDefaultCapable() Gets the value of the defaultCapable property. protected String paramString() Returns a string representation of this JButton. void removeNotify() Overrides JComponent.removeNotify to check if this button is currently set as the default button on the RootPane. And if so, sets the RootPane's default button to null to ensure the RootPane doesn't hold onto an invalid button reference. void setDefaultCapable(boolean defaultCapable) Sets the defaultCapable property, which determines whether this button can be made the default button for its root pane. void updateUI() Resets the UI property to a value from the current Methods Inherited This class inherits methods from the following classes − javax.swing.AbstractButton javax.swing.JComponent java.awt.Container java.awt.Component java.lang.Object JComboBox Example import javax.swing.*; public class ComboBoxExample { private JFrame f; ComboBoxExample() { f = new JFrame("ComboBox Example"); String[] countries = {"India", "Australia", "U.S.A", "England", "New Zealand"}; JComboBox cb = new JComboBox(countries); OutPut cb.setBounds(50, 50, 150, 20); f.add(cb); f.setLayout(null); f.setSize(400, 300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(ComboBoxExample::new); } } JComboBox Example with ActionListener import javax.swing.*; import java.awt.event.*; public class ComboBoxExample { JFrame f; ComboBoxExample(){ f=new JFrame("ComboBox Example"); final JLabel label = new JLabel(); label.setHorizontalAlignment(JLabel.CENTER); label.setSize(400,100); JButton b=new JButton("Show"); b.setBounds(200,100,75,20); String languages[]={"C","C++","C#","Java","PHP"}; final JComboBox cb=new JComboBox(languages); cb.setBounds(50, 100,90,20); f.add(cb); f.add(label); f.add(b); f.setLayout(null); f.setSize(350,350); f.setVisible(true); b.addActionListener(new ActionListener() { Cont… public void actionPerformed(ActionEvent e) { String data = "Programming language Selected: " + cb.getItemAt(cb.getSelectedIndex()); outPut label.setText(data); } }); } public static void main(String[] args) { new ComboBoxExample(); } } Java Swing | JCheckBox JCheckBox is a part of Java Swing package. JCheckBox can be selected or deselected. It displays it state to the user. JCheckBox is an implementation to checkbox JCheckBox inherits JToggleButton class. Constructor of the class are : JCheckBox() : creates a new checkbox with no text or icon JCheckBox(Icon i) : creates a new checkbox with the icon specified JCheckBox(Icon icon, boolean s) : creates a new checkbox with the icon specified and the boolean value specifies whether it is selected or not. JCheckBox(String t) :creates a new checkbox with the string specified JCheckBox(String text, boolean selected) :creates a new checkbox with the string specified and the boolean value specifies whether it is selected or not. JCheckBox(String text, Icon icon) :creates a new checkbox with the string and the icon specified. JCheckBox(String text, Icon icon, boolean selected): creates a new checkbox with the string and the icon specified and the boolean value specifies Methods to add Item Listener to checkbox. addActionListener(ItemListener l): adds item listener to the component itemStateChanged(ItemEvent e) : abstract function invoked when the state of the item to which listener is applied changes getItem() : Returns the component-specific object associated with the item whose state changed getStateChange() : Returns the new state of the item. The ItemEvent class defines two states: SELECTED and DESELECTED. getSource() : Returns the component that fired the item event. Commonly used setIcon(Icon i) methods: : sets the icon of the checkbox to the given icon setText(String s) :sets the text of the checkbox to the given text setSelected(boolean b) : sets the checkbox to selected if boolean value passed is true or vice versa getIcon() : returns the image of the checkbox getText() : returns the text of the checkbox updateUI() : resets the UI property with a value from the current look and feel. getUI() : returns the look and feel object that renders this component. paramString() : returns a string representation of this JCheckBox. getAccessibleContext() : gets the AccessibleContext associated with this JCheckBox. isBorderPaintedFlat() : gets the value of the borderPaintedFlat property. setBorderPaintedFlat(boolean b) : sets the borderPaintedFlat property, // java Program to create a simple checkbox using JCheckBox import java.awt.event.*; import java.awt.*; import javax.swing.*; class solve extends JFrame { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // set layout of frame f.setLayout(new FlowLayout()); // create checkbox JCheckBox c1 = new JCheckBox("checkbox 1"); JCheckBox c2 = new JCheckBox("checkbox 2"); // create a new panel JPanel p = new JPanel(); // add checkbox to panel p.add(c1); p.add(c2); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); output: } } JRadioButton We use the JRadioButton class to create a radio button. Radio button is use to select one option from multiple options. It is used in filling forms, online objective papers and quiz. We add radio buttons in a ButtonGroup so that we can select only one radio button at a time. We use “ButtonGroup” class to create a Constructors for JRadioButton Default Constructor: JRadioButton radioButton = new JRadioButton(); Constructor with Text: JRadioButton radioButton = new JRadioButton(String text); Constructor with Text and Initial Selection State: JRadioButton radioButton = new JRadioButton(String text, boolean selected); Methods Used : JRadioButton() : Creates a unselected RadioButton with no text. Example: JRadioButton j1 = new JRadioButton() JButton(String s) : Creates a JButton with a specific text. Example:JButton b1 = new JButton("Button") JLabel(String s) : Creates a JLabel with a specific text. Example:JLabel L = new JLabel("Label 1") ButtonGroup() : Use to create a group, in which we can add JRadioButton. We can select only one JRadioButton in a ButtonGroup. Steps to Group the radio buttons together. Create a ButtonGroup instance by using “ButtonGroup()” Method. ButtonGroup G = new ButtonGroup() Now add buttons in a Group “G”, with the help of “add()” Method.Example: G.add(Button1); G.add(Button2); isSelected() : it will return a Boolean value true or false, if a JRadioButton is selected it Will return true otherwise false.Example: JRadioButton.isSelected() Set(…) and Get(…) Methods : i) Set and get are used to replace directly accessing member variables from external classes.ii) Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them. Program 1 : JRadioButton Without ActionListener import java.awt.*; import javax.swing.*; import java.awt.event.*; class Demo extends JFrame { // Declaration of object of JRadioButton class. JRadioButton jRadioButton1; // Declaration of object of JRadioButton class. JRadioButton jRadioButton2; // Declaration of object of JButton class. JButton jButton; // Declaration of object of ButtonGroup class. ButtonGroup G1; // Declaration of object of JLabel class. JLabel L1; // Constructor of Demo class. public Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of "JRadioButton" class. jRadioButton1 = new JRadioButton(); // Initialization of object of "JRadioButton" class. jRadioButton2 = new JRadioButton(); // Initialization of object of "JButton" class. jButton = new JButton("Click"); // Initialization of object of "ButtonGroup" class. G1 = new ButtonGroup(); // Initialization of object of " JLabel" class. L1 = new JLabel("Qualification"); / setText(...) function is used to set text of radio button. // Setting text of "jRadioButton2". jRadioButton1.setText("Under-Graduate"); // Setting text of "jRadioButton4". jRadioButton2.setText("Graduate"); // Setting Bounds of "jRadioButton2". jRadioButton1.setBounds(120, 30, 120, 50); // Setting Bounds of "jRadioButton4". jRadioButton2.setBounds(250, 30, 80, 50); // Setting Bounds of "jButton". jButton.setBounds(125, 90, 80, 30); // Setting Bounds of JLabel "L2". L1.setBounds(20, 30, 150, 50); // "this" keyword in java refers to current object. // Adding "jRadioButton2" on JFrame. this.add(jRadioButton1); // Adding "jRadioButton4" on JFrame. this.add(jRadioButton2); // Adding "jButton" on JFrame. this.add(jButton); // Adding JLabel "L2" on JFrame. this.add(L1); // Adding "jRadioButton1" and "jRadioButton3" in a Button Group "G2". G1.add(jRadioButton1); G1.add(jRadioButton2); } } class RadioButton { // Driver code. OutPut public static void main(String args[]) { // Creating object of demo class. Demo f = new Demo(); // Setting Bounds of JFrame. f.setBounds(100, 100, 400, 200); // Setting Title of frame. f.setTitle("RadioButtons"); // Setting Visible status of frame as true. f.setVisible(true); } } Key Differences Between Jbutton and JRadioButton Functionality: – JButton is used for generic actions like submitting forms or opening dialogs. – JRadioButton is used for making a selection from a group of options. Selection: – JButton does not maintain a selected state; it simply triggers an action when clicked. – JRadioButton maintains a selected state and, when grouped, ensures only one button in the group is selected at a time. Visual Representation: – JButton appears as a standard push button. – JRadioButton appears as a small circle that can be filled (selected) or empty (deselected). Grouping: – JButton instances can be used independently or in groups, but grouping does not affect their behavior. – JRadioButton instances are often used in groups (ButtonGroup), and grouping controls their selection behavior. Java JTabbedPane JTabbedPane is a GUI(Graphical User Interface) component in the Java Swing library that allows to create a tabbed pane interface. A tabbed pane is a container that can store and organize multiple components into distinct tabs. It contains a collection of tabs. When click on a tab, only data related to that tab will be displayed. JTabbedPane comes under the Java Swing package. Constructors used in JTabbedPane JTabbedPane(): This constructor initializes an empty tabbed pane with no tabs and no initial content when a JTabbedPane is created. JTabbedPane(int tabPlacement): The JTabbedPane(int tabPlacement) constructor allows to creation of a JTabbedPane with a defined initial location for the tabs. commonly used methods of the JTabbedPane addTab(String title, Component component): Creates a new tab with the given title and content. removeTabAt(int index): Removes the tab at the given index. getTabCount(): Returns the number of tabs present in the JTabbedPane. setSelectedIndex(int index): Sets the chosen tab to the index given. getSelectedIndex(): Returns the index of the currently selected tab. The classes from which JTabbedPane methods are inherited java.awt.Container javax.swing.JComponent javax.swing.JTabbedPane javax.swing.JContainer Programs to implement JTabbedPane // JTabbedPane with Labels import javax.swing.*; import java.awt.*; // Driver Class public class TabbedUIExample1 { // main function public static void main(String[] args) { // Run the Swing application on the Event Dispatch Thread (EDT) SwingUtilities.invokeLater(new Runnable() { public void run() { // Create a new JFrame (window) JFrame window = new JFrame("JTabbedPane Example"); // Close operation when the window is closed window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close operation when the window is closed // Set the initial size of the window window.setSize(400, 300); // Create a JTabbedPane, which will hold the tabs JTabbedPane tabPanel = new JTabbedPane(); // Create the first tab (page1) and add a JLabel to it JPanel page1 = new JPanel(); page1.add(new JLabel("This is Tab 1")); // Create the second tab (page2) and add a JLabel to it JPanel page2 = new JPanel(); page2.add(new JLabel("This is Tab 2")); // Create the third tab (page3) and add a JLabel to it JPanel page3 = new JPanel(); page3.add(new JLabel("This is Tab 3")); // Add the three tabs to the JTabbedPane OutPut: tabPanel.addTab("Tab 1", page1); tabPanel.addTab("Tab 2", page2); tabPanel.addTab("Tab 3", page3); // Add the JTabbedPane to the JFrame's content window.add(tabPanel); // Make the JFrame visible window.setVisible(true); } }); } } Java JScrollPane Java JScrollPane is a component in the Java Swing library that provides a scrollable view of another component, usually a JPanel or a JTextArea. It provides a scrolling functionality to the display for which the size changes dynamically. It is useful to display the content which exceeds the visible area of the window. Constructor of JScrollPane: JScrollPane():It is a default constructor that creates an empty JScrollPane. JScrollPane(Component comp):This constructor creates a JScrollPane with the specified view component as the scrollable content. JScrollPane(int vertical, int horizontal):This constructor creates an empty JScrollPane with the specified vertical and horizontal scrollbar. JScrollPane(LayoutManager layout):This constructor creates a JScrollPane with the specified layout manager. Methods of JScrollPane void setVerticalScrollBarPolicy(int vertical):Sets the vertical scrollbar policy void setHorizontalScrollBarPolicy(int horizontal):Sets the horizontal scrollbar policy void setColumnHeaderView(Compone nt comp):sets the column header for the JScrollPane setCorner(String key, Component corner):t is used to set a component to be displayed in one of the corners of the scroll pane Component getCorner(String key):It is used to retrieve the component that has been previously set in one of the corners of the scroll pane using the setCorner method void setViewportView(Component Program to demonstrate simple JscrollPane / Simple JscrollPane import javax.swing.*; import java.awt.*; // Driver Class public class SimpleJScrollPaneExample { // main function public static void main(String[] args) { JFrame frame = new JFrame("Simple JScrollPane Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); // Create a JPanel to hold a list of labels. JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // Add a large number of labels to the panel. for (int i = 1; i