This document discusses adding text areas to a frame using both the AWT TextArea and Java Swing JTextArea. It provides code templates for creating each type of text area, including setting their size, location, and adding them to the frame. For JTextArea, it notes that a JScrollPane must be used to provide scrolling functionality when the text exceeds the component size. The document also lists three ways text could be provided to the text areas: an array of strings, a single string with carriage returns, or the path of a file containing the text.
The document discusses different types of loops in C#, including for, while, and do-while loops. It provides examples and explanations of how each loop works. The key types of loops are:
- For loops, which allow initialization of a counter variable, a condition to test each iteration, and an increment/decrement portion.
- While loops, which test a condition and run the code block if true, then re-test the condition.
- Do-while loops, which run the code block first before checking the condition, so the code runs at least once.
Break and continue statements can alter normal loop flow by breaking out of the entire loop or skipping to the next iteration. Lo
This document discusses different types of flow control in Python programs. It explains that a program's control flow defines the order of execution and can be altered using control flow statements. There are three main types of control flow: sequential, conditional/selection, and iterative/looping.
Sequential flow executes code lines in order. Conditional/selection statements like if/else allow decisions based on conditions. Iterative/looping statements like for and while loops repeat code for a set number of iterations or as long as a condition is true. Specific conditional statements, loops, and examples are described in more detail.
The document discusses various Python flow control statements including if/else, for loops, while loops, break and continue. It provides examples of using if/else statements for decision making and checking conditions. It also demonstrates how to use for and while loops for iteration, including using the range function. It explains how break and continue can be used to terminate or skip iterations. Finally, it briefly mentions pass, for, while loops with else blocks, and nested loops.
The document discusses different types of loops in Java including while, do-while, and for loops. It explains the syntax and flow of each loop type and provides examples of how and when to use each loop. The document also covers break and continue statements that can be used inside loops to control flow, as well as increment and decrement operators.
The document discusses different types of conditional and control statements in Python including if, if-else, elif, nested if-else, while, for loops, and else with loops.
It provides the syntax and examples of each statement type. The if statement and if-else statement are used for simple decision making. The elif statement allows for chained conditional execution with more than two possibilities. Nested if-else allows if/elif/else statements within other conditionals. While and for loops are used to repeatedly execute blocks of code, with while looping until a condition is false and for looping over sequences. The else statement with loops executes code when the loop condition is false.
The document discusses the flow of control in programs and control statements. There are two major categories of control statements: loops and decisions. Loops cause a section of code to repeat, while decisions cause jumps in the program flow depending on calculations or conditions. Common loop statements are for, while, and do-while loops. Common decision statements include if-else and switch statements. Nested statements and loops can also be used to further control program flow.
The document discusses different types of decision making and looping statements in C programming. It describes simple if, if-else, nested if-else, and else-if ladder statements for decision making. It also covers while, do-while, and for loops for iterative execution. Examples are provided for each statement type to illustrate their syntax and usage.
The document discusses different types of loops in C#, including for, while, and do-while loops. It provides examples and explanations of how each loop works. The key types of loops are:
- For loops, which allow initialization of a counter variable, a condition to test each iteration, and an increment/decrement portion.
- While loops, which test a condition and run the code block if true, then re-test the condition.
- Do-while loops, which run the code block first before checking the condition, so the code runs at least once.
Break and continue statements can alter normal loop flow by breaking out of the entire loop or skipping to the next iteration. Lo
This document discusses different types of flow control in Python programs. It explains that a program's control flow defines the order of execution and can be altered using control flow statements. There are three main types of control flow: sequential, conditional/selection, and iterative/looping.
Sequential flow executes code lines in order. Conditional/selection statements like if/else allow decisions based on conditions. Iterative/looping statements like for and while loops repeat code for a set number of iterations or as long as a condition is true. Specific conditional statements, loops, and examples are described in more detail.
The document discusses various Python flow control statements including if/else, for loops, while loops, break and continue. It provides examples of using if/else statements for decision making and checking conditions. It also demonstrates how to use for and while loops for iteration, including using the range function. It explains how break and continue can be used to terminate or skip iterations. Finally, it briefly mentions pass, for, while loops with else blocks, and nested loops.
The document discusses different types of loops in Java including while, do-while, and for loops. It explains the syntax and flow of each loop type and provides examples of how and when to use each loop. The document also covers break and continue statements that can be used inside loops to control flow, as well as increment and decrement operators.
The document discusses different types of conditional and control statements in Python including if, if-else, elif, nested if-else, while, for loops, and else with loops.
It provides the syntax and examples of each statement type. The if statement and if-else statement are used for simple decision making. The elif statement allows for chained conditional execution with more than two possibilities. Nested if-else allows if/elif/else statements within other conditionals. While and for loops are used to repeatedly execute blocks of code, with while looping until a condition is false and for looping over sequences. The else statement with loops executes code when the loop condition is false.
The document discusses the flow of control in programs and control statements. There are two major categories of control statements: loops and decisions. Loops cause a section of code to repeat, while decisions cause jumps in the program flow depending on calculations or conditions. Common loop statements are for, while, and do-while loops. Common decision statements include if-else and switch statements. Nested statements and loops can also be used to further control program flow.
The document discusses different types of decision making and looping statements in C programming. It describes simple if, if-else, nested if-else, and else-if ladder statements for decision making. It also covers while, do-while, and for loops for iterative execution. Examples are provided for each statement type to illustrate their syntax and usage.
How to start functional programming (in Scala): Day1Taisuke Oe
Functional programming involves composing computations like functions in a modular way. Scala supports both functional and object-oriented paradigms. Functions in Scala can be composed through methods like andThen and compose. Higher order functions allow functions to take other functions as arguments or return values. Pure functions always return the same output for the same inputs and avoid side effects. The Monoid typeclass abstracts the concepts of combining elements of a type and providing a default value, allowing new folding behaviors to be defined for types through implicit values. This allows behaviors to be extended to existing types without modifying them.
Types of Statements in Python Programming LanguageExplore Skilled
The slide describes the types of flow control statements in Python including conditional statement , loop statement , control statement such as break and continue .
The document discusses various control structures in C++ like conditional statements (if-else, switch), loops (while, for, do-while), and jump statements (break, continue, goto). It provides examples to explain if-else, switch, while, for, do-while loops. Nested loops and break/continue statements are also covered. The last section briefly explains unconditional jump with goto statement.
This document provides instructions on installing Python 3 on Ubuntu and Windows operating systems. It discusses installing Python 3.8 on Ubuntu using the apt install command and verifying the installation with the python --version command. It also outlines downloading the Python installer, running the executable, adding Python to environment variables, and verifying the installation on Windows. The document further explains installing iPython using pip and provides examples of using boolean values, conditionals, loops, functions, and strings in Python programs.
Looping Statements and Control Statements in PythonPriyankaC44
This document discusses looping statements and control statements in Python. It explains while loops, for loops, and the use of break, continue, else and pass statements. Some key points:
- While loops repeatedly execute statements as long as a condition is true. For loops iterate over a sequence.
- Break and continue statements can alter loop flow - break exits the entire loop, continue skips to the next iteration.
- The else block in loops runs when the condition becomes false (while) or the sequence is complete (for).
- Pass is a null operation used when syntax requires a statement but no operation is needed.
Several examples of loops and control statements are provided to demonstrate their usage.
In this PPT you will learn how to use looping in python.
For more presentation in any subject please contact us on
raginijain0208@gmail.com.
You get a new presentation every Sunday at 10 AM.
Learn more about Python by clicking on given below link
Python Introduction- https://www.slideshare.net/RaginiJain21/final-presentation-on-python
Basic concept of Python -https://www.slideshare.net/RaginiJain21/python-second-ppt
Python Datatypes - https://www.slideshare.net/RaginiJain21/data-types-in-python-248466302
Python Library & Module - https://www.slideshare.net/RaginiJain21/python-libraries-and-modules
Basic Python Programs- https://www.slideshare.net/RaginiJain21/basic-python-programs
Python Media Libarary - https://www.slideshare.net/RaginiJain21/python-media-library
The document discusses the different types of loops in C language: while loop, do-while loop, and for loop. It provides the syntax and an example of each loop. The while loop checks the condition first and repeats the block of code as long as the condition is true. The do-while loop ensures the block of code executes at least once before checking the condition. The for loop allows initialization of a counter, specifies a condition to test, and how to change the counter between iterations of the loop.
The document discusses stacks and their implementation. It introduces stacks and their common operations like push and pop. It describes using stacks to solve problems like reversing a list, calculating in Reverse Polish Notation, and bracket matching by keeping track of opening brackets on a stack. Sample code is provided to implement a stack class with methods like push, pop and top to manipulate items on the stack.
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopPriyom Majumder
This file is based on the loops that could be used in C Programming. These are explained with some examples and sample programmings and screen shots.
NOTE: The software used in this programming is Notepad++ and the programs are compiled and run through gcc compiler using command prompt.
This chapter discusses different types of repetition statements in Java including while, do-while, for, and nested loops. It covers implementing repetition using these statements, choosing the appropriate one for a given task, and avoiding common pitfalls like off-by-one errors and infinite loops. Examples are provided to demonstrate generating tables with nested for loops and formatting output using the Formatter class.
The document discusses stacks and their implementation and applications. It defines a stack as a linear data structure for temporary storage where elements can only be inserted or deleted from one end, called the top. Stacks follow the LIFO (last in, first out) principle. Stacks have two main operations - push, which inserts an element, and pop, which removes the top element. Stacks can be implemented using arrays or linked lists. Common applications of stacks include reversing strings, checking matching parentheses, and converting infix, postfix, and prefix expressions.
The control statements enable us to specify the order in which the various instructions in a program are to be executed by the computer. They determine the flow of control in a program.
There are 4 types of control statements in C. They are:
a) Sequence control statements
b) Decision control statements or conditional statement
c) Case-control statements
d) Repetition or loop control statements
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
For loops allow code to be repeatedly executed until a condition is met. They include initialization, condition, and update statements. While and do-while loops also repeatedly execute code until a condition is met, but check the condition at the start or end of each iteration respectively. Loops are useful for tasks like adding numbers in a range or populating data structures to avoid repetitive code.
This document outlines an algorithm for calculating the average of a class by using counter-controlled repetition. It describes using a while loop to iterate 10 times, prompting the user for a grade on each iteration, adding the grade to a running total, and incrementing the counter. After the loop, it calculates the average by dividing the total sum of grades by 10. Pseudocode and Visual Basic code are provided as examples to demonstrate this counter-controlled repetition algorithm for calculating a class average.
Data Structure- Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations −
PUSH, POP, PEEP
The document provides an overview of core Java concepts including Abstract Windowing Toolkit (AWT), event handling, Swing, layout managers, and applets. It discusses AWT components like containers, windows, panels and frames. It also covers creating frames, setting buttons, and different approaches to event handling like within a class, with an outer class, or anonymously. The document reviews Swing components and hierarchies. It includes examples of creating Swing frames and using buttons, radio buttons, and displaying images on buttons.
1) Arrays allow storing multiple values of the same type under one variable name using subscripts. One-dimensional arrays store elements in a single list, while multi-dimensional arrays can store elements in multiple lists.
2) Control statements like if/else, switch, while, do-while, for, break, continue and return allow altering the flow of execution in a program.
3) Classes are blueprints that define the structure and behavior of objects. Classes contain variables and methods, and objects are instances of classes that store their own set of variable values.
How to start functional programming (in Scala): Day1Taisuke Oe
Functional programming involves composing computations like functions in a modular way. Scala supports both functional and object-oriented paradigms. Functions in Scala can be composed through methods like andThen and compose. Higher order functions allow functions to take other functions as arguments or return values. Pure functions always return the same output for the same inputs and avoid side effects. The Monoid typeclass abstracts the concepts of combining elements of a type and providing a default value, allowing new folding behaviors to be defined for types through implicit values. This allows behaviors to be extended to existing types without modifying them.
Types of Statements in Python Programming LanguageExplore Skilled
The slide describes the types of flow control statements in Python including conditional statement , loop statement , control statement such as break and continue .
The document discusses various control structures in C++ like conditional statements (if-else, switch), loops (while, for, do-while), and jump statements (break, continue, goto). It provides examples to explain if-else, switch, while, for, do-while loops. Nested loops and break/continue statements are also covered. The last section briefly explains unconditional jump with goto statement.
This document provides instructions on installing Python 3 on Ubuntu and Windows operating systems. It discusses installing Python 3.8 on Ubuntu using the apt install command and verifying the installation with the python --version command. It also outlines downloading the Python installer, running the executable, adding Python to environment variables, and verifying the installation on Windows. The document further explains installing iPython using pip and provides examples of using boolean values, conditionals, loops, functions, and strings in Python programs.
Looping Statements and Control Statements in PythonPriyankaC44
This document discusses looping statements and control statements in Python. It explains while loops, for loops, and the use of break, continue, else and pass statements. Some key points:
- While loops repeatedly execute statements as long as a condition is true. For loops iterate over a sequence.
- Break and continue statements can alter loop flow - break exits the entire loop, continue skips to the next iteration.
- The else block in loops runs when the condition becomes false (while) or the sequence is complete (for).
- Pass is a null operation used when syntax requires a statement but no operation is needed.
Several examples of loops and control statements are provided to demonstrate their usage.
In this PPT you will learn how to use looping in python.
For more presentation in any subject please contact us on
raginijain0208@gmail.com.
You get a new presentation every Sunday at 10 AM.
Learn more about Python by clicking on given below link
Python Introduction- https://www.slideshare.net/RaginiJain21/final-presentation-on-python
Basic concept of Python -https://www.slideshare.net/RaginiJain21/python-second-ppt
Python Datatypes - https://www.slideshare.net/RaginiJain21/data-types-in-python-248466302
Python Library & Module - https://www.slideshare.net/RaginiJain21/python-libraries-and-modules
Basic Python Programs- https://www.slideshare.net/RaginiJain21/basic-python-programs
Python Media Libarary - https://www.slideshare.net/RaginiJain21/python-media-library
The document discusses the different types of loops in C language: while loop, do-while loop, and for loop. It provides the syntax and an example of each loop. The while loop checks the condition first and repeats the block of code as long as the condition is true. The do-while loop ensures the block of code executes at least once before checking the condition. The for loop allows initialization of a counter, specifies a condition to test, and how to change the counter between iterations of the loop.
The document discusses stacks and their implementation. It introduces stacks and their common operations like push and pop. It describes using stacks to solve problems like reversing a list, calculating in Reverse Polish Notation, and bracket matching by keeping track of opening brackets on a stack. Sample code is provided to implement a stack class with methods like push, pop and top to manipulate items on the stack.
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopPriyom Majumder
This file is based on the loops that could be used in C Programming. These are explained with some examples and sample programmings and screen shots.
NOTE: The software used in this programming is Notepad++ and the programs are compiled and run through gcc compiler using command prompt.
This chapter discusses different types of repetition statements in Java including while, do-while, for, and nested loops. It covers implementing repetition using these statements, choosing the appropriate one for a given task, and avoiding common pitfalls like off-by-one errors and infinite loops. Examples are provided to demonstrate generating tables with nested for loops and formatting output using the Formatter class.
The document discusses stacks and their implementation and applications. It defines a stack as a linear data structure for temporary storage where elements can only be inserted or deleted from one end, called the top. Stacks follow the LIFO (last in, first out) principle. Stacks have two main operations - push, which inserts an element, and pop, which removes the top element. Stacks can be implemented using arrays or linked lists. Common applications of stacks include reversing strings, checking matching parentheses, and converting infix, postfix, and prefix expressions.
The control statements enable us to specify the order in which the various instructions in a program are to be executed by the computer. They determine the flow of control in a program.
There are 4 types of control statements in C. They are:
a) Sequence control statements
b) Decision control statements or conditional statement
c) Case-control statements
d) Repetition or loop control statements
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
For loops allow code to be repeatedly executed until a condition is met. They include initialization, condition, and update statements. While and do-while loops also repeatedly execute code until a condition is met, but check the condition at the start or end of each iteration respectively. Loops are useful for tasks like adding numbers in a range or populating data structures to avoid repetitive code.
This document outlines an algorithm for calculating the average of a class by using counter-controlled repetition. It describes using a while loop to iterate 10 times, prompting the user for a grade on each iteration, adding the grade to a running total, and incrementing the counter. After the loop, it calculates the average by dividing the total sum of grades by 10. Pseudocode and Visual Basic code are provided as examples to demonstrate this counter-controlled repetition algorithm for calculating a class average.
Data Structure- Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations −
PUSH, POP, PEEP
The document provides an overview of core Java concepts including Abstract Windowing Toolkit (AWT), event handling, Swing, layout managers, and applets. It discusses AWT components like containers, windows, panels and frames. It also covers creating frames, setting buttons, and different approaches to event handling like within a class, with an outer class, or anonymously. The document reviews Swing components and hierarchies. It includes examples of creating Swing frames and using buttons, radio buttons, and displaying images on buttons.
1) Arrays allow storing multiple values of the same type under one variable name using subscripts. One-dimensional arrays store elements in a single list, while multi-dimensional arrays can store elements in multiple lists.
2) Control statements like if/else, switch, while, do-while, for, break, continue and return allow altering the flow of execution in a program.
3) Classes are blueprints that define the structure and behavior of objects. Classes contain variables and methods, and objects are instances of classes that store their own set of variable values.
Java Swing is a GUI toolkit that is used to create window-based applications. It is built on top of AWT and provides more powerful and lightweight components like tables, lists, scroll panes etc. Swing components are platform-independent and follow the MVC architecture. Common Swing components include JButton, JTextField, JTextArea and common layouts include FlowLayout, BorderLayout, GridLayout etc. Menus in Swing can support keyboard navigation using mnemonics and shortcuts using accelerators.
The document discusses Java AWT and Swing GUI programming. It provides details on commonly used AWT and Swing components like Frame, Button, Label, Textfield. It explains the hierarchy and differences between AWT and Swing. Examples are provided to demonstrate creating a simple GUI using various components like Buttons, Labels and adding them to a Frame. The document also covers other Swing components like Checkboxes, Scrollpanes and containers like Frame, Dialog, Panel.
The document discusses Swing components in Java, including how to create windows, add components to windows, handle events, and work with text components. Key topics covered include the component hierarchy for common Swing widgets like JFrame, JLabel, JButton, and JTextField. It also discusses how to register listeners, manipulate document content, and build a basic browser component.
This document discusses using variables and constants in Java, including:
- Declaring and initializing different variable types like int, float, and String
- Assigning values to variables and constants
- Using methods like getText() and setText() to work with text fields and text areas
- Adding buttons and adding listeners to buttons to detect click events
- Getting the system date using the Calendar class
The document describes an implementation of the Observer pattern using four Java classes - Data, TextFrame, BarGraph, and MouseAdapter.
Data is the model that holds the bar graph data and notifies observers of changes. TextFrame and BarGraph are observer views that update when the model changes. TextFrame displays the data values and BarGraph displays the bar graph. MouseAdapter handles mouse clicks on the bar graph to allow modifying the data.
When the user enters a new value in TextFrame, it updates Data. Data then notifies BarGraph and TextFrame of the change. When the user clicks a bar in BarGraph, MouseAdapter modifies the data in Data. Data again notifies the observers of the change
The document provides an introduction and overview of Swing components in Java. It discusses key Swing classes like JApplet, JLabel, JTextField, JButton, JCheckBox, JRadioButton, JComboBox, and JTabbedPane. It explains their functionality, important methods, and gives examples of how to use each component in an applet. The document also compares Swing to the older AWT toolkit and outlines the MVC architecture used in Swing.
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfmohammedfootwear
PLEASE HELP ME !!
IT IS Due Tonight ;(!
i have to submit it before 12 palzz help me :\"\"(
How can I make the add button and remove button initialize button work?
For the buttons should add and remove to the JTextArea and JList.
when you write you use the JTextField to add or remove what you write in the JTextArea and
JList.
For the initialize, the button should initialize the text once.
Ihave three class.
this what I code so far:
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.Image;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFileChooser;
import java.awt.Insets;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Handler;
import java.awt.event.ActionEvent;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Component;
import javax.swing.ButtonGroup;
import javax.swing.DropMode;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.TitledBorder;
import javax.swing.UIManager;
import java.awt.FlowLayout;
public class Schedule extends JFrame implements ListSelectionListener, ActionListener {
private ScheduleTextArea STArea;
private ScheduleButton SButton;
private JRadioButtonMenuItem BRed;
private JRadioButtonMenuItem BBlue;
private JRadioButtonMenuItem BGreen;
private JRadioButtonMenuItem BYellow;
private JPanel cntrolPanel;
public static void main(String[] args){
Schedule S= new Schedule();
S.setVisible(true);
}
public Schedule() {
setTitle(\"Student schedule\");
setSize(800,700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(0, 1, 0, 0));
createMenuBar();
cntrolPanel= new JPanel();
cntrolPanel.setBorder(new MatteBorder(3, 3, 3, 3, (Color) Color.GRAY));
getContentPane().add(cntrolPanel);
cntrolPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
STArea = new ScheduleTextArea();
STArea.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(128, 128, 128)));
cntrolPanel.add(STArea);
SButton = new ScheduleButton(null);
SButton.setBorder(new MatteBorder(1, 1, 1, 1, (Color) Color.GRAY));
cntrolPanel.add(SButton);
}
private void createMenuBar() {
BHandler handler = new BHandler();
JMenuBar menuBar= new JMenuBar();
setJ.
Part 1 Project Setup, Building the ViewUIIn the video belo.pdfamazing2001
Part 1: Project Setup, Building the View/UI
In the video below, some initial steps are given to setup the GUI for the project as well as the
main entry point for the application.
Part 2: The IDialLock Interface
Note: All classes and interfaces you develop in Part 2 of the assignment should be placed in the
"model" package.
Develop an interface for a three-digit dial combination lock. The interface should be named
IDialLock and should export the following abstract methods:
void reset() - resets the lock dial back to 0.
void left(int t) - turns the lock left by the specified number of ticks t.
void right(int t) - turns the lock right by the specified number of ticks t.
int currentTick() - returns the tick number the dial is pointing to between 0..maxTicks.
boolean pull() - attempts to pull open the lock; the method returns true if successful false in all
other cases.
The lock opens if one performs the following sequence of turns:
right(..) to the first secret digit,
then left(..) to the second secret digit,
then right(..) to the third secret digit.
The image below is a rough illustration of the sort of dial lock you'll be building:
2.1: A "Helper Class" Representing Dial Turns
Before you implement the interface above, add the following helper class to the model package:
This class represents a single turn of the dial. It encapsulates the direction the dial was turned
(either left or right) along with the digit that the dial stopped on after the turn was completed.
2.2: Developing a "Tracking" Implementation of the IDialLock Interface
Now create another class (in the model package) called: TrLockImpl. This particular
implementation will 'track' the history of turns each time the left(..) or right(..) methods are called
in order to determine whether or not the lock will open (i.e.: when pull(..) is finally called).
To get started, make your class implement the IDialLock interface. The IDE should prompt you
to insert 'default / stub' implementations of the abstract methods in the interface.
Next, add the following fields to the class:
1. int maxTicks - this stores an upper bound on the digits around the lock.
2. int s1, s2, s3 - these are the three secret digits needed to open the lock.
3. int currentTick - the number the lock's dial is currently pointing towards (between
0..maxTicks).
4. List moves - this will store the history of turns made; so each time the left(..) or right(..)
methods are called, this list will increase in length by one.
Be sure to use appropriate access modifiers when defining the above fields.
Now add a constructor that accepts four ints as parameters:
s1, s2, and s3, and mTicks - these represent the three secret digits needed to open the lock, while
mTicks is the upper bound on the number of digits around the lock.
If any of these are negative, then throw a new IllegalArgumentException("secret digits cannot be
negative").
Important note: when initializing the maxTicks field within the constructor, do it this way:
this.maxT.
This document discusses conditional statements in Python. It introduces if, if-else, and if-elif-else constructs for decision making. Logical operators like and and or are also covered. The ternary operator provides another way to write conditional expressions. The get construct allows implementing conditional logic similar to a switch statement using dictionaries. Examples demonstrate taking input from the user and validating it, finding the greatest of three numbers, and conditionally executing code based on dictionary lookups. Proper indentation is emphasized as it determines code blocks in Python.
The document discusses JFC (Java Foundation Classes) and Swing, which are GUI toolkits for Java. It provides details on key JFC components like containers, controls, and displays. It also covers concepts like event handling with listeners, data models, and using graphics to draw on components. An example application is presented that counts button clicks to demonstrate designing a GUI with JFC components, laying them out, and handling click events.
This document discusses event handling in Java. It describes how events are triggered by changes in an object's state. The java.awt.event package provides event classes and listener interfaces for handling events. There are several steps to perform event handling: register a component with a listener using registration methods, implement the listener interface, and add event handling code either within the class, in another class, or as an anonymous class. Examples are provided of each approach to handling button click events and updating a text field.
1) The document provides an introduction to programming with the maXbox tool. It explains the interface and how to load sample code.
2) The sample code checks if numbers are prime by using a function called checkPrim() within a procedure called TestPrimNumbers(). It saves the results to a file.
3) The main routine calls TestPrimNumbers(), saves the output list to a file, loads the file, and displays the results along with performance times. This demonstrates functions, procedures, file I/O, and other basic programming concepts.
You can look at the Java programs in the text book to see how commenanitramcroberts
You can look at the Java programs in the text book to see how comments are added to programs.
Minimal Submitted Files
You are required, but not limited, to turn in the following source files:
Assignment6.java (No need to modify)
Movie.java (No need to modify, modified version from the assignment 4)
Review.java (No need to modify)
CreatePane.java - to be completed
ReviewPane.java - to be completed
You might need to add more methods than the specified ones.
Skills to be Applied:
JavaFX, ArrayList
Classes may be needed:
Button, TextField, TextArea, Label, RadioButton, ListView, and ActionHandler. You may use other classes.
Here is the Assignmnet6.java:
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.StackPane;
import java.util.ArrayList;
public class Assignment6 extends Application
{
private TabPane tabPane;
private CreatePane createPane;
private ReviewPane reviewPane;
private ArrayList movieList;
public void start(Stage stage)
{
StackPane root = new StackPane();
//movieList to be used in both createPane & reviewPane
movieList = new ArrayList();
reviewPane = new ReviewPane(movieList);
createPane = new CreatePane(movieList, reviewPane);
tabPane = new TabPane();
Tab tab1 = new Tab();
tab1.setText("Movie Creation");
tab1.setContent(createPane);
Tab tab2 = new Tab();
tab2.setText("Movie Review");
tab2.setContent(reviewPane);
tabPane.getSelectionModel().select(0);
tabPane.getTabs().addAll(tab1, tab2);
root.getChildren().add(tabPane);
Scene scene = new Scene(root, 700, 400);
stage.setTitle("Movie Review Apps");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
Here is Movie.java:
public class Movie
{
private String movieTitle;
private int year;
private int length;
private Review bookReview;
//Constructor to initialize all member variables
public Movie()
{
movieTitle = "?";
length = 0;
year = 0;
bookReview = new Review();
}
//Accessor methods
public String getMovieTitle()
{
return movieTitle;
}
public int getLength()
{
return length;
}
public int getYear()
{
return year;
}
public Review getReview()
{
return bookReview;
}
//Mutator methods
public void setMovieTitle(String aTitle)
{
movieTitle = aTitle;
}
public void setLength(int aLength)
{
length = aLength;
}
public void setYear(int aYear)
{
year = aYear;
}
public void addRating(double rate)
{
book ...
SCANNER CLASS(Methods)
DIALOG BOXES
Message Dialogs
INPUT DIALOGS
Disadvantage of JOptionPane
Methods for converting strings to numbers
DECISION / CONTROL FLOW STRUCTURES
IF STATEMENT
IF STATEMENT SYNTAX
Flow of If statements
If-else Statement
If –else statement SYNTAX
Logic of if-else Statement
NESTED IF STATEMENT
Nested if statement SYNTAX
This document discusses creating graphical user interfaces (GUIs) in Java using Swing. It introduces JFrame for creating windows, layout managers for positioning components, and common Swing components like JButton and JLabel. It also covers event handling using the delegation model with interfaces like ActionListener, creating menus, dialogs using JOptionPane and JFileChooser, and separating GUI code from business logic by implementing listeners.
Your 1ab8 c file is doe by Friday 1159pm to be submitted.pdfabhijitmaskey
Your 1ab8. c file is doe by Friday, 11.59pm, to be submitted on Gradescope. Overview This week,
you will start with last week's program and create your own functions for some of the tasks. You'll
have a printmenu () function, printarray () function and a convertcase () function. Just like you saw
in class, the code from the main () function that performs each of those tasks will be moved from
the the main () function and into their respective functions. More details about those functions are
shown below in the Lab Assignment section. All the functions will be in one file, called lab8.c.
Background Information For this lab, you will use last week's program to start with. Copy it and
rename it lab8.c. Again, you will be adding more code to this program in the future, so make sure
you get this one working. Functions and Reminders 1. As you saw in class, functions perform
(usually) one task, or a couple of smaller tasks that combined perform a task. 2. Some functions
return a value (the retum type being specified in the functon header/signature and a return
statement at the bottom of the function): int printmenu() & and some functions do not return any
value (the retum type then being specified as void and no return statement at the bottom of the
function): void convertCase (char text [MAX_LINE] [MAX_LINE_LEN] ) i 3. When arguments are
being sent to the function, the function then has "parameters" specified in the function
header/signature. The parameters that are specified indicate the type and the name: void
printarray (char text[MAX_LINE] [MAX_LINE_LEN], int size) { If a function is not being sent any
arguments, then the parameter list will be empty (meaning nothing in the parentheses). int
printMenu() f / / empty parentheses 4. When sending a 1-D array to a function, the parameter can
be specified with empty square brackets: int findLowest (int theArray[], int size) f // from in-class
exercise When a 2-D array is sent to a function, however, the parameter has to at least specify the
number of columns. So the parameter can be specified as: void f1 (int array [][12]) If a variable is
being used for the dimension(s) of the array, then the variable must appear first in the list of
parameters: void 11 (int numRows, int numCols, int array 1 [numRows] [numCols]) For this lab,
since the number of rows and number of columns are either idefine or constants, defined outside
of the main0 function, the parameter showing the array can use those names for the dimensions
without including them in the parameter list: void convertCase (char text[MAX_LINE]
[MAX_LINE_LEN]) I 5. As discussed in class, to eliminate chances of confusion, you should
ensure that there is no variable shadowing (the argument being sent to the function has a different
name than the parameter). 6. Function prototypes should be at the top of the file, EVFN IF THE
MAINO FUNCTION IS AT THE BOTTOM OF5. Function prototypes should be at the top of the file,
EVEN If THE MANNO FUNCTION IS AT THE.
This document discusses adding a scrolling body of text to a Java Swing application without using layout managers. It proposes a class that handles placing text boxes by trying to position each new control based on its specified position, and checking for and resolving any conflicts with previously placed controls by moving the new control up as needed to avoid overlaps.
This document discusses creating a class in Java Swing to handle displaying a scrolling body of text. It refers to previous documents that created an array of text boxes and stored their widths, heights, and positions. It introduces instance variables for the component array, component widths, component heights, and component positions that will be used by the new scrolling text class.
This document discusses adding a scrolling body of text to a Java Swing application without using a layout manager. It describes declaring a JTextArea variable to contain the text, populating the JTextArea with sample text from an array, and adding the JTextArea to a JScrollPane to enable scrolling. The JScrollPane is then added to the application frame to display the scrollable text.
This document discusses creating a scrolling body of text within a Java Swing application without using a layout manager. It introduces a series on this topic and provides code snippets for setting the location of an object using setLocation() and making a frame undecorated.
This document discusses creating a scrolling body of text in a Java Swing application without using a layout manager. It describes creating a ControlType class with static JButton and JTextField fields, initializing their sizes and locations, adding them to the application frame, and implementing an action listener to repaint the frame on button clicks.
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
GraphRAG for Life Science to increase LLM accuracyTomaz Bratanic
GraphRAG for life science domain, where you retriever information from biomedical knowledge graphs using LLMs to increase the accuracy and performance of generated answers
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Building Production Ready Search Pipelines with Spark and MilvusZilliz
Spark is the widely used ETL tool for processing, indexing and ingesting data to serving stack for search. Milvus is the production-ready open-source vector database. In this talk we will show how to use Spark to process unstructured data to extract vector representations, and push the vectors to Milvus vector database for search serving.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Best 20 SEO Techniques To Improve Website Visibility In SERPPixlogix Infotech
Boost your website's visibility with proven SEO techniques! Our latest blog dives into essential strategies to enhance your online presence, increase traffic, and rank higher on search engines. From keyword optimization to quality content creation, learn how to make your site stand out in the crowded digital landscape. Discover actionable tips and expert insights to elevate your SEO game.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
20240609 QFM020 Irresponsible AI Reading List May 2024
T
1. TFD
This, class TFD, shows adding controls to the frame without a Layout
manager.
Chapter Four of The JFC Swing Tutorial Second Edition
by Kathy Walrath et. al. discusses using the layout manager.
(http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html)
At the end, the section on "Absolute Positioning" or "Dong without a
Layout Manager" Of course, I note that the authors chide us taht, "you
should
use a layout if at all possible." In XXXX, I explain the impetus for
my dealing with absolute positioning now.
There is a series of operations, a pattern, for each control when we
do absolute positioning. They consist of the steps listed below.
I give a template for each step.
(In the document TFBackground--I discuss why I am doing this series of
gist's and companion power points.)
In the templates, I use:
ControlType for the Java Class such as JTextField or JButton.
V for the instance of that type, which, of course, is a pointer,
such as in JButton One, I generalize this to be ControlType V.
Of course, for each template, I tell you where it is exemplified in the
example source file, TFD.java.
That example at the beginning displays
a button and a text box. (designated One and Three). However, when the
user clicks on the button, another Button and Textbox are created.
They are called Two and Four. Note that the actual allocation is
in the main program. The actionPerfomed for the button is in
the class I defined, L, from lines 17 to 42.
As I am teaching absolute positioning, we have to write:
T.getContentPane().setLayout(null);
That turns off the normal default layout manager. (Many years ago, it
took
me much headscratching to discover that I needed to do that, as the
buttons,
etc. would come up but sometimes do strange things or move around in
strange
ways.)
1) Declare the V, ControlType V.
You will see I have four controls, with V's of One, Two, Three and
Four.
They are declared as follows:
static JButton One; // this is the one always on the screen.
static JButton Two; // this will be created by the first
2. static JTextField Three;
static JTextField Four;
2) For each one of these, do the standard Java thing
to actually create a new operator. That is:
V = new ControlType();
See the lines 55, 59, 60, and 67.
Note: I create the control and set its size in the main method. One and
Three
will actually be made visible to the user there. Two and Four will be
made visible to the user when they pressed the button One. That will
be in the code for the actionPerformed in the actionListener, L.
3) set the size for each control. That is:
V .setSize (width, height);
Alternatively, one can use the form:
Dimension d-name;
d-name = new Dimension( width, height);
V.setSize(d-name);
That is good software-enginnering to have several buttons of the same
size--one only changes that size respectively. For example, in
ABFEAapp, I want one of several messages to all be at the same size (and
location). I coded this as follows, with MS being the size.
MS = new Dimension (1000,50);
V.setSize(MS);
where V is the textbox containing the error messages
4) set the position. As we are using "absolute positioning," this
simply is the x and y location. The template is
V.setLocation( x-location, y-location)
Remember that the y-location is given from the TOP of the window.
Thus, V.setLocation (35,27) positions the top left hand corner of V
35 pixels from the left of the window and 27 pixels from the top.
(One can say this puts this 35,27 from the upper-left hand corner of the
frame.)
You wil find the lines to position One, Two, Three and Four in lines:
57, 64, 62, 69, respectively.
(Sorry my example did not have these in order.)
5) Add the control to the frame:
Frame.getContentPane().add( V );
As mentioned above, we only add the controls Two and Four when the First
button
is pressed: thus, you will see the statement to add these in the
ActionListener , L. (lines 26 and 30, respectively).
One and Three are shown when the application is started. Those, thus,
appear in the main method at lines 65 and 66.
3. As mentioned above, the controls Two and Four are made visible,
that is, added to the window, a JFrame, T, iwhen the button is pressed.
That is, this code is in the L, actionPerformed. However, I found
that they wer enot seen unless we do the following:
T.repaint() (on line 38).
import java.util.*;import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import Debug.*;
public class TFD {
static JFrame T;
static JButton One; // this is the one always on the screen.
static JButton Two; // this will be created by the first
static JTextField Three;
static JTextField Four;
static PrintWriter F;
static boolean SA=false;;
static public class L implements ActionListener {
public void actionPerformed (ActionEvent e) {
Debug.P(" in action Performed");
F.println (" in action performed");F.flush();
String t;
t = Three.getText();
F.println ( "String in actino performed |"+t+"|");F.flush();
if (!SA) {
SA=true;
T.getContentPane().add(Two);
M m;
m = new M();
Two.addActionListener(m);
T.getContentPane().add(Four);
Debug.P("finished adding Two and Four");
}
else {
t = Four.getText();
F.println ("got stuff from second text box |"+"|");F.flush();
Debug.P("in else");
}
T.repaint();
Debug.P("leaving action performed");
}
}
static public class M implements ActionListener{
public void actionPerformed (ActionEvent e) {
4. Debug.P("clicked Two");
}
}
public static void main (String [] args) throws IOException {
F = new PrintWriter (new FileOutputStream ("TF.out"));
T = new JFrame ();
T.setSize(150,350);
T.getContentPane().setLayout(null);
One = new JButton ("One");
One.setSize (100,50);
One.setLocation (20,70);
T.getContentPane().add(One);
Two = new JButton();
Three = new JTextField();
Three.setSize(100,50);
Three.setLocation(20,200);
Two.setSize(100,50);
Two.setLocation(20,130);
T.getContentPane().add(One);
T.getContentPane().add(Three);
Four = new JTextField();
Four.setSize(100,50);
Four.setLocation(20,280);
L L;
L = new L();
One.addActionListener(L);
T.setVisible(true);
}
}
5. TP
This short program shows adding a JTextArea to a frame. I am trying to
put it at the bottom of the window (I am turning off the layout manager,
using absolute positioning).
Since the height of the frame is in FH and the height of the JTextArea is
in TH,
positioning it with
T.setLocation (0,FH-TH) should put the text area at the bottom of the
screen with its bottom edge coincident with the bottom edge ofthe window.
It does not!
The problem is the top part of the window put in by Microsoft Windows.
When I add the line
Fr.setUndecorated(true);
the item is positioned correctly.
I looked for a command to get the height of that part, put in by Microsoft
Windows so I could allow for it. Found it as the call getInsets
( a member of the Component class). That worked fine.
Example: (f is the frame in which I wish to put the component TA).
(this corectly puts the TA at the bottom cnter of the frame with TA's
bottom
border properly flush against the bottom of the frame!)
Insets I;
I = f.getInsets();
int height=TA.getHeight();
int width = TA.getWidth();
int ypos = MyHeight - height - I.top-I.bottom;
MyWidth = MyWidth - I.left - I.right;
int xpos = I.left+MyWidth/2 - width /2;
TA.setLocation(xpos,ypos);
import java.io.*;import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TP {
static int FH = 200; // height of containing window
static int FW = 300; // width of containging window
static int TW = 75; // width of component
static int TH = 32; // height of component
static JFrame Fr; // containing window
public static void main (String[] args) {
Fr = new JFrame();
6. Fr.setLayout(null);
Fr.setSize(FW,FH);
JTextArea T;
T = new JTextArea();
javax.swing.border.Border B;
B = BorderFactory.createLineBorder(Color.red,3);
T.setBorder(B);
T.setSize(TW,TH);
T.setLocation(0,FH-TH);
Fr.add(T);
Fr.repaint();
Fr.setVisible(true);
}
}
7. T0
T0.java shows creating multi-line text boxes using both the
Abstract Window Toolkit (AWT) TextArea
and
Java Swing JTextArea.
As you know, AWT came with the original Java. Java Swing was built on top
of it. One can recognize the classes created by Java Swing--they begin
with
the letter J.
Often, the Java Swing has a version of each class
in AWT, but with a little gloss upon it. This unit (T0) covers and shows
TextArea and JTextArea.
In the case of AWT, the TextArea includes scrolling functionality.
That is, if one puts more text into the
TextArea than can be shown in the amount of space given to it with
setSize method, scroll bars will appear and function appropriately, In
Java Swing, one has to put the JTextArea in a JScrollPane if one wants to
have it scroll when this happens. (This is more of a difference than
one usually sees between the AWT class and the corresponding Java Swing
class.)
Our program creates one of each--I follow the steps and templates in
TFD unit. The routine stuff, I simply show the template. The lines
for AWT are in the left-hand column. The lines for Java Swing are in
the right-hand column. I put the line numbers for T0.java in parentheses.
How we get the text.
In my application, I wish to support receiving and displaying the text in
one of three ways:
An Array of Strings.
A big long String containing carriage returns.
Passing the name (or path name) of a file containing the text to be
displayed
A Collection of Strings. (See Chapter 21 on Collections in Java in
The Java Programming Language , Fourth Edition.)
For this example, I just show the first (Array of String) The example
input
is in JT on lines 79 to 84. Obviously, the extension of this to the other
three is straightforward, but I show it in the set XXX.
Step One:
ControlType V
TextArea TA (151) JTextArea RT (136)
JScrollPane J; (149)
8. Remember that in using the JSwing classes, one has to put the text area
within a JScrollPane. This is to handle the case when the text is too big
to fit in the space we care to allot on the screen for it.
Step Two:
V = new ControlType()
TA = new TextArea (B.toString(), RT = new JTextArea(NORows,MaxLL);
NoRows,NoCols);
Assume one has a Dimension D giving the space we care to allot to display
our text.
For using Java Swing, we need to find out how big the text is, assuming
we had a screen big enough to hold it. I call that measuring the text.
We assign that as the size of RT. Then, we set the JScrollPane to size D.
It is much a simpler for us programmers when we use
the AWT TextArea. We simply setSize TextArea to D. Any necessary
measuring of the text seems to be done internally by the TextArea.
Measuring the Text.
For the JTextArea (Java Swing), we have to find out how big the text would
be if we were to display it in all its glory. That is how big would the
text be if we were to allot enough space on the screen so the user could
see all of it at once (assuming that the display hardware were big
enough).
I call this "measuring the text."
We loop through the lines of the text. We get the length of each line,
both in pixels and in characters. We take the maximum of each.
This is a loop such as the following (lines 137 to 148):
See the JT discussion below.
for (i=0;i<JT.length;i++){
String L = JT[i]; // line that we are checking
Rectangle2D WR = SFM.getStringBounds (L,C);
int W= (int)WR.getWidth();
Debug.P(" processing line |"+L+"| position "+i+ " width is: "+W);
if (W>maxLW){
maxLW = W;
}
if (L.length() > maxLL) {
maxLL = L.length();
}
}
Remember that maxLW is the size of the JTextArea in pixels--that gets
passed
to its setSize call. maxLL is the length of the longest line in
characters!
We passed that to the constructor.
9. (That is known as the number of "columns" and there is a
getColumns method to get this value from the JTextArea--should one lose
track
of it.)
Some important things that I found the hard way.
Be sure that SFM is gotten by doing the getFontMetrics that one actually
is using on the JTextArea. We set that font with a command such as
RT.setFont(SF) or TA.setFont(TA). (lines 128 or 163).
Expletive-deleting this caused ugly space to appear to the right and
bottom of
our text as I scrolled it!
Also, C is gotten by using getGraphics() on the component in which we
are placing the text. I tried C = f.getGraphics() (line 109)
where f was simply the whole frame for our Windows program.
Sometimes, that seemed to work OK; sometimes it seemed to
matter that I actually got the context of the TextArea after I put it
on the frame.
Lastly, we get measure the height. That is easier as each line is
the same height. We get that by using the getHeight method of
the FontMetrics. It is important to realize that "This is the distance
between the baselines of adjacent lines of text." I call your attention
to the Java API documentation for FontMetrics.getHeight() (I took
the quote in the previous sentence from that documentation.)
We simply multipy that value by the number of lines that we include
in the text. See lines 149 to 151.
Glomming or Concatenating the text.
As mentioned above, I want my class to handle receiving the text in all
kinds of ways. In this set, I just show receiving the text as an array
of strings. That is, in T0.java, I declared (lines 79 to 84):
static String [] JT = new String [] {
"ONE True --- ONE ONE ----- ONE True ----- ONE True ---- ONE
True",
"TWO True --- TWO TWO ----- TWO True ----- TWO True ---- TWO
True",
"THREE True --- THREE THREE ----- THREE True ----- THREE True
---- THREE True",
"FOUR True --- FOUR FOUR ----- FOUR True ----- FOUR True ----
FOUR True"
};
Step Three:
For the TextArea, we simply apply the setSize method to it.
However, when using the JTextArea, as mentioned above, we put it in
a JScrollPane.
10. However, as mentioned, the size that is for the JTextArea is that of the
text in all its glory.
These are the variables maxLW and HT found in
Measuring the text. (lines 137 to 148 and 149)
Then, we simply write RT.setSize(maxLW,H);
The size on the screen is given to the JScrollPane itself. We have to put
the JTextArea inside the JScrollBar(). One should be able to do this
with the JScrollPane constructor:
JScrollPane J;
J = new JScrollPane(RT);
but I had better luck doing it piece-by-piece explicitly. Besides, it
helps
one understand what happens.
On lines 129 to 136 see something like the following:
JScrollPane J;
J = new JScrollPane();
J.setSize(100,50);
J.setLocation(50,50);
JViewport V;
V = (JViewport)J.getViewport();
V.add(RT);
At the beginning of the Swing API documetnation for the class JScrollPane,
you will see the discussionof the JViewPort which contains that which is
to
be scrolled. One can explicitly add the control representing that which
we are to scroll. In this case, that is the JTextArea RT.
Step Four
Of course, we just give the TextArea the size which it has to display
the text--which will usually be smaller than is needed to display all
that it will display. The TextArea will provide scroll bars and scrolling
that is needed:
TA.setSize(100,50);
TA.setLocation(50,200);
One thing I learned the hard way is that we need to explicitly set the
Font and color for the JTextArea. That is (lines 127 to 128):
RT.setForeground(Color.black);
RT.setFont(SF);
Remember, that we give the JScrollPane the explicit location
and size where we want them to appear on the screen for our user!
11. J.setLocation(50,50);
Step Five:
Remember that we add the TextArea directly to the screen; we add
the JScrollBar (containing the JTextArea) to the screen:
f.getContentPane().add(TA);
f.getContentPane().add(J);
(Lines 164 and 165)
In T1, I show creating a class to control these.
import java.util.*;
import java.awt.geom.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Font;
public class T0{
/**
* A simple debugging class I have been using for years.
* I put a shortened version, so
* this program is self-contained.
*<P>
* It is irrelevant to that which these examples are trying to teach.
*/
static class Debug {
public PrintWriter D;
Debug (){
try {
D = new PrintWriter (new FileOutputStream("T0.out"));
}
catch (IOException e) {
System.out.println ("cannot open debug file");
}
}
public void P(String s) {
D.println (s);D.flush();
}
public void P(String s,boolean b) {
if (b) {D.println (s);}else { D.print(s);}D.flush();
}
/**
* Simply, call {@code toString()} on the {@code Object} but shorten
* overlong results -- also protects from Null Exception if object is
* null.
*/
12. public String SS (Object O) {
if (O != null) {
String RT = O.toString();
if (RT.length() > 50) {
return RT.substring(0,50);
}
else {
return RT;
}
}
else {
return "null";
}
} // end SS method
} // end class Debug
static Debug Debug;
static JFrame f;
/**
* We will use this font throughout this example.
*/
static Font SF;
/**
* The {@code FontMetrics} for the standard font {@link SF}
* being used for text areas.
*/
static FontMetrics SFM;
/**
* The {@code Graphics} for the frame-- which we will need
* to get an accurate width for a line as wit will be displayed.
*/
static Graphics C;
/**
* the string on which we will test; the string that we will put in the
* text area;
*/
static String [] JT = new String [] {
"ONE True --- ONE ONE ----- ONE True ----- ONE True ---- ONE
True",
"TWO True --- TWO TWO ----- TWO True ----- TWO True ---- TWO
True",
"THREE True --- THREE THREE ----- THREE True ----- THREE True
---- THREE True",
"FOUR True --- FOUR FOUR ----- FOUR True ----- FOUR True ----
FOUR True"
};
/**
* The maximum length of a line, based upon the number of characters
*/
static int maxLL=0;
/**
13. * The maximum length of a line, based upon pixels.
*/
static int maxLW =0;
/**
* We will put the text area inside this to get it to scroll.
*/
public static void main (String [] args) throws IOException {
Debug = new Debug();
int i;
f = new JFrame();
f.setSize(400,500);
f.setLayout(null);
f.setVisible(true);
f.validate();
C = f.getGraphics();
SF = new Font ("Arial",Font.BOLD,24);
SFM = f.getFontMetrics(SF);
v
// determine maximum width and height of the text area
// based on putting in the text JT
JTextArea RT;
RT = new JTextArea();
// assemble text area
StringBuffer B;
B = new StringBuffer();
for (i=0;i<JT.length;i++){
B.append(JT[i]);
if (i!=JT.length-1){B.append ('n');}
}
RT.setForeground(Color.black);
RT.setFont(SF);
RT.setText(B.toString());
JScrollPane J;
J = new JScrollPane();
J.setSize(100,50);
J.setLocation(50,50);
JViewport V;
V = (JViewport)J.getViewport();
V.add(RT);
for (i=0;i<JT.length;i++){
String L = JT[i]; // line that we are checking
Rectangle2D WR = SFM.getStringBounds (L,C);
int W= (int)WR.getWidth();
Debug.P(" processing line |"+L+"| position "+i+ " width is: "+W);
if (W>maxLW){
maxLW = W;
}
14. if (L.length() > maxLL) {
maxLL = L.length();
}
}
int NORows = JT.length;
int height = SFM.getHeight(); // height of text area in pixels
int H = NORows*height;
Debug.P(" after loop max LW is "+maxLW + " pixels; max LL = "+maxLL+ "
characters ");
RT.setSize(maxLW,H);
Debug.P (" RT 's text is |"+RT.getText()+"| its font " +RT.getFont() + "
its color "+RT.getForeground() + " checking that it is in the view port
"+V.getComponent(0) + " number of rows in RT is " + RT.getRows() + "
number of columns in RT is " + RT.getColumns());
Debug.P(" the text sent to text area is |"+B.toString()+"|",false);
Debug.P(" after measuring text ("+maxLW+","+H+")");
TextArea TA;
TA = new TextArea (B.toString(),NORows,maxLL);
Debug.P(" Constructing Text Area with
|"+B.toString()+"|,"+NORows+","+maxLL+")");
TA.setSize(100,50);
TA.setLocation(50,200);
TA.setFont(SF);
f.getContentPane().add(J);
f.getContentPane().add(TA);
f.validate();
f.repaint();
} // end of main method
} //end of class
15. T1
In T1, we create a class SWA to handle much of these. I will be building
on these to add more wonderful complications :-) in the T2 and T3 series.
Be sure to see the Unified Model Language (UML) diagram in T1.pptx.
It shows the relationships
between SWA, the outer Frame, and, right now, the single text area on
that Frame!
Now, please remember from your understanding of Java GUI programming
(that is the AWT package and the Java Swing package) that one can
associate a ComponentListener to a main window of an application.
It detects when the user resizes the window by dragging the sides.
Conveniently, it also detects when the Component first comes up.
SWA implements that ComponentListener interface!
(There are four methods in the interface.
That means that SWA will have a definition for each of these four methods.
However, all that we need to do, all the action for this series,
I put in the method I define, Adjust. All four of those methods simply
call Adjust!
All four of those methods have a single argument, a ComponentEvent.
(This
is fairly typical for methods in listeners and adapters in Java
Swing/AWT.)
From that, we get the Component that was resized or shown. This is the
OUTER window!
(By the way, I do check that the Component is a Resized or Shown--if it
was one of the other two things (hidden or moved), we do nothing.)
In order to proceed, we need to know the new width and height of the
OUTER window!
(Or the initial height and width if this window is the first time shown).
I get them in lines 262 to 264.
I put them in global variables, MyHeight and MyWidth.
In this example, there is a single component for which the SWA is
responsible. That is indicated by the connection mc (see that UML
diagram).
The T2 series will have multiple things managed by each SWA instance.
The T3 series will have multiple SWA instances, one for each Frame (outer
window) in the application program.
In this example, T1.java, we only support centering the item in the lower
left-hand corner of its outer window. That item's size
is given bythe variables height and width. CSP sets these in the
SWA instance.
To adjust the item properly, we use the formula:
16. xpos = MyWidth / 2 – width/2;
Then, we set the location:
mc.setLocation(xpos,ypos);
(The ypos is computed from the vertical room in the window - the height
of its object. Remember that in Java Swing, as in most graphical
systems,
the y axis goes downward with zero representing the top of the window.
In fact, we have to allow for what are called "Decorations." In
particular,
the bar at the top of the window, so familiar that you probably that you
don't think about it. It is where the little button to minimize the
window,
make the window go to the entire size of your screen or exit the
application
with an X are. (We can turn these off with setDecorations(false)'
Unfortunately, that also means that we cannot resize the window, the whole
point of this exercise.)
The Java AWT Frame class implements the method getInsets(). That enables
us
to find out how much space is taken up by these decorations. (There is a
smaller amount of space taken up by borders on the left, right and bottom
sides of a typical window.)
See, in particular lines 266, 270.
Also, shoudl the user make the screen so small that we cannot display
the text area completely, we make the item smaller. Note that the
SWA class variables height and width don't change when this occurs.
The result is that the component size snaps right back when the user makes
the window big enough to contain the component completely.
Note that T1.java's implementation of SWA only allows for items to be
centered. (Note that the whole series only provides for items on the
bottom of the window.)
See T1b.java, where we pass a position to addTextArea when we create
the text area. A zero value means that the item should be centered,
as in T1.java. A positive value is the number of pixels from the left-
hand
corner. A negative value allows one to define that the item should
be so many pixels from the right-hand margin. That is, a -1 right-
justifies
the smaller text area or component within the main screen.
In T1B.java, see line 328 for the calculation in Adjust
import java.util.*;
import java.awt.geom.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
17. import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
public class T1{
/**
* A simple debugging class I have been using for years.
* I put a shortened version, so
* this program is self-contained.
*/
static class Debu {
/**
* This is the debugging file; normally, one puts stuff in it
* with {@link P(String} or {@link P(String,booolean)}; but, one
* can write directly to it, if convenient.
*/
public PrintWriter D;
/**
* Create/open debugging file, {@link D}.
*/
Debu (){
try {
D = new PrintWriter (new FileOutputStream("T1.out"));
}
catch (IOException e) {
System.out.println ("cannot open debug file");
}
}
/**
* output string to debugging file, with a new line.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s) {
D.println (s);D.flush();
}
/**
* output string to debugging file, with a new line only if {@code b}
* is true.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s,boolean b) {
if (b) {D.println (s);}else { D.print(s);}D.flush();
}
/**
* Simply, get Hash code and then call {@code toString()} on the
{@code Object} but shorten
* overlong results -- also it protects from Null Exception if object
is
* null.
* @param O - that which is to be output to debugging file
18. * @returns {@code String} which will usually be sent to {@code P}.
*/
public String SS (Object O) {
if (O != null) {
String RT = O.hashCode()+": "+O.toString();
if (RT.length() > 57) {
return RT.substring(0,57);
}
else {
return RT;
}
}
else {
return "null";
}
} // end of SS method
} // end of Debug class
static JFrame f;
static Debu Debug;
/**
* We will use this font throughout this example.
*/
static Font SF;
/**
* The {@code FontMetrics} for the standard font {@link SF}
* being used for text areas.
*/
static FontMetrics SFM;
/**
* see the discussion in the companion files {@code T1} and {@code
T1.pptx}.
*/
static class SWA implements ComponentListener {
/**
* if on, then, we will write some stuff to the debugging file,using my
* {@code Debug} class.
*/
boolean Dx=false;
/**
* To Whom I belong. If this is a {@code JFrame} or {@code Frame}, we
will
* call {@code getInsets} to get the proper width and height without the
* "decorations". See the discussion at the beginning of the {@code AWT}
* class {@code Frame}. Otherwise, {@code F} will be empty and we will
* just have C set. If we are using a frame, the caller, wil have to get
* the component by calling {@code getContentPane()}.
*/
Frame F;
/**
19. * To Whom I belong. If ultimate is a {@code JFrame} or {@code Frame},
the
* caller will have to
* call {@code getContentPane()}.
* @see F
*/
Container MC;
/**
* This associates this with the frame or other thing containing the
* components being adjusted.
*/
public void AM (Container WTA, JFrame F) {
MC = WTA;
this.F=F;
F.addComponentListener(this);
}
/*
* This is the component that we are adjusting and displaying here
* A later version will do arrays of these things.
*/
Component mc;
/**
* In spite of its name, will take any {@code Component} and associate it
with the
* frame to which this {@code SWA} is attached.
* It is intended to be used by simply
* passing {@code frame.getContentPane()} for the one argument, {@code
JTA}.
* @see AddScrollPane
*/
void addTextArea (Component JTA){
this.mc = JTA;
if (MC!=null) {
MC.add(JTA);
}
}
/**
* Take the indicated {@code Component} and put it in a {@code
JScrollPane}.
* Note, programmer is responsible
* for setting its location and actually adding it
* to the frame to be seen to the unit.
* Uses default size with which to show this for the user.
*/
JScrollPane CSP (Component JTA) {
return CSP ( JTA, 200,50);
}
/**
* Take the indicated {@code Component} {@code JTA} and put it on
* a {@code JScrollPane} on the associated {@link Frame}. Uses the
* indicated size. Except if the {@code JTA} is smaller than that size,
20. * we make the scrollbar fit the text. In other words, if the text is
shorter
* or narrower than the programmer expects, we use the width or height
that
* we actually need rather than what the programmer specified.
* Programmer is responsible for setting its location.
*/
JScrollPane CSP(Component JTA, int width, int height){
JScrollPane J;
J = new JScrollPane();
int Width = JTA.getWidth();
int Height = JTA.getHeight();
if (Width < width){
width = Width;
}
if (Height < height) {
height = Height;
}
J.setSize(width,height);
JViewport V;
V = (JViewport)J.getViewport();
V.add(JTA);
mc = J;
return J;
}
/**
* Create a {@code JTextArea} from the {@code String WTD} , which
presumably
* has carriage returns separating the lines or rows in the {@code
TextArea}
* @param WTD stick this content in the return {@code TextArea}
* @returns a {@code TextArea} set with the appropriate number of rows
and columns as well as the width and height in pixels.
* <P>
* To better measure the text
* (see companion files {@code T0} and {@code T1} or {@code T0.pptx}
* or {@code T1.pptx}, we will add this, at least temporarily to the
* {@code Container} with which this is associated. That assume that
this was
* associated with one; we tell by seeing if {@code MC} is not {@code
null}.
*/
public JTextArea CTA ( String WTD){
int NoRows;
NoRows = 0;
char c; int i; int W /* width */; // temps
int LastPos=0;
int maxLL = 0; // maximum length of a line based on the number of
characters
int maxLW = 0; // maximum length of a line based upon the font
// (in a unit like pixels)
21. int NumberChars;
JTextArea RT; // text area to be returned. (This is an abbreviation for
// Return This.
RT = new JTextArea();
RT.setFont(SF);
RT.setForeground(Color.black);
Graphics C;
if (MC !=null) {
MC.add(RT);
}
C = RT.getGraphics();
for (i=0 ; i < WTD.length();i++) {
c = WTD.charAt(i);
if (c== 'n') {
NoRows++;
NumberChars = i-LastPos;
if (NumberChars > maxLL) {
maxLL = NumberChars;
}
String L;
if (LastPos==0) {
L = WTD.substring(0,i);
}
else {
L = WTD.substring(LastPos+1,i);
}
C = RT.getGraphics();
Rectangle2D WR = SFM.getStringBounds(L,C);
W = (int)WR.getWidth();
if (Dx) {
}
if (W > maxLW) {
maxLW = W;
}
LastPos=i;
if (Dx) {
}
} // we have a new line, separating actual lines in the text area.
} // loop through all characters in the String to put in the text area.
int height = SFM.getHeight();
int H = NoRows*height; // height that we will make our JTextArea to be
RT.setSize(maxLW,H);
RT.setText(WTD);
return RT;
}
/**
* Put this text area (or other component) at the bottom center of the
frame
* {@link F} to whom I belong. <P>Later versions of this class will give
* more control over multiple components.
* This is called whenever {@link F} has an event associated with
* {@code ComponentListener} interface.
*/
22. private void Adjust (ComponentEvent e) {
int eid=e.getID();
if (eid == ComponentEvent.COMPONENT_RESIZED || eid ==
ComponentEvent.COMPONENT_SHOWN){
if (mc!=null){
Component w = e.getComponent();
int MyHeight=w.getHeight();
int MyWidth = w.getWidth();
Insets I;
I = F.getInsets();
int height=mc.getHeight();
int width = mc.getWidth();
int ypos;
int room = MyHeight-I.top-I.bottom; // how much room there is in the
window;
boolean flag=false;// if the component's size does not fit in the window,
// we set this true, so we change the size of the
// textbox to fit.
if (room>height){
ypos = MyHeight - height - I.top-I.bottom;
}
else {
ypos = I.top;
height = room;
flag=true;
}
MyWidth = MyWidth - I.left - I.right;
int xpos;
if (width <MyWidth) {
xpos = I.left+MyWidth/2 - width /2;
}
else {
xpos = I.left;
width = MyWidth;
flag = true;
}
mc.setLocation(xpos,ypos);
if (flag) { mc.setSize(width,height);}
} // there really is a component to adjust
} // this is one of the events for which we could move around the
component
} // end of Adjust method.
public void componentResized (ComponentEvent e) {
Adjust(e);
}
public void componentMoved (ComponentEvent e) {
Adjust(e);
}
public void componentHidden(ComponentEvent e){
Adjust(e);
}
public void componentShown (ComponentEvent e){
Adjust(e);
23. }
} // end of SWA class, this is the class, we are trying to demonstrate.
/**
* For testing, the string to be put in the {@code JTextArea} on the
screen.
*/
static String JT =
"ONE True --- ONE ONE ----- ONE True ----- ONE True ---- ONE
True"+'n'+
"TWO True --- TWO TWO ----- TWO True ----- TWO True ---- TWO
True"+'n'+
"THREE True --- THREE THREE ----- THREE True ----- THREE True
---- THREE True"+'n'+
"FOUR True --- FOUR FOUR ----- FOUR True ----- FOUR True ----
FOUR True";
public static void main (String [] args) throws IOException {
Debug = new Debu();
f = new JFrame();
f.setSize(400,500);
f.setLayout(null);
SF = new Font ("Arial",Font.BOLD,24);
SFM = f.getFontMetrics(SF);
SWA wa = new SWA();
wa.Dx = true;
wa.AM(f.getContentPane(),f);
JTextArea JTA;
JScrollPane J;
JTA = wa.CTA(JT);
J = wa.CSP(JTA,275,100);
wa.addTextArea(J);
f.setVisible(true);
f.repaint();
} // end of main
} //end of program (class)
import java.util.*;
import java.awt.geom.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
public class T1A{
24. /**
* A simple debugging class I have been using for years.
* I put a shortened version, so
* this program is self-contained.
*/
static class Debu {
/**
* This is the debugging file; normally, one puts stuff in it
* with {@link P(String} or {@link P(String,booolean)}; but, one
* can write directly to it, if convenient.
*/
public PrintWriter D;
/**
* Create/open debugging file, {@link D}.
*/
Debu (){
try {
D = new PrintWriter (new FileOutputStream("T1.out"));
}
catch (IOException e) {
System.out.println ("cannot open debug file");
}
}
/**
* output string to debugging file, with a new line.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s) {
D.println (s);D.flush();
}
/**
* output string to debugging file, with a new line only if {@code b}
* is true.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s,boolean b) {
if (b) {D.println (s);}else { D.print(s);}D.flush();
}
/**
* Simply, get Hash code and then call {@code toString()} on the
{@code Object} but shorten
* overlong results -- also it protects from Null Exception if object
is
* null.
* @param O - that which is to be output to debugging file
* @returns {@code String} which will usually be sent to {@code P}.
*/
public String SS (Object O) {
if (O != null) {
String RT = O.hashCode()+": "+O.toString();
25. if (RT.length() > 57) {
return RT.substring(0,57);
}
else {
return RT;
}
}
else {
return "null";
}
} // end of SS method
} // end of Debug class
static JFrame f;
static Debu Debug;
/**
* We will use this font throughout this example.
*/
static Font SF;
/**
* The {@code FontMetrics} for the standard font {@link SF}
* being used for text areas.
*/
static FontMetrics SFM;
/**
* see the discussion in the companion files {@code T1} and {@code
T1.pptx}.
*/
static class SWA implements ComponentListener {
/**
* if on, then, we will write some stuff to the debugging file,using my
* {@code Debug} class.
*/
boolean Dx=false;
/**
* To Whom I belong. If this is a {@code JFrame} or {@code Frame}, we
will
* call {@code getInsets} to get the proper width and height without the
* "decorations". See the discussion at the beginning of the {@code AWT}
* class {@code Frame}. Otherwise, {@code F} will be empty and we will
* just have C set. If we are using a frame, the caller, wil have to get
* the component by calling {@code getContentPane()}.
*/
Frame F;
/**
* To Whom I belong. If ultimate is a {@code JFrame} or {@code Frame},
the
* caller will have to
* call {@code getContentPane()}.
* @see F
*/
26. Container MC;
/**
* This associates this with the frame or other thing containing the
* components being adjusted.
*/
public void AM (Container WTA, JFrame F) {
MC = WTA;
this.F=F;
F.addComponentListener(this);
}
/**
* This is the component that we are adjusting and displaying here
* A later version will do arrays of these things.
*/
Component mc;
/**
* This is the preferred width of the component added, assuming there is
* enough room for it.
*/
int mcw;
/**
* This is the preferred height of the component added, assuming there is
* enough room for it.
*/
int mch;
/**
* In spite of its name, will take any {@code Component} and associate it
with the
* frame to which this {@code SWA} is attached.
* It is intended to be used by simply
* passing {@code frame.getContentPane()} for the one argument, {@code
JTA}.
* @see AddScrollPane
*/
void addTextArea (Component JTA){
this.mc = JTA;
if (MC!=null) {
MC.add(JTA);
}
}
/**
* Take the indicated {@code Component} and put it in a {@code
JScrollPane}.
* Note, programmer is responsible
* for setting its location and actually adding it
* to the frame to be seen to the unit.
* Uses default size with which to show this for the user.
*/
JScrollPane CSP (Component JTA) {
return CSP ( JTA, 200,50);
}
27. /**
* Take the indicated {@code Component} {@code JTA} and put it on
* a {@code JScrollPane} on the associated {@link Frame}. Uses the
* indicated size. Except if the {@code JTA} is smaller than that size,
* we make the scrollbar fit the text. In other words, if the text is
shorter
* or narrower than the programmer expects, we use the width or height
that
* we actually need rather than what the programmer specified.
* Programmer is responsible for setting its location.
*/
JScrollPane CSP(Component JTA, int width, int height){
JScrollPane J;
J = new JScrollPane();
int Width = JTA.getWidth();
int Height = JTA.getHeight();
if (Width < width){
width = Width;
}
if (Height < height) {
height = Height;
}
J.setSize(width,height);
JViewport V;
V = (JViewport)J.getViewport();
V.add(JTA);
mc = J;
mcw = width;
mch = height;
return J;
}
/**
* Create a {@code JTextArea} from the {@code String WTD} , which
presumably
* has carriage returns separating the lines or rows in the {@code
TextArea}
* @param WTD stick this content in the return {@code TextArea}
* @returns a {@code TextArea} set with the appropriate number of rows
and columns as well as the width and height in pixels.
* <P>
* To better measure the text
* (see companion files {@code T0} and {@code T1} or {@code T0.pptx}
* or {@code T1.pptx}, we will add this, at least temporarily to the
* {@code Container} with which this is associated. That assume that
this was
* associated with one; we tell by seeing if {@code MC} is not {@code
null}.
*/
public JTextArea CTA ( String WTD){
int NoRows;
NoRows = 0;
28. char c; int i; int W /* width */; // temps
int LastPos=0;
int maxLL = 0; // maximum length of a line based on the number of
characters
int maxLW = 0; // maximum length of a line based upon the font
// (in a unit like pixels)
int NumberChars;
JTextArea RT; // text area to be returned. (This is an abbreviation for
// Return This.
RT = new JTextArea();
RT.setFont(SF);
RT.setForeground(Color.black);
Graphics C;
if (MC !=null) {
MC.add(RT);
}
C = RT.getGraphics();
for (i=0 ; i < WTD.length();i++) {
c = WTD.charAt(i);
if (c== 'n') {
NoRows++;
NumberChars = i-LastPos;
if (NumberChars > maxLL) {
maxLL = NumberChars;
}
String L;
if (LastPos==0) {
L = WTD.substring(0,i);
}
else {
L = WTD.substring(LastPos+1,i);
}
C = RT.getGraphics();
Rectangle2D WR = SFM.getStringBounds(L,C);
W = (int)WR.getWidth();
if (Dx) {
}
if (W > maxLW) {
maxLW = W;
}
LastPos=i;
if (Dx) {
}
} // we have a new line, separating actual lines in the text area.
} // loop through all characters in the String to put in the text area.
int height = SFM.getHeight();
int H = NoRows*height; // height that we will make our JTextArea to be
RT.setSize(maxLW,H);
RT.setText(WTD);
return RT;
}
/**
29. * Put this text area (or other component) at the bottom center of the
frame
* {@link F} to whom I belong. <P>Later versions of this class will give
* more control over multiple components.
* This is called whenever {@link F} has an event associated with
* {@code ComponentListener} interface.
*/
private void Adjust (ComponentEvent e) {
int eid=e.getID();
if (eid == ComponentEvent.COMPONENT_RESIZED || eid ==
ComponentEvent.COMPONENT_SHOWN){
if (mc!=null){
Component w = e.getComponent();
int MyHeight=w.getHeight();
int MyWidth = w.getWidth();
Insets I;
I = F.getInsets();
int height=mch;
int width = mcw;
int ypos;
int room = MyHeight-I.top-I.bottom; // how much room there is in the
window;
boolean flag=false;// if the component's size does not fit in the window,
// we set this true, so we change the size of the
// textbox to fit.
if (room>height){
ypos = MyHeight - height - I.top-I.bottom;
}
else {
ypos = I.top;
height = room;
flag=true;
}
MyWidth = MyWidth - I.left - I.right;
int xpos;
if (width <MyWidth) {
xpos = I.left+MyWidth/2 - width /2;
}
else {
xpos = I.left;
width = MyWidth;
flag = true;
}
mc.setLocation(xpos,ypos);
if (flag) { mc.setSize(width,height);}
} // there really is a component to adjust
} // this is one of the events for which we could move around the
component
} // end of Adjust method.
public void componentResized (ComponentEvent e) {
Adjust(e);
}
public void componentMoved (ComponentEvent e) {
30. Adjust(e);
}
public void componentHidden(ComponentEvent e){
Adjust(e);
}
public void componentShown (ComponentEvent e){
Adjust(e);
}
} // end of SWA class, this is the class, we are trying to demonstrate.
/**
* For testing, the string to be put in the {@code JTextArea} on the
screen.
*/
static String JT =
"ONE True --- ONE ONE ----- ONE True ----- ONE True ---- ONE
True"+'n'+
"TWO True --- TWO TWO ----- TWO True ----- TWO True ---- TWO
True"+'n'+
"THREE True --- THREE THREE ----- THREE True ----- THREE True
---- THREE True"+'n'+
"FOUR True --- FOUR FOUR ----- FOUR True ----- FOUR True ----
FOUR True";
public static void main (String [] args) throws IOException {
Debug = new Debu();
f = new JFrame();
f.setSize(400,500);
f.setLayout(null);
SF = new Font ("Arial",Font.BOLD,24);
SFM = f.getFontMetrics(SF);
SWA wa = new SWA();
wa.Dx = true;
wa.AM(f.getContentPane(),f);
JTextArea JTA;
JScrollPane J;
JTA = wa.CTA(JT);
J = wa.CSP(JTA,275,100);
wa.addTextArea(J);
f.setVisible(true);
f.repaint();
} // end of main
} //end of program (class)
import java.util.*;
import java.awt.geom.*;
import java.io.*;
31. import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
public class T1B{
/**
* A simple debugging class I have been using for years.
* I put a shortened version, so
* this program is self-contained.
*/
static class Debu {
/**
* This is the debugging file; normally, one puts stuff in it
* with {@link P(String} or {@link P(String,booolean)}; but, one
* can write directly to it, if convenient.
*/
public PrintWriter D;
/**
* Create/open debugging file, {@link D}.
*/
Debu (){
try {
D = new PrintWriter (new FileOutputStream("T1.out"));
}
catch (IOException e) {
System.out.println ("cannot open debug file");
}
}
/**
* output string to debugging file, with a new line.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s) {
D.println (s);D.flush();
}
/**
* output string to debugging file, with a new line only if {@code b}
* is true.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s,boolean b) {
if (b) {D.println (s);}else { D.print(s);}D.flush();
}
/**
* Simply, get Hash code and then call {@code toString()} on the
{@code Object} but shorten
* overlong results -- also it protects from Null Exception if object
is
32. * null.
* @param O - that which is to be output to debugging file
* @returns {@code String} which will usually be sent to {@code P}.
*/
public String SS (Object O) {
if (O != null) {
String RT = O.hashCode()+": "+O.toString();
if (RT.length() > 57) {
return RT.substring(0,57);
}
else {
return RT;
}
}
else {
return "null";
}
} // end of SS method
} // end of Debug class
static JFrame f;
static Debu Debug;
/**
* We will use this font throughout this example.
*/
static Font SF;
/**
* The {@code FontMetrics} for the standard font {@link SF}
* being used for text areas.
*/
static FontMetrics SFM;
/**
* see the discussion in the companion files {@code T1} and {@code
T1.pptx}.
*/
static class SWA implements ComponentListener {
/**
* if on, then, we will write some stuff to the debugging file,using my
* {@code Debug} class.
*/
boolean Dx=false;
/**
* To Whom I belong. If this is a {@code JFrame} or {@code Frame}, we
will
* call {@code getInsets} to get the proper width and height without the
* "decorations". See the discussion at the beginning of the {@code AWT}
* class {@code Frame}. Otherwise, {@code F} will be empty and we will
* just have C set. If we are using a frame, the caller, wil have to get
* the component by calling {@code getContentPane()}.
*/
Frame F;
33. /**
* To Whom I belong. If ultimate is a {@code JFrame} or {@code Frame},
the
* caller will have to
* call {@code getContentPane()}.
* @see F
*/
Container MC;
/**
* This associates this with the frame or other thing containing the
* components being adjusted.
*/
public void AM (Container WTA, JFrame F) {
MC = WTA;
this.F=F;
F.addComponentListener(this);
}
/**
* This is the component that we are adjusting and displaying here
* A later version will do arrays of these things.
*/
Component mc;
/**
* This is the preferred width of the component added, assuming there is
* enough room for it.
*/
int mcw;
/**
* This is the preferred height of the component added, assuming there is
* enough room for it.
*/
int mch;
/**
* position to put {@link mc} relative to the containing window (@link
MC}
* <UL><LI>
* If positive, will be the number of pixels of right of the left-hand
side
* of {@link MC}
* <LI>
* If negative, will give the number of pixels to the left of the right-
hand
* edge of the containing window (@link MC}. That is, the {@code
Component}
* will be kept with a certain right margin.
* <LI>
* If zero, will be centered like in {@code T1A.java}.
* </UL>
*/
int position;
/**
34. * In spite of its name, will take any {@code Component} and associate it
with the
* frame to which this {@code SWA} is attached.
* It is intended to be used by simply
* passing {@code frame.getContentPane()} for the one argument, {@code
JTA}.
* @see AddScrollPane
* @param JTA that which is to be added.
* @param position <UL><LI> position is positive, that is the number of
pixels from the lower=left <LI>position is negative, then this will give
the number of pixels from the right<LI>if position is zero, then it will
be centered</UL>--note, it is impossible to align this precisely with the
lower left hand corner. Simply have it one pixel just to the right of
that.
*/
void addTextArea (Component JTA,int position){
this.position = position;
this.mc = JTA;
if (MC!=null) {
MC.add(JTA);
}
}
/**
* In spite of its name, will take any {@code Component} and associate it
with the
* frame to which this {@code SWA} is attached.
* It is intended to be used by simply
* passing {@code frame.getContentPane()} for the one argument, {@code
JTA}.
* @see AddScrollPane
* @param JTA that which is to be added.
*/
void addTextArea(Component JTA) {
addTextArea(JTA,0);
}
/**
* Take the indicated {@code Component} and put it in a {@code
JScrollPane}.
* Note, programmer is responsible
* for setting its location and actually adding it
* to the frame to be seen to the unit.
* Uses default size with which to show this for the user.
*/
JScrollPane CSP (Component JTA) {
return CSP ( JTA, 200,50);
}
/**
* Take the indicated {@code Component} {@code JTA} and put it on
* a {@code JScrollPane} on the associated {@link Frame}. Uses the
* indicated size. Except if the {@code JTA} is smaller than that size,
* we make the scrollbar fit the text. In other words, if the text is
shorter
35. * or narrower than the programmer expects, we use the width or height
that
* we actually need rather than what the programmer specified.
* Programmer is responsible for setting its location.
*/
JScrollPane CSP(Component JTA, int width, int height){
JScrollPane J;
J = new JScrollPane();
int Width = JTA.getWidth();
int Height = JTA.getHeight();
if (Width < width){
width = Width;
}
if (Height < height) {
height = Height;
}
J.setSize(width,height);
JViewport V;
V = (JViewport)J.getViewport();
V.add(JTA);
mc = J;
mcw = width;
mch = height;
return J;
}
/**
* Create a {@code JTextArea} from the {@code String WTD} , which
presumably
* has carriage returns separating the lines or rows in the {@code
TextArea}
* @param WTD stick this content in the return {@code TextArea}
* @returns a {@code TextArea} set with the appropriate number of rows
and columns as well as the width and height in pixels.
* <P>
* To better measure the text
* (see companion files {@code T0} and {@code T1} or {@code T0.pptx}
* or {@code T1.pptx}, we will add this, at least temporarily to the
* {@code Container} with which this is associated. That assume that
this was
* associated with one; we tell by seeing if {@code MC} is not {@code
null}.
*/
public JTextArea CTA ( String WTD){
int NoRows;
NoRows = 0;
char c; int i; int W /* width */; // temps
int LastPos=0;
int maxLL = 0; // maximum length of a line based on the number of
characters
int maxLW = 0; // maximum length of a line based upon the font
// (in a unit like pixels)
36. int NumberChars;
JTextArea RT; // text area to be returned. (This is an abbreviation for
// Return This.
RT = new JTextArea();
RT.setFont(SF);
RT.setForeground(Color.black);
Graphics C;
if (MC !=null) {
MC.add(RT);
}
C = RT.getGraphics();
for (i=0 ; i < WTD.length();i++) {
c = WTD.charAt(i);
if (c== 'n') {
NoRows++;
NumberChars = i-LastPos;
if (NumberChars > maxLL) {
maxLL = NumberChars;
}
String L;
if (LastPos==0) {
L = WTD.substring(0,i);
}
else {
L = WTD.substring(LastPos+1,i);
}
C = RT.getGraphics();
Rectangle2D WR = SFM.getStringBounds(L,C);
W = (int)WR.getWidth();
if (Dx) {
}
if (W > maxLW) {
maxLW = W;
}
LastPos=i;
if (Dx) {
}
} // we have a new line, separating actual lines in the text area.
} // loop through all characters in the String to put in the text area.
int height = SFM.getHeight();
int H = NoRows*height; // height that we will make our JTextArea to be
RT.setSize(maxLW,H);
RT.setText(WTD);
return RT;
}
/**
* Put this text area (or other component) at the bottom center of the
frame
* {@link F} to whom I belong. <P>Later versions of this class will give
* more control over multiple components.
* This is called whenever {@link F} has an event associated with
* {@code ComponentListener} interface.
*/
37. private void Adjust (ComponentEvent e) {
int eid=e.getID();
if (eid == ComponentEvent.COMPONENT_RESIZED || eid ==
ComponentEvent.COMPONENT_SHOWN){
if (mc!=null){
Component w = e.getComponent();
int MyHeight=w.getHeight();
int MyWidth = w.getWidth();
Insets I;
I = F.getInsets();
int height=mch;
int width = mcw;
int ypos;
int room = MyHeight-I.top-I.bottom; // how much room there is in the
window;
boolean flag=false;// if the component's size does not fit in the window,
// we set this true, so we change the size of the
// textbox to fit.
if (room>height){
ypos = MyHeight - height - I.top-I.bottom;
}
else {
ypos = I.top;
height = room;
flag=true;
}
int myWidth; // my real width after subtracting any insets
myWidth = MyWidth - I.left - I.right;
int xpos;
if (width <MyWidth) {
xpos=0;
if (position ==0){
xpos = I.left+MyWidth/2 - width /2;
}
else
if (position > 0) {
xpos = I.left + position;
}
else
if (position <0) {
xpos = -I.right + myWidth - width + position;
}
}
else {
xpos = I.left;
width = MyWidth;
flag = true;
}
mc.setLocation(xpos,ypos);
if (flag) { mc.setSize(width,height);}
} // there really is a component to adjust
} // this is one of the events for which we could move around the
component
} // end of Adjust method.
38. public void componentResized (ComponentEvent e) {
Adjust(e);
}
public void componentMoved (ComponentEvent e) {
Adjust(e);
}
public void componentHidden(ComponentEvent e){
Adjust(e);
}
public void componentShown (ComponentEvent e){
Adjust(e);
}
} // end of SWA class, this is the class, we are trying to demonstrate.
/**
* For testing, the string to be put in the {@code JTextArea} on the
screen.
*/
static String JT =
"ONE True --- ONE ONE ----- ONE True ----- ONE True ---- ONE
True"+'n'+
"TWO True --- TWO TWO ----- TWO True ----- TWO True ---- TWO
True"+'n'+
"THREE True --- THREE THREE ----- THREE True ----- THREE True
---- THREE True"+'n'+
"FOUR True --- FOUR FOUR ----- FOUR True ----- FOUR True ----
FOUR True";
public static void main (String [] args) throws IOException {
Debug = new Debu();
f = new JFrame();
f.setSize(400,500);
f.setLayout(null);
SF = new Font ("Arial",Font.BOLD,24);
SFM = f.getFontMetrics(SF);
SWA wa = new SWA();
wa.Dx = true;
wa.AM(f.getContentPane(),f);
JTextArea JTA;
JScrollPane J;
JTA = wa.CTA(JT);
J = wa.CSP(JTA,275,100);
wa.addTextArea(J,-11);
f.setVisible(true);
f.repaint();
} // end of main
} //end of program (class)
39. import java.util.*;
import java.awt.geom.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
public class T1T{
/**
* A simple debugging class I have been using for years.
* I put a shortened version, so
* this program is self-contained.
*/
static class Debug {
/**
* This is the debugging file; normally, one puts stuff in it
* with {@link P(String} or {@link P(String,booolean)}; but, one
* can write directly to it, if convenient.
*/
public PrintWriter D;
/**
* Create/open debugging file, {@link D}.
*/
Debug (){
try {
D = new PrintWriter (new FileOutputStream("T1T.out"));
}
catch (IOException e) {
System.out.println ("cannot open debug file");
}
}
/**
* output string to debugging file, with a new line.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s) {
D.println (s);D.flush();
}
/**
* output string to debugging file, with a new line only if {@code b}
* is true.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s,boolean b) {
if (b) {D.println (s);}else { D.print(s);}D.flush();
}
40. /**
* Simply, get Hash code and then call {@code toString()} on the
{@code Object} but shorten
* overlong results -- also it protects from Null Exception if object
is
* null.
* @param O - that which is to be output to debugging file
* @returns {@code String} which will usually be sent to {@code P}.
*/
public String SS (Object O) {
if (O != null) {
String RT = O.hashCode()+": "+O.toString();
if (RT.length() > 57) {
return RT.substring(0,57);
}
else {
return RT;
}
}
else {
return "null";
}
} // end of SS method
} // end of Debug class
static JFrame [] f;
/**
* number of frames on which we will test
*/
static int NOF = 3;
static Debug Debug;
/**
* We will use this font throughout this example.
*/
static Font []SF;
/**
* The {@code FontMetrics} for the standard font {@link SF}
* being used for text areas.
*/
static FontMetrics [] SFM;
/**
* see the discussion in the companion files {@code T1} and {@code
T1.pptx}.
*/
static class SWA implements ComponentListener {
/**
* if on, then, we will write some stuff to the debugging file,using my
* {@code Debug} class.
*/
boolean Dx=false;
/**
41. * To Whom I belong. If this is a {@code JFrame} or {@code Frame}, we
will
* call {@code getInsets} to get the proper width and height without the
* "decorations". See the discussion at the beginning of the {@code AWT}
* class {@code Frame}. Otherwise, {@code F} will be empty and we will
* just have C set. If we are using a frame, the caller, wil have to get
* the component by calling {@code getContentPane()}.
*/
Frame F;
/**
* To Whom I belong. If ultimate is a {@code JFrame} or {@code Frame},
the
* caller will have to
* call {@code getContentPane()}.
* @see F
*/
Container MC;
/**
* This associates this with the frame or other thing containing the
* components being adjusted.
*/
public void AM (Container WTA, JFrame F) {
MC = WTA;
this.F=F;
F.addComponentListener(this);
}
/*
* This is the component that we are adjusting and displaying here
* A later version will do arrays of these things.
*/
Component mc;
/**
* In spite of its name, will take any {@code Component} and associate it
with the
* frame to which this {@code SWA} is attached.
* It is intended to be used by simply
* passing {@code frame.getContentPane()} for the one argument, {@code
JTA}.
* @see AddScrollPane
*/
void addTextArea (Component JTA){
this.mc = JTA;
if (MC!=null) {
MC.add(JTA);
}
if (Dx) {Debug.P(" returning from add Text Area, added component
"+Debug.SS(JTA)+ " TO " + Debug.SS(MC)+ " ",false);}
}
/**
* Take the indicated {@code Component} and put it in a {@code
JScrollPane}.
42. * Note, programmer is responsible
* for setting its location and actually adding it
* to the frame to be seen to the unit.
* Uses default size with which to show this for the user.
*/
JScrollPane CSP (Component JTA) {
return CSP ( JTA, 200,50);
}
/**
* Take the indicated {@code Component} {@code JTA} and put it on
* a {@code JScrollPane} on the associated {@link Frame}. Uses the
* indicated size. Except if the {@code JTA} is smaller than that size,
* we make the scrollbar fit the text. In other words, if the text is
shorter
* or narrower than the programmer expects, we use the width or height
that
* we actually need rather than what the programmer specified.
* Programmer is responsible for setting its location.
*/
JScrollPane CSP(Component JTA, int width, int height){
JScrollPane J;
J = new JScrollPane();
int Width = JTA.getWidth();
int Height = JTA.getHeight();
Insets I = J.getInsets();
if (Width < width){
width = Width;
}
if (Height < height) {
height = Height;
}
JViewport V;
if (Dx) {Debug.P( " returning scroll Pane "+Debug.SS(J) +
" new location ("+width+","+height+") ",false);
J.setSize(width,height);
mc = J;
return J;
}
/**
* Create a {@code JTextArea} from the {@code String WTD} , which
presumably
* has carriage returns separating the lines or rows in the {@code
TextArea}
* @param WTD stick this content in the return {@code TextArea}
* @returns a {@code TextArea} set with the appropriate number of rows
and columns as well as the width and height in pixels.
* <P>
* To better measure the text
* (see companion files {@code T0} and {@code T1} or {@code T0.pptx}
* or {@code T1.pptx}, we will add this, at least temporarily to the
* {@code Container} with which this is associated. That assume that
this was
43. * associated with one; we tell by seeing if {@code MC} is not {@code
null}.
*/
public JTextArea CTA ( String WTD, Font SF,FontMetrics SFM){
int NoRows;
NoRows = 0;
char c; int i; int W /* width */; // temps
int LastPos=0;
int maxLL = 0; // maximum length of a line based on the number of
characters
int maxLW = 0; // maximum length of a line based upon the font
// (in a unit like pixels)
int NumberChars;
JTextArea RT; // text area to be returned. (This is an abbreviation for
// Return This.
RT = new JTextArea();
RT.setFont(SF);
RT.setForeground(Color.black);
Graphics C;
if (MC !=null) {
MC.add(RT);
}
C = RT.getGraphics();
for (i=0 ; i < WTD.length();i++) {
c = WTD.charAt(i);
if (c== 'n') {
NoRows++;
NumberChars = i-LastPos;
if (NumberChars > maxLL) {
maxLL = NumberChars;
}
String L;
if (LastPos==0) {
L = WTD.substring(0,i);
}
else {
L = WTD.substring(LastPos+1,i);
}
C = RT.getGraphics();
Rectangle2D WR = SFM.getStringBounds(L,C);
W = (int)WR.getWidth();
if (W > maxLW) {
maxLW = W;
}
LastPos=i;
if (Dx) {
}
} // we have a new line, separating actual lines in the text area.
} // loop through all characters in the String to put in the text area.
int height = SFM.getHeight();
int H = NoRows*height; // height that we will make our JTextArea to be
RT.setSize(maxLW,H);
RT.setText(WTD);
44. return RT;
}
/**
* Put this text area (or other component) at the bottom center of the
frame
* {@link F} to whom I belong. <P>Later versions of this class will give
* more control over multiple components.
* This is called whenever {@link F} has an event associated with
* {@code ComponentListener} interface.
*/
private void Adjust (ComponentEvent e) {
int eid=e.getID();
if (eid == ComponentEvent.COMPONENT_RESIZED || eid ==
ComponentEvent.COMPONENT_SHOWN){
if (mc!=null){
Component c = e.getComponent();
if (Dx) {Debug.P (" Resizing the frame (or outer container) " +
Debug.SS(c),false);}
int MyHeight=c.getHeight();
int MyWidth = c.getWidth();
if (Dx) {Debug.P (" My Height " + MyHeight + " My Width " + MyWidth + "
",false);}
Insets I;
I = F.getInsets();
int height=mc.getHeight();
int width = mc.getWidth();
int ypos;
int room = MyHeight-I.top-I.bottom; // how much room there is in the
window;
if (Dx){Debug.P (" of component being adjusted , height "+ height + "
width "+ width + " vertical Room " + room + " I.top "+I.top + " I.bottom
"+I.bottom + " ",false);}
boolean flag=false;// if the component's size does not fit in the window,
// we set this true, so we change the size of the
// textbox to fit.
if (room>height){
ypos = MyHeight - height - I.top-I.bottom;
}
else {
ypos = I.top;
height = room;
flag=true;
}
if (Dx){Debug.P ( " room " + room + " height " + height + " ypos "
+ypos,false);}
MyWidth = MyWidth - I.left - I.right;
if (Dx){Debug. P (" new My Width (or horizontal room ) " + MyWidth + "
I.left "+I.left + " I.right "+I.right,false);}
int xpos;
if (width <MyWidth) {
xpos = I.left+MyWidth/2 - width /2;
}
else {
45. xpos = I.left;
width = MyWidth;
flag = true;
}
if (Dx){Debug.P(" new xpos " + xpos + " ypos " + ypos );}
mc.setLocation(xpos,ypos);
JScrollPane J=null;
try {
J = (JScrollPane) mc;
}
catch (ClassCastException cce) {
Debug.P (" class cast exception encountered on converting to JScrollPane
");
}
JViewport V;
V=null;
// if the text area is now smaller than the scroll bar space, we will
change it
// to be the scroll base space -- after allowing for the width of the
vertical
// scroll bar and the height of the horizontal scroll bar.
if (J!=null){
V = (JViewport)J.getViewport();
JScrollBar VSB = J.getVerticalScrollBar();
int VSBw=0;
if (VSB !=null) {
VSBw = VSB.getWidth();
}
JScrollBar HSB = J.getHorizontalScrollBar();
int HSBh = 0;
if (HSB !=null) {
HSBh = HSB.getHeight();
}
if (Dx){
Debug.P (" scroll bar width: "+width +
" height " + height + " vertical scroll bar "+Debug.SS (VSB) +
" horizontal scroll bar " + Debug.SS (HSB) +
" vertical scroll bar width "+VSBw + " horizontal scroll bar height " +
HSBh
+
"("+width+"+"+I.left+"+"+I.right+"+"+VSBw+","+
height+"+"+I.top+"+"+I.bottom+"+"+HSBh+") ",false);
}
int Cc = V.getComponentCount();
if (Cc == 1){
Component C = V.getComponent(0);
int H,W,h,w;
// if the text area is now smaller than the scroll space, we will change
it
// to be the scroll base space -- after allowing for the width of the
vertical
// scroll bar and the height of the horizontal scroll bar.
46. H = C.getHeight() ;
W = C.getWidth();
if (Dx){
Debug.P (" got the text area or whatever was inside the Component:
"+Debug.SS(C)+ " H is " + H + " W is "+ W + " ",false);
}
h= height - HSBh;
w = width - VSBw;
boolean Flag;
Flag = false;
if (Dx) {
Debug.P (" h is " + h + " w " + w + " ",false);
}
if (H < h) {
Flag = true;
h = H;
}
if (w > W) {
Flag = true;
w = W;
}
if (flag){
C.setSize(W+VSBw,H+HSBh);
if (Dx) {
Debug.P (" resetting size of text area to ("+w + ","+h + ")
",false);
}
}
} // C in getting component of the scroll pane finds exactly one
} // J in converting component to scroll pane NOT NULL
if (flag) { mc.setSize(width,height);}
} // there really is a component to adjust
} // this is one of the events for which we could move around the
component
} // end of Adjust method.
public void componentResized (ComponentEvent e) {
Adjust(e);
}
public void componentMoved (ComponentEvent e) {
Adjust(e);
}
public void componentHidden(ComponentEvent e){
Adjust(e);
}
public void componentShown (ComponentEvent e){
Adjust(e);
}
} // end of SWA class, this is the class, we are trying to demonstrate.
47. /**
* For testing, the string to be put in the {@code JTextArea} on the
screen.
*/
static String JT =
"ONE True --- ONE ONE ----- ONE True ----- ONE True ---- ONE
True"+'n'+
"TWO True --- TWO TWO ----- TWO True ----- TWO True ---- TWO
True"+'n'+
"THREE True --- THREE THREE ----- THREE True ----- THREE True
---- THREE True"+'n'+
"FOUR True --- FOUR FOUR ----- FOUR True ----- FOUR True ----
FOUR True";
static String ST = "ONnTWOnTHREE";
public static void main (String [] args) throws IOException {
Debug = new Debug();
f = new JFrame[NOF];
SFM = new FontMetrics[NOF];
SF = new Font[NOF];
SWA []wa;
wa = new SWA [NOF];
JTextArea[] JTA;
JTA = new JTextArea[NOF];
JScrollPane []J;
J = new JScrollPane[NOF];
int i;
for (i=0;i<NOF;i++) {
f[i] = new JFrame();
f[i].setSize(400,500);
f[i].setLayout(null);
SF[i] = new Font ("Arial",Font.BOLD,24);
SFM[i] = f[i].getFontMetrics(SF[i]);
wa[i] = new SWA();
wa[i].Dx = true;
wa[i].AM(f[i].getContentPane(),f[i]);
switch (i){
case 0:
JTA[i] = wa[i].CTA(JT,SF[i],SFM[i]);
J[i] = wa[i].CSP(JTA[i],75,100);
break;
case 1:
JTA[i] = wa[i].CTA(ST,SF[i],SFM[i]);
J[i] = wa[i].CSP(JTA[i],300,300);
break;
case 2:
JTA[i] = wa[i].CTA(ST,SF[i],SFM[i]);
J [i] = wa[i].CSP(JTA[i],500,300);
break;
default:
System.err.println (" should not be here , wrong case in switchn");
System.exit(-100);
48. }
Debug.P(" adding component " + Debug.SS(J[i]) + " to frame # "+i+ "
"+Debug.SS(f[i]) + " Scroll panel is "+Debug.SS(J[i])+ " Text Area is
"+Debug.SS(JTA[i])+ " ",false);
wa[i].addTextArea(J[i]);
Debug.P ("returned from wa addTextArea ");
f[i].setVisible(true);
f[i].repaint();
} // loop to do all (NOF) frames
} // end of main
} //end of program (class)
49. T2
In T2.java, I promised you that we would allow each instance of the SWA
class to manage several items or text areas. (Note, here we are still
only
supporting one outer window; that is, we only have one instance of SWA).
I have four parallel arrays:
mc - the text area or component within the outer frame
mcw - its width
mch - its height
position - (*)
Thus, assume we call AddTextArea three times. The last time, the
last time, we call it with a component or JScrollPane 789 with
a position of -11. (See T2T.java where we do call it such.)
Then mc[2] will point to JScrollPane 789. position[2] will be -11.
And mcw[2] and mch[2] will give the preferred width and height
for component 789. (The latter two values are copied from the
JTextArea or component being added in line 184 of T2T.java.
(*) Recall that in T1B.java, we introduced passing zero to have the item
centered horizontally, a positive number to be left justified or justified
against the left-hand margin, and a negative number to have it right-
justified
or given a position relative to the right-hand border of the outer frame.
The Adjust subroutine follows that in the T1 series--it just loops
through all the items in those four parallel arrays. Thus, you will
see height=mch[i] and width=mcw[i] and then height and width are used
in the remainder of Adjust, copied from the T1 series.
import java.util.*;
import java.awt.geom.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
public class T2{
/**
* A simple debugging class I have been using for years.
* I put a shortened version, so
* this program is self-contained.
*/
static class Debu {
/**
* This is the debugging file; normally, one puts stuff in it
* with {@link P(String} or {@link P(String,booolean)}; but, one
* can write directly to it, if convenient.
50. */
public PrintWriter D;
/**
* Create/open debugging file, {@link D}.
*/
Debu (){
try {
D = new PrintWriter (new FileOutputStream("T1.out"));
}
catch (IOException e) {
System.out.println ("cannot open debug file");
}
}
/**
* output string to debugging file, with a new line.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s) {
D.println (s);D.flush();
}
/**
* output string to debugging file, with a new line only if {@code b}
* is true.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s,boolean b) {
if (b) {D.println (s);}else { D.print(s);}D.flush();
}
/**
* Simply, get Hash code and then call {@code toString()} on the
{@code Object} but shorten
* overlong results -- also it protects from Null Exception if object
is
* null.
* @param O - that which is to be output to debugging file
* @returns {@code String} which will usually be sent to {@code P}.
*/
public String SS (Object O) {
if (O != null) {
String RT = O.hashCode()+": "+O.toString();
if (RT.length() > 57) {
return RT.substring(0,57);
}
else {
return RT;
}
}
else {
return "null";
}
51. } // end of SS method
} // end of Debug class
static JFrame f;
static Debu Debug;
/**
* We will use this font throughout this example.
*/
static Font SF;
/**
* The {@code FontMetrics} for the standard font {@link SF}
* being used for text areas.
*/
static FontMetrics SFM;
/**
* see the discussion in the companion files {@code T1} and {@code
T1.pptx}.
*/
static class SWA implements ComponentListener {
/**
* if on, then, we will write some stuff to the debugging file,using my
* {@code Debug} class.
*/
boolean Dx=false;
/**
* To Whom I belong. If this is a {@code JFrame} or {@code Frame}, we
will
* call {@code getInsets} to get the proper width and height without the
* "decorations". See the discussion at the beginning of the {@code AWT}
* class {@code Frame}. Otherwise, {@code F} will be empty and we will
* just have C set. If we are using a frame, the caller, will have to
get
* the component by calling {@code getContentPane()}.
*/
Frame F;
/**
* To Whom I belong. If it is a {@code JFrame} or {@code Frame}, the
* caller will have to:
* <BR>
* call {@code getContentPane()}.
* @see F
*/
Container MC;
/**
* This associates this with the frame or other thing containing the
* components being adjusted.
*/
public void AM (Container WTA, JFrame F) {
MC = WTA;
this.F=F;
52. F.addComponentListener(this);
}
/**
* This array contains the component that we are
* adjusting and displaying here .
*/
Component [] mc;
/**
* This tells how many components we have to which keep track.
* Note, there are parallel arrays {@link mc}, {@link mcw}, {@link
position},
* and {@link mch}
**/
int CC;
/**
* This is the preferred width of the component added, assuming there is
* enough room for it.
*/
int [] mcw;
/**
* This is the preferred height of the component added, assuming there is
* enough room for it.
*/
int [] mch;
/**
* position to put {@link mc} relative to the containing window (@link
MC}
* <UL><LI>
* If positive, will be the number of pixels of right of the left-hand
side
* of {@link MC}
* <LI>
* If negative, will give the number of pixels to the left of the right-
hand
* edge of the containing window (@link MC}. That is, the {@code
Component}
* will be kept with a certain right margin.
* <LI>
* If zero, will be centered like in {@code T1A.java}.
* </UL>
*/
int []position;
/**
* maximum number of components we allow
*/
final int MNC=1000;
SWA () {
mc = new Component[MNC];
mcw = new int[MNC];
mch = new int [MNC];
position = new int [ MNC];
}
/**
53. * In spite of its name, will take any {@code Component} and associate it
with the
* frame to which this {@code SWA} is attached.
* It is intended to be used by simply
* passing {@code frame.getContentPane()} for the one argument, {@code
JTA}.
* @see AddScrollPane
* @param JTA that which is to be added.
* @param position <UL><LI> position is positive, that is the number of
pixels from the lower=left <LI>position is negative, then this will give
the number of pixels from the right<LI>if position is zero, then it will
be centered</UL>--note, it is impossible to align this precisely with the
lower left hand corner. Simply have it one pixel just to the right of
that.
*/
void addTextArea (Component JTA,int position){
this.position[CC] = position;
this.mc[CC] = JTA;
this.mcw[CC] = JTA.getWidth();
this.mch[CC] = JTA.getHeight();
CC++;
if (MC!=null) {
MC.add(JTA);
}
}
/**
* In spite of its name, will take any {@code Component} and associate it
with the
* frame to which this {@code SWA} is attached.
* It is intended to be used by simply
* passing {@code frame.getContentPane()} for the one argument, {@code
JTA}.
* @see AddScrollPane
* @param JTA that which is to be added.
*/
void addTextArea(Component JTA) {
addTextArea(JTA,0);
}
/**
* Take the indicated {@code Component} and put it in a {@code
JScrollPane}.
* Note, programmer is responsible
* for setting its location and actually adding it
* to the frame to be seen to the unit.
* Uses default size with which to show this for the user.
*/
JScrollPane CSP (Component JTA) {
return CSP ( JTA, 200,50);
}
/**
* Take the indicated {@code Component} {@code JTA} and put it on
* a {@code JScrollPane} on the associated {@link Frame}. Uses the
* indicated size. Except if the {@code JTA} is smaller than that size,
54. * we make the scrollbar fit the text. In other words, if the text is
shorter
* or narrower than the programmer expects, we use the width or height
that
* we actually need rather than what the programmer specified.
* Programmer is responsible for setting its location.
*/
JScrollPane CSP(Component JTA, int width, int height){
JScrollPane J;
J = new JScrollPane();
int Width = JTA.getWidth();
int Height = JTA.getHeight();
if (Width < width){
width = Width;
}
if (Height < height) {
height = Height;
}
J.setSize(width,height);
JViewport V;
V = (JViewport)J.getViewport();
V.add(JTA);
return J;
}
/**
* Create a {@code JTextArea} from the {@code String WTD} , which
presumably
* has carriage returns separating the lines or rows in the {@code
TextArea}
* @param WTD stick this content in the return {@code TextArea}
* @returns a {@code TextArea} set with the appropriate number of rows
and columns as well as the width and height in pixels.
* <P>
* To better measure the text
* (see companion files {@code T0} and {@code T1} or {@code T0.pptx}
* or {@code T1.pptx}, we will add this, at least temporarily to the
* {@code Container} with which this is associated. That assume that
this was
* associated with one; we tell by seeing if {@code MC} is not {@code
null}.
*/
public JTextArea CTA ( String WTD){
int NoRows;
NoRows = 0;
char c; int i; int W /* width */; // temps
int LastPos=0;
int maxLL = 0; // maximum length of a line based on the number of
characters
int maxLW = 0; // maximum length of a line based upon the font
// (in a unit like pixels)
int NumberChars;
55. JTextArea RT; // text area to be returned. (This is an abbreviation for
// Return This.
RT = new JTextArea();
RT.setFont(SF);
RT.setForeground(Color.black);
Graphics C;
if (MC !=null) {
MC.add(RT);
}
C = RT.getGraphics();
for (i=0 ; i < WTD.length();i++) {
c = WTD.charAt(i);
if (c== 'n') {
NoRows++;
NumberChars = i-LastPos;
if (NumberChars > maxLL) {
maxLL = NumberChars;
}
String L;
if (LastPos==0) {
L = WTD.substring(0,i);
}
else {
L = WTD.substring(LastPos+1,i);
}
C = RT.getGraphics();
Rectangle2D WR = SFM.getStringBounds(L,C);
W = (int)WR.getWidth();
if (Dx) {
}
if (W > maxLW) {
maxLW = W;
}
LastPos=i;
if (Dx) {
}
} // we have a new line, separating actual lines in the text area.
} // loop through all characters in the String to put in the text area.
int height = SFM.getHeight();
int H = NoRows*height; // height that we will make our JTextArea to be
RT.setSize(maxLW,H);
RT.setText(WTD);
return RT;
}
/**
* Put this text area (or other component) at the bottom center of the
frame
* {@link F} to whom I belong. <P>Later versions of this class will give
* more control over multiple components.
* This is called whenever {@link F} has an event associated with
* {@code ComponentListener} interface.
*/
private void Adjust (ComponentEvent e) {
56. int eid=e.getID();
if (eid == ComponentEvent.COMPONENT_RESIZED || eid ==
ComponentEvent.COMPONENT_SHOWN){
Component w = e.getComponent();
int MyHeight=w.getHeight();
int MyWidth = w.getWidth();
Insets I;
I = F.getInsets();
int height;
int width;
int ypos;
int room = MyHeight-I.top-I.bottom; // how much room there is in the
window;
boolean []flag;
flag = new boolean[CC];
int i; // position within arrays mc,position,mch,mcw;
// tells which component is being adjusted
for ( i = 0; i < CC; i++) {
flag[i]=false;// if the component's size does not fit in the window,
// if we set this true, so we change the size of the
// textbox to fit.
height = mch[i];
width = mcw[i];
if (room>height){
ypos = MyHeight - height - I.top-I.bottom;
}
else {
ypos = I.top;
height = room;
flag[i]=true;
}
int myWidth; // my real width after subtracting any insets
myWidth = MyWidth - I.left - I.right;
int xpos;
if (width <MyWidth) {
xpos=0;
if (position[i] ==0){
xpos = I.left+MyWidth/2 - width /2;
}
else
if (position[i] > 0) {
xpos = I.left + position[i];
}
else
if (position[i]<0) {
xpos = -I.right + myWidth - width + position[i];
}
}
else {
xpos = I.left;
width = MyWidth;
flag[i] = true;
}
57. mc[i].setLocation(xpos,ypos);
if (flag[i]) { mc[i].setSize(width,height);}
} // for each component to adjust
} // this is one of the events for which we could move around the
component
} // end of Adjust method.
public void componentResized (ComponentEvent e) {
Adjust(e);
}
public void componentMoved (ComponentEvent e) {
Adjust(e);
}
public void componentHidden(ComponentEvent e){
Adjust(e);
}
public void componentShown (ComponentEvent e){
Adjust(e);
}
} // end of SWA class, this is the class, we are trying to demonstrate.
/**
* For testing, the string to be put in the {@code JTextArea} on the
screen.
*/
static String JT =
"ONE True --- ONE ONE ----- ONE True ----- ONE True ---- ONE
True"+'n'+
"TWO True --- TWO TWO ----- TWO True ----- TWO True ---- TWO
True"+'n'+
"THREE True --- THREE THREE ----- THREE True ----- THREE True
---- THREE True"+'n'+
"FOUR True --- FOUR FOUR ----- FOUR True ----- FOUR True ----
FOUR True";
public static void main (String [] args) throws IOException {
Debug = new Debu();
f = new JFrame();
f.setSize(400,500);
f.setLayout(null);
SF = new Font ("Arial",Font.BOLD,24);
SFM = f.getFontMetrics(SF);
SWA wa = new SWA();
wa.Dx = true;
wa.AM(f.getContentPane(),f);
JTextArea JTA;
JScrollPane J;
JTA = wa.CTA(JT);
J = wa.CSP(JTA,275,100);
wa.addTextArea(J,0);
f.setVisible(true);
f.repaint();
58. } // end of main
} //end of program (class)
import java.util.*;
import java.awt.geom.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
public class T2T{
/**
* A simple debugging class I have been using for years.
* I put a shortened version, so
* this program is self-contained.
*/
static class Debu {
/**
* This is the debugging file; normally, one puts stuff in it
* with {@link P(String} or {@link P(String,booolean)}; but, one
* can write directly to it, if convenient.
*/
public PrintWriter D;
/**
* Create/open debugging file, {@link D}.
*/
Debu (){
try {
D = new PrintWriter (new FileOutputStream("T1.out"));
}
catch (IOException e) {
System.out.println ("cannot open debug file");
}
}
/**
* output string to debugging file, with a new line.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s) {
D.println (s);D.flush();
59. }
/**
* output string to debugging file, with a new line only if {@code b}
* is true.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s,boolean b) {
if (b) {D.println (s);}else { D.print(s);}D.flush();
}
/**
* Simply, get Hash code and then call {@code toString()} on the
{@code Object} but shorten
* overlong results -- also it protects from Null Exception if object
is
* null.
* @param O - that which is to be output to debugging file
* @returns {@code String} which will usually be sent to {@code P}.
*/
public String SS (Object O) {
if (O != null) {
String RT = O.hashCode()+": "+O.toString();
if (RT.length() > 57) {
return RT.substring(0,57);
}
else {
return RT;
}
}
else {
return "null";
}
} // end of SS method
} // end of Debug class
static JFrame f;
static Debu Debug;
/**
* We will use this font throughout this example.
*/
static Font SF;
/**
* The {@code FontMetrics} for the standard font {@link SF}
* being used for text areas.
*/
static FontMetrics SFM;
/**
* see the discussion in the companion files {@code T1} and {@code
T1.pptx}.
*/
static class SWA implements ComponentListener {
60. /**
* if on, then, we will write some stuff to the debugging file,using my
* {@code Debug} class.
*/
boolean Dx=false;
/**
* To Whom I belong. If this is a {@code JFrame} or {@code Frame}, we
will
* call {@code getInsets} to get the proper width and height without the
* "decorations". See the discussion at the beginning of the {@code AWT}
* class {@code Frame}. Otherwise, {@code F} will be empty and we will
* just have C set. If we are using a frame, the caller, will have to
get
* the component by calling {@code getContentPane()}.
*/
Frame F;
/**
* To Whom I belong. If it is a {@code JFrame} or {@code Frame}, the
* caller will have to:
* <BR>
* call {@code getContentPane()}.
* @see F
*/
Container MC;
/**
* This associates this with the frame or other thing containing the
* components being adjusted.
*/
public void AM (Container WTA, JFrame F) {
MC = WTA;
this.F=F;
F.addComponentListener(this);
}
/**
* This array contains the component that we are
* adjusting and displaying here .
*/
Component [] mc;
/**
* This tells how many components we have to which keep track.
* Note, there are parallel arrays {@link mc}, {@link mcw}, {@link
position},
* and {@link mch}
**/
int CC;
/**
* This is the preferred width of the component added, assuming there is
* enough room for it.
*/
int [] mcw;
/**
61. * This is the preferred height of the component added, assuming there is
* enough room for it.
*/
int [] mch;
/**
* position to put {@link mc} relative to the containing window (@link
MC}
* <UL><LI>
* If positive, will be the number of pixels of right of the left-hand
side
* of {@link MC}
* <LI>
* If negative, will give the number of pixels to the left of the right-
hand
* edge of the containing window (@link MC}. That is, the {@code
Component}
* will be kept with a certain right margin.
* <LI>
* If zero, will be centered like in {@code T1A.java}.
* </UL>
*/
int []position;
/**
* maximum number of components we allow
*/
final int MNC=1000;
SWA () {
mc = new Component[MNC];
mcw = new int[MNC];
mch = new int [MNC];
position = new int [ MNC];
}
/**
* In spite of its name, will take any {@code Component} and associate it
with the
* frame to which this {@code SWA} is attached.
* It is intended to be used by simply
* passing {@code frame.getContentPane()} for the one argument, {@code
JTA}.
* @see AddScrollPane
* @param JTA that which is to be added.
* @param position <UL><LI> position is positive, that is the number of
pixels from the lower=left <LI>position is negative, then this will give
the number of pixels from the right<LI>if position is zero, then it will
be centered</UL>--note, it is impossible to align this precisely with the
lower left hand corner. Simply have it one pixel just to the right of
that.
*/
void addTextArea (Component JTA,int position){
this.position[CC] = position;
this.mc[CC] = JTA;
this.mcw[CC] = JTA.getWidth();
this.mch[CC] = JTA.getHeight();
CC++;
62. if (MC!=null) {
MC.add(JTA);
}
}
/**
* In spite of its name, will take any {@code Component} and associate it
with the
* frame to which this {@code SWA} is attached.
* It is intended to be used by simply
* passing {@code frame.getContentPane()} for the one argument, {@code
JTA}.
* @see AddScrollPane
* @param JTA that which is to be added.
*/
void addTextArea(Component JTA) {
addTextArea(JTA,0);
}
/**
* Take the indicated {@code Component} and put it in a {@code
JScrollPane}.
* Note, programmer is responsible
* for setting its location and actually adding it
* to the frame to be seen to the unit.
* Uses default size with which to show this for the user.
*/
JScrollPane CSP (Component JTA) {
return CSP ( JTA, 200,50);
}
/**
* Take the indicated {@code Component} {@code JTA} and put it on
* a {@code JScrollPane} on the associated {@link Frame}. Uses the
* indicated size. Except if the {@code JTA} is smaller than that size,
* we make the scrollbar fit the text. In other words, if the text is
shorter
* or narrower than the programmer expects, we use the width or height
that
* we actually need rather than what the programmer specified.
* Programmer is responsible for setting its location.
*/
JScrollPane CSP(Component JTA, int width, int height){
JScrollPane J;
J = new JScrollPane();
int Width = JTA.getWidth();
int Height = JTA.getHeight();
if (Width < width){
width = Width+31;
}
if (Height < height) {
height = Height;
}
J.setSize(width,height);
JViewport V;
63. V = (JViewport)J.getViewport();
V.add(JTA);
return J;
}
/**
* Create a {@code JTextArea} from the {@code String WTD} , which
presumably
* has carriage returns separating the lines or rows in the {@code
TextArea}
* @param WTD stick this content in the return {@code TextArea}
* @returns a {@code TextArea} set with the appropriate number of rows
and columns as well as the width and height in pixels.
* <P>
* To better measure the text
* (see companion files {@code T0} and {@code T1} or {@code T0.pptx}
* or {@code T1.pptx}, we will add this, at least temporarily to the
* {@code Container} with which this is associated. That assume that
this was
* associated with one; we tell by seeing if {@code MC} is not {@code
null}.
*/
public JTextArea CTA ( String WTD){
int NoRows;
NoRows = 0;
char c; int i; int W /* width */; // temps
int LastPos=0;
int maxLL = 0; // maximum length of a line based on the number of
characters
int maxLW = 0; // maximum length of a line based upon the font
// (in a unit like pixels)
int NumberChars;
JTextArea RT; // text area to be returned. (This is an abbreviation for
// Return This.
RT = new JTextArea();
RT.setFont(SF);
RT.setForeground(Color.black);
Graphics C;
if (MC !=null) {
MC.add(RT);
}
C = RT.getGraphics();
for (i=0 ; i < WTD.length();i++) {
c = WTD.charAt(i);
if (c== 'n') {
NoRows++;
NumberChars = i-LastPos;
if (NumberChars > maxLL) {
maxLL = NumberChars;
}
String L;
if (LastPos==0) {
L = WTD.substring(0,i);
64. }
else {
L = WTD.substring(LastPos+1,i);
}
C = RT.getGraphics();
Rectangle2D WR = SFM.getStringBounds(L,C);
W = (int)WR.getWidth();
if (Dx) {
}
if (W > maxLW) {
maxLW = W;
}
LastPos=i;
if (Dx) {
}
} // we have a new line, separating actual lines in the text area.
} // loop through all characters in the String to put in the text area.
int height = SFM.getHeight();
int H = NoRows*height; // height that we will make our JTextArea to be
RT.setSize(maxLW,H);
RT.setText(WTD);
return RT;
}
/**
* Put this text area (or other component) at the bottom center of the
frame
* {@link F} to whom I belong. <P>Later versions of this class will give
* more control over multiple components.
* This is called whenever {@link F} has an event associated with
* {@code ComponentListener} interface.
*/
private void Adjust (ComponentEvent e) {
int eid=e.getID();
if (eid == ComponentEvent.COMPONENT_RESIZED || eid ==
ComponentEvent.COMPONENT_SHOWN){
Component w = e.getComponent();
int MyHeight=w.getHeight();
int MyWidth = w.getWidth();
Insets I;
I = F.getInsets();
int height;
int width;
int ypos;
int room = MyHeight-I.top-I.bottom; // how much room there is in the
window;
boolean []flag;
flag = new boolean[CC];
int i; // position within arrays mc,position,mch,mcw;
// tells which component is being adjusted
for ( i = 0; i < CC; i++) {
flag[i]=false;// if the component's size does not fit in the window,
// if we set this true, so we change the size of the
// textbox to fit.
65. height = mch[i];
width = mcw[i];
if (room>height){
ypos = MyHeight - height - I.top-I.bottom;
}
else {
ypos = I.top;
height = room;
flag[i]=true;
}
int myWidth; // my real width after subtracting any insets
myWidth = MyWidth - I.left - I.right;
int xpos;
if (width <MyWidth) {
xpos=0;
if (position[i] ==0){
xpos = I.left+MyWidth/2 - width /2;
}
else
if (position[i] > 0) {
xpos = I.left + position[i];
}
else
if (position[i]<0) {
xpos = -I.right + myWidth - width + position[i];
}
}
else {
xpos = I.left;
width = MyWidth;
flag[i] = true;
}
mc[i].setLocation(xpos,ypos);
if (flag[i]) { mc[i].setSize(width,height);}
} // for each component to adjust
} // this is one of the events for which we could move around the
component
} // end of Adjust method.
public void componentResized (ComponentEvent e) {
Adjust(e);
}
public void componentMoved (ComponentEvent e) {
Adjust(e);
}
public void componentHidden(ComponentEvent e){
Adjust(e);
}
public void componentShown (ComponentEvent e){
Adjust(e);
}
} // end of SWA class, this is the class, we are trying to demonstrate.
66. /**
* For testing, the string to be put in the {@code JTextArea} on the
screen.
*/
static String FT =
"ONE True --- ONE ONE ----- ONE True ----- ONE True ---- ONE
True"+'n'+
"TWO True --- TWO TWO ----- TWO True ----- TWO True ---- TWO
True"+'n'+
"THREE True --- THREE THREE ----- THREE True ----- THREE True
---- THREE True"+'n'+
"FOUR True --- FOUR FOUR ----- FOUR True ----- FOUR True ----
FOUR True";
static String ST =
"FIVE True n"+
"SIX True n"+
"SEVEN Truen"+
"EIGHT True";
public static void main (String [] args) throws IOException {
Debug = new Debu();
f = new JFrame();
f.setSize(400,500);
f.setLayout(null);
SF = new Font ("Arial",Font.BOLD,24);
SFM = f.getFontMetrics(SF);
SWA wa = new SWA();
wa.Dx = true;
wa.AM(f.getContentPane(),f);
JTextArea JTA;
JScrollPane J;
JTA = wa.CTA(FT);
J = wa.CSP(JTA,275,100);
wa.addTextArea(J,0);
JTA = wa.CTA(ST);
J = wa.CSP(JTA,275,300);
wa.addTextArea(J,-11);
f.setVisible(true);
f.repaint();
} // end of main
} //end of program (class)
67. T3
We now truly support having one SWA instance for each frame. We
demonstrate
having an array of Frames to show how this works.
Also SWA will stack
up the controls when there is not enough room at the bottom of the screen
for all of them.
(As we did in the T2 series, SWA has arrays to track all the controls
added. Each control is entered in the mc array, along with its
corresponding
desired size in mcw and mcw, w ith its desired position relative to the
left margin in position.)
But here, SWA.Adjust implements the following pseudocode:
for each control (i)
try to place it based upon the position[i] specified when we added it
to the frame with SWA.AddTextArea
for each control previously placed (for j from 0 to i-1)
see if the new control (i) conflicts with it.
if so, find out how far up we have to move it so it doesn't overlap
with any control.
move it there
T3A.java, T3T.java and T3AF.java exercises multiple SWA instances, one
for each Frame or JFrame in the application program.
I will focus on T3A.java and T3AF.java; these create an array of frames;
A doubly-nested loop generates a set of text boxes on each frame.
In T3AF, each frame uses a different font name and each
text box on that frame is in a different sizes (12, 16, 24 and 32).
(As I discussed in T0, one needs to get a FontMetrics for the font
and frame that we are using. Thus, I modified CTA method
calling sequence slightly--one passes the font that one is using along
with the string. It sets the font for
and gets the FontMetrics from the JTextArea that it creates.)
import java.util.*;
import java.awt.geom.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
public class T3{
/**
* A simple debugging class I have been using for years.
68. * I put a shortened version, so
* this program is self-contained.
*/
static class Debu {
/**
* This is the debugging file; normally, one puts stuff in it
* with {@link P(String} or {@link P(String,booolean)}; but, one
* can write directly to it, if convenient.
*/
public PrintWriter D;
/**
* Create/open debugging file, {@link D}.
*/
Debu (){
try {
D = new PrintWriter (new FileOutputStream("T3.out"));
}
catch (IOException e) {
System.out.println ("cannot open debug file");
}
}
/**
* output string to debugging file, with a new line.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s) {
D.println (s);D.flush();
}
/**
* output string to debugging file, with a new line only if {@code b}
* is true.
* <BR>
* Flushes output,
* just in case program crashes afterward.
*/
public void P(String s,boolean b) {
if (b) {D.println (s);}else { D.print(s);}D.flush();
}
/**
* Simply, get Hash code and then call {@code toString()} on the
{@code Object} but shorten
* overlong results -- also it protects from Null Exception if object
is
* null.
* @param O - that which is to be output to debugging file
* @returns {@code String} which will usually be sent to {@code P}.
*/
public String SS (Object O) {
if (O != null) {
String RT = O.hashCode()+": "+O.toString();
if (RT.length() > 57) {
return RT.substring(0,57);
69. }
else {
return RT;
}
}
else {
return "null";
}
} // end of SS method
} // end of Debug class
static JFrame f;
static Debu Debug;
/**
* We will use this font throughout this example.
*/
static Font SF;
/**
* The {@code FontMetrics} for the standard font {@link SF}
* being used for text areas.
*/
static FontMetrics SFM;
/**
* see the discussion in the companion files {@code T1} and {@code
T1.pptx}.
*/
static class SWA implements ComponentListener {
/**
* if on, then, we will write some stuff to the debugging file,using my
* {@code Debug} class.
*/
boolean Dx=false;
/**
* To Whom I belong. If this is a {@code JFrame} or {@code Frame}, we
will
* call {@code getInsets} to get the proper width and height without the
* "decorations". See the discussion at the beginning of the {@code AWT}
* class {@code Frame}. Otherwise, {@code F} will be empty and we will
* just have C set. If we are using a frame, the caller, will have to
get
* the component by calling {@code getContentPane()}.
*/
Frame F;
/**
* To Whom I belong. If it is a {@code JFrame} or {@code Frame}, the
* caller will have to:
* <BR>
* call {@code getContentPane()}.
* @see F
*/
Container MC;
70. /**
* This associates this with the frame or other thing containing the
* components being adjusted.
*/
public void AM (Container WTA, JFrame F) {
MC = WTA;
this.F=F;
F.addComponentListener(this);
}
/**
* This array contains the component that we are
* adjusting and displaying here .
*/
Component [] mc;
/**
* This tells how many components we have to which keep track.
* Note, there are parallel arrays {@link mc}, {@link mcw}, {@link
position},
* and {@link mch}
**/
int CC;
/**
* This is the preferred width of the component added, assuming there is
* enough room for it.
*/
int [] mcw;
/**
* This is the preferred height of the component added, assuming there is
* enough room for it.
*/
int [] mch;
/**
* position to put {@link mc} relative to the containing window (@link
MC}
* <UL><LI>
* If positive, will be the number of pixels of right of the left-hand
side
* of {@link MC}
* <LI>
* If negative, will give the number of pixels to the left of the right-
hand
* edge of the containing window (@link MC}. That is, the {@code
Component}
* will be kept with a certain right margin.
* <LI>
* If zero, will be centered like in {@code T1A.java}.
* </UL>
*/
int []position;
/**
* maximum number of components we allow
*/
71. final int MNC=1000;
SWA () {
mc = new Component[MNC];
mcw = new int[MNC];
mch = new int [MNC];
position = new int [ MNC];
}
/**
* In spite of its name, will take any {@code Component} and associate it
with the
* frame to which this {@code SWA} is attached.
* It is intended to be used by simply
* passing {@code frame.getContentPane()} for the one argument, {@code
JTA}.
* @see AddScrollPane
* @param JTA that which is to be added.
* @param position <UL><LI> position is positive, that is the number of
pixels from the lower=left <LI>position is negative, then this will give
the number of pixels from the right<LI>if position is zero, then it will
be centered</UL>--note, it is impossible to align this precisely with the
lower left hand corner. Simply have it one pixel just to the right of
that.
*/
void addTextArea (Component JTA,int position){
this.position[CC] = position;
this.mc[CC] = JTA;
this.mcw[CC] = JTA.getWidth();
this.mch[CC] = JTA.getHeight();
CC++;
if (MC!=null) {
MC.add(JTA);
}
}
/**
* In spite of its name, will take any {@code Component} and associate it
with the
* frame to which this {@code SWA} is attached.
* It is intended to be used by simply
* passing {@code frame.getContentPane()} for the one argument, {@code
JTA}.
* @see AddScrollPane
* @param JTA that which is to be added.
*/
void addTextArea(Component JTA) {
addTextArea(JTA,0);
}
/**
* Take the indicated {@code Component} and put it in a {@code
JScrollPane}.
* Note, programmer is responsible
* for setting its location and actually adding it
* to the frame to be seen to the unit.
* Uses default size with which to show this for the user.