1 / 29

Example of Inheritance and use of JTextArea

Example of Inheritance and use of JTextArea.

merle
Download Presentation

Example of Inheritance and use of JTextArea

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Example of Inheritance and use of JTextArea

  2. import java.io.*;import javax.swing.*;import java.awt.event.*;import java.awt.*;public class important{public static void main(String args[]){JTextArea outarea= new JTextArea(400,50);Human person = new Human();Student learner = new Student();person.setName(“Zeynep Altan");person.setAge(23);learner.setName(“Özlem Yıldız");String nn=learner.getName(); // in other words: inheritanceJOptionPane.showMessageDialog(null," "+nn);learner.setRank();String out="name " +person.getName()+“"+learner.getRank();outarea.setText(out);JOptionPane.showMessageDialog(null,outarea);System.exit(0);}}

  3. public class Human{private String name= new String();private int age;public Human(){name=" ";age=0;}public void setName(String st)//Sets the index name. Explicit setting of an index name is not required{name=st;}public void setAge(int ag){age=ag;}public String getName(){//Returns the index name. Explicit setting of an index name is not required. return(name);} } 

  4. import java.io.*;import javax.swing.*;import java.awt.event.*;import java.awt.*;public class Student extends Human{private int total_hours;private char rank;public Student(){total_hours=0;rank=' ';}public void setRank(){String rr=JOptionPane.showInputDialog("enter code 1 2 3 4 ");rank=rr.charAt(0) ;}public char getRank(){return (rank);}}

  5. Packages & Interfaces

  6. Packages are containers for classes that are used to keep the class name space divided • Packages are stored in a hierarchical manner and are explicitly imported into new class definition. • A package allows us to create a class named List, which we can store it in our own package without concern that it will conflict with some other named List stored anywhere

  7. Access Protection Classes and packages are both means of encapsulating and containing the name space and scope of variables and methods. • Packages act as containers for classes and other subordinate packages • Classes act as containers for data and code. • The class is Java’s smallest unit of abstraction. Because of interaction between classes and packages, Java addresses four categories of visibility for class members

  8. Access rights for the different elements class\ have accesstoprivate default protectedpublic elementselementselementselements (no modifier) own class (Base)yesyesyesyes subclass – same package(SubA)noyes yesyes class – same package (AnotherA)noyesyesyes subclass - another package (SubB)nonoyes/no *yes class – another package (AnotherB)no no no yes *Class SubBhas access only to the inherited from Baseprotected elements, i.e. its ownelements, but the protected data of other Base instances is not accessible fromSubB.

  9. packagepackageA; public class Base { public String publicStr = "publicString"; protected String protectedStr = "protectedString"; String defaultStr = "defaultString"; privateString privateStr = "privateString"; public void print() { System.out.println("packageA.Base has access to"); System.out.println(" " + publicStr); System.out.println(" " + protectedStr); System.out.println(" " + defaultStr); System.out.println(" " + privateStr); Base b = new Base(); // other Base instance System.out.println(" b." + b.publicStr); System.out.println(" b." + b.protectedStr); System.out.println(" b." + b.defaultStr); System.out.println(" b." + b.privateStr); } }

  10. packagepackageA; public classSubA extendsBase { public void print() { System.out.println("packageA.SubA has access to"); System.out.println(" " + publicStr + " (inherited from Base)"); System.out.println(" " + protectedStr + " (inherited from Base)"); System.out.println(" " + defaultStr + " (inherited from Base)"); // not accessible - private elements are even not inherited // System.out.println(privateStr); Base b = newBase(); // other Base instanceSystem.out.println(" b." + b.publicStr); System.out.println(" b." + b.protectedStr); System.out.println(" b." + b.defaultStr); // not accessible System.out.println(b.privateStr); } }

  11. packagepackageA; public class AnotherA { public void print() { System.out.println(packageA.AnotherA has access to"); Base b =newBase(); System.out.println(" b." + b.publicStr); System.out.println(" b." + b.protectedStr); System.out.println(" b." + b.defaultStr); // not accessible System.out.println(b.privateStr); } }

  12. packagepackageB; importpackageA.Base; public classSubBextendsBase { public void print(){ System.out.println("packageB.SubB has access to"); System.out.println(" " + publicStr + " (inherited from Base)"); // protectedStr is inherited element -> accessible System.out.println(" " + protectedStr + " (inherited from Base)"); // not accessible System.out.println(defaultStr); // not accessible System.out.println(privateStr); Base b = newBase();//other Base instanceSystem.out.println(" b." + b.publicStr); // protected element, which belongs to other object -> not accessible // System.out.println(b.protectedStr); // not accessible System.out.println(b.defaultStr); // not accessibleSystem.out.println(b.privateStr); } }

  13. packagepackageB; importpackageA.Base; public class AnotherB { public void print() { System.out.println("packageB.AnotherB has access to"); Base b = newBase(); System.out.println(" b." + b.publicStr); // not accessibleSystem.out.println(b.protectedStr); // not accessibleSystem.out.println(b.defaultStr); // not accessibleSystem.out.println(b.privateStr); } }

  14. importpackageA.*; importpackageB.*; // testing class public class TestProtection { public static void main(String[] args) { // all classes are public, so class TestProtection // has access to all of them newBase().print(); newSubA().print(); newAnotherA().print(); newSubB().print(); newAnotherB().print(); }}

  15. Summary • private is the most restrictive access level • a private member is accessible only in the class in which it is defined • private members are not inherited by the subclasses

  16. Interfaces • The use of the interface keyword allows us to fully abstract the interface from its implementation • Using interface we can specify a set of methods which can be implemented by one or more classes. • The interface, itself does not define any implementation • Although interfaces are similar to abstract classes, they have an additional capability • A class can implement more than one interface. • Bu constract, a class can only inherit a single superclass (abstract or otherwise)

  17. Creating an Interface modifier interface InterfaceName { constants declarations; methods signatures; } Example of Creating an Interface //This interface is defined in java.lang //package public interface Comparable { public int compareTo(Object o); }

  18. Generic max Method public class Max { // Return the maximum between two objects public static Comparable max (Comparable o1, Comparable o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } }

  19. The abstract Class • The abstract class • Cannot be instantiated • Should be extended and implemented in subclasses • The abstract method • Method signature withoutimplementation

  20. Comparator Interface • Is it possible to iterate over a set of Person objects in ageorder? • Is it possible to construct a TreeSet of objects that do notimplement Comparable? Answer: Yes, we can use an object that implements Comparator The Comparator interface has a single method, similar toComparable: int compare(Object a, Object b) Like Comparable.compareTo() it returns an integer, whose signencodes the comparison

  21. JPanel Basics • In the simplest case, we use a JPanel exactly the same way as a Panel. • JPanel also acts as a replacement for Canvas (there is no JCanvas). • When using JPanel we should firstly set the preferred size via setPreferredSize (recall that a Canvas' preferred size is just its current size, while a Panel and JPanel determine their preferred size from the components they contain). • Secondly, we should use paintComponent for drawing, not paint. • Since double-buffering is turned on by default, the first thing we normally do in paintComponent is clear the off-screen bitmap via super.paintComponent. public void paintComponent(Graphics g) { super.paintComponent(g); ... } existing Border objects whenever possible.

  22. Beside from double buffering, the most obvious new feature is the ability to assign borders to JPanels. • Swing gives us seven basic border types:titled, etched, beveled (regular plus a "softer" version), line, matte, compound, and empty. we can also create our own. • We can assign a Border via the setBorder method, and create the Border either by calling the constructors directly, or more often by using one of the following convenience methods in BorderFactory: createTitledBorder, createEtchedBorder,createBevelBorder,createRaisedBevelBorder, createLoweredBevelBorder,createLineBorder, createMatteBorder,createCompoundBorder, createEmptyBorder. • These factory methods reuseexisting Border objects whenever possible.

  23. import java.awt.*; import javax.swing.*; // This example illustrates the use of JPanels, the ability to add Borders public class JPanels extends JFrame { public static void main(String[] args) { new JPanels(); } public JPanels() { super("Using JPanels with Borders"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); content.setBackground(Color.lightGray); JPanel controlArea = new JPanel(new GridLayout(3, 1)); String[] colors = { "Red", "Green", "Blue", "Black", "White", "Gray" }; controlArea.add(new SixChoicePanel("Color", colors)); String[] thicknesses = { "1", "2", "3", "4", "5", "6" };

  24. controlArea.add(new SixChoicePanel("Line Thickness",thicknesses)); String[] fontSizes = { "10", "12", "14", "18", "24", "36" }; controlArea.add(new SixChoicePanel("Font Size", fontSizes)); content.add(controlArea, BorderLayout.EAST);); } } JPanel drawingArea = new JPanel(); // Preferred height is irrelevant, since using WEST region drawingArea.setPreferredSize(new Dimension(400, 0)); drawingArea.setBorder(BorderFactory.createLineBorder (Color.blue, 2)); drawingArea.setBackground(Color.white); content.add(drawingArea, BorderLayout.WEST); pack(); setVisible(true); }

  25. import java.awt.*; import javax.swing.*; public class SixChoicePanel extends JPanel { public SixChoicePanel(String title, String[] buttonLabels) { super(new GridLayout(3, 2)); setBackground(Color.lightGray); setBorder(BorderFactory.createTitledBorder(title)); ButtonGroup group = new ButtonGroup(); JRadioButton option; int halfLength = buttonLabels.length/2;// Assumes even length for(int i=0; i<halfLength; i++) { option = new JRadioButton(buttonLabels[i]); group.add(option); add(option); option = new JRadioButton(buttonLabels[i+halfLength]); group.add(option); add(option); } }

  26. WindowsUtilities.java import javax.swing.*; import java.awt.*; public class WindowUtilities { public static void setNativeLookAndFeel() { try { UIManager.setLookAndFeel(UIManager.getSystemLook AndFeelClassName()); } catch(Exception e) { System.out.println("Error setting native LAF: " + e); } }

  27. public static void setJavaLookAndFeel() { try { UIManager.setLookAndFeel (UIManager.getCrossPlatformLookAndFeelClassName()); } catch(Exception e) { System.out.println("Error setting Java LAF: " + e); } } public static void setMotifLookAndFeel() { try { UIManager.setLookAndFeel ("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); } catch(Exception e) { System.out.println("Error setting Motif LAF: " + e); } }

  28. public static JFrame openInJFrame(Container content, int width, int height, String title, Color bgColor) { JFrame frame = new JFrame(title); frame.setBackground(bgColor); content.setBackground(bgColor); frame.setSize(width, height); frame.setContentPane(content); frame.addWindowListener(new ExitListener()); frame.setVisible(true); return(frame); } //Uses Color.white as the background color. public static JFrame openInJFrame(Container content int width,int height, String title) { return(openInJFrame(content, width, height, title, Color.white)); } //Uses Color.white as the background color, and thename of the Container's // classasthe JFrame title. public static JFrame openInJFrame(Container content,int width,int height) { return(openInJFrame(content, width, height,content.getClass().getName(), Color.white)); }}

More Related