Bluej Figures Example Download

61 views
Skip to first unread message

Suk Maddix

unread,
Jan 24, 2024, 5:58:09 AM1/24/24
to luolighbooksden

To customize initial column widths, you can invoke setPreferredWidth on each of your table's columns. This sets both the preferred widths of the columns and their approximate relative widths. For example, adding the following code to SimpleTableDemo makes its third column bigger than the other columns:

bluej figures example download


Download File https://t.co/kqEOrgAxBZ



As the preceding code shows, each column in a table is represented by a TableColumn object. TableColumn supplies getter and setter methods for the minimum, preferred, and maximum widths of a column, as well as a method for getting the current width. For an example of setting cell widths based on an approximation of the space needed to draw the cells' contents, see the initColumnSizes method in TableRenderDemo.java.

A table model can have a set of listeners that are notified whenever the table data changes. Listeners are instances of TableModelListener. In the following example code, SimpleTableDemo is extended to include such a listener. New code is in bold.

For example, each cell in the # of Years column in TableDemo contains Number data — specifically, an Integer object. By default, the cell renderer for a Number-containing column uses a single JLabel instance to draw the appropriate numbers, right-aligned, on the column's cells. If the user begins editing one of the cells, the default cell editor uses a right-aligned JTextField to control the cell editing.

It is easy to customize the text or image rendered by the default renderer, DefaultTableCellRenderer. You just create a subclass and implement the setValue method so that it invokes setText or setIcon with the appropriate string or image. For example, here is how the default date renderer is implemented:

To specify a cell-specific renderer, you need to define a JTable subclass that overrides the getCellRenderer method. For example, the following code makes the first cell in the first column of the table use a custom renderer:

The code is fairly straightforward, except perhaps for the call to convertColumnIndexToModel. That call is necessary because if the user moves the columns around, the view's index for the column will not match the model's index for the column. For example, the user might drag the Vegetarian column (which the model considers to be at index 4) so it is displayed as the first column — at view index 0. Since prepareRenderer provides the view index, you need to translate the view index to a model index so you can be sure the intended column has been selected.

TableRowSorter uses java.util.Comparator objects to sort its rows. A class that implements this interface must provide a method called compare that defines how any two objects are compared for the purpose of sorting. For example, the following code creates a Comparator that sorts a set of strings by the last word in each string:

This example is fairly simplistic; more typically, a Comparator implementation is a subclass of java.text.Collator. You can define your own subclass, use the factory methods in Collator to obtain a Comparator for a specific locale, or use java.text.RuleBasedCollator.

To specify the sort order and sort precedence for columns, invoke setSortKeys. Here is an example that sorts the table used in the examples by the first two columns. The precedence of the columns in the sort is indicated by the order of the sort keys in the sort key list. In this case, the second column has the first sort key, so they rows are sorted by first name, then last name.

In addition to reordering the results, a table sorter can also specify which rows will be displayed. This is known as filtering. TableRowSorter implements filtering using javax.swing.RowFilter objects. RowFilter implements several factory methods that create common kinds of filters. For example, regexFilter returns a RowFilter that filters based on a regular expression.

In a subsequent example, newFilter() is invoked every time the text field changes. When the user enters complicated regular expressions, the try...catch prevents the syntax exception from interfering with input.

The following example brings together the ideas discussed in this section. TableFilterDemo.java adds a small number of changes to TableDemo. These include the code snippets earlier in this section, which provide a sorter for the main table, and use a text field to supply the filtering regular expression. The following screen shot shows TableFilterDemo before any sorting or filtering has been done. Notice that row 3 in the model is still the same as row 3 in the view:

The automatic checking of user-entered strings occurs when the default editor attempts to create a new instance of the class associated with the cell's column. The default editor creates this instance using a constructor that takes a String as an argument. For example, in a column whose cells have type Integer, when the user types in "123" the default editor creates the corresponding Integer using code equivalent to new Integer("123"). If the constructor throws an exception, the cell's outline turns red and refuses to let focus move out of the cell. If you implement a class used as a column data type, you can use the default editor if your class supplies a constructor that takes a single argument of type String.

Invoking print on a normal Swing application brings up a standard printing dialog box. (On a headless application, the table is simply printed.) The return value indicates whether the user went ahead with the print job or cancelled it. JTable.print can throw java.awt.print.PrinterException, which is a checked exception; that's why the above example uses a try ... catch.

For example, you could try and see what Double.parseDouble(String s) returns for you. It should throw a NumberFormatException if it does not find an appropriate value in the string. I would suggest this technique because you could actually make use of the value represented by the String as a numeric type.

Adding two numbers together is easy to do, but adding a range of numbers is morecomplicated. In the following example, recursion is used to add a range of numberstogether by breaking it down into the simple task of adding two numbers:

Just as loops can run into the problem of infinite looping, recursive functions can run intothe problem of infinite recursion. Infinite recursion is when the function never stops callingitself. Every recursive function should have a halting condition, which is the conditionwhere the function stops calling itself. In the previous example, the halting condition iswhen the parameter k becomes 0.

It is helpful to see a variety of different examples to better understand the concept. In thisexample, the function adds a range of numbers between a start and an end. The haltingcondition for this recursive function is when end is not greater than start:

This is one example of why it is a bad idea to explicitly spell out the else when you have a set of conditions. The more important reason being that your if will often contain something much more complex and you might not negate it properly.

I'm writing a program that deals with planets' mass and diameter; These quantities are expressed in scientific notation. My question is NOT, mind you, NOT how does one print large numbers the right way (That's using printf(), duh), its how I would... "type" these numbers, I guess you could say. For example, the mass of mercury is expressed:

In a GUI program, a component must be kept (or added) in a container. You need to identify a container to hold the components. Every container has a method called add(Component c). A container (say aContainer) can invoke aContainer.add(aComponent) to add aComponent into itself. For example,

To exit this program, you have to close the CMD-shell (or press "control-c" on the CMD console); or push the "red" close button in Eclipse's Application Console. This is because we have yet to write the handler for the Frame's close button. We shall do that in the later example.

It is interesting to inspect the GUI objects via the toString(), to gain an insight to these classes. (Alternatively, use a graphic debugger in Eclipse/NetBeans or study the JDK source code.) For example, if we insert the following code before and after the setvisible():

In this example, the top-level container is again the typical java.awt.Frame. It contains 4 components: a Label "Enter an Integer", a TextField for accepting user input, another Label "The Accumulated Sum is", and another non-editable TextField for displaying the sum. The components are arranged in GridLayout of 2 rows 2 columns.

In the above examples, the method actionPerformed() is known as a callback method. In other words, you never invoke actionPerformed() in your codes explicitly. The actionPerformed() is called back by the graphics subsystem under certain circumstances in response to certain user actions.

In some languages, you can directly attach a method (or function) to an event (such as mouse-click). For example, the following JavaScript code (called JSCounter.html) implement a counter similar to the AWTCounter, with a text label, text field and button:

In Java, we CANNOT attach a method to a source object directly, as method is not a first-class object in Java. For example, a Java method cannot accept methods as its arguments and it cannot return a method; you cannot assign a method to a variable, etc. (JavaScript and C language CAN!).

How the source and listener understand each other? The answer is via an agreed-upon interface. For example, if a source is capable of firing an event called XxxEvent (e.g., ActionEvent). Firstly, we need to declare an interface called XxxListener (e.g., ActionListener) containing the names of the handler methods (recall that an interface contains only abstract methods without implementation). For example, the ActionListener interface is declared as follows:

Secondly, all XxxEvent listeners must implement the XxxListener interface. That is, the listeners must provide their own implementations (i.e., programmed responses) to all the abstract methods declared in the XxxListener interface. In this way, the listener(s) can response to these events appropriately. For example,

f5d0e4f075
Reply all
Reply to author
Forward
0 new messages