System.Drawing vs java2d

I feel both server about the same purpose

Advertisements

memory leak in GUI event handlers – swing^c#

Here’s a common java swing memory leak as described on stack overflow — Essentially, because you register an object as a listener and forget to unregister, the notifier ends up holding onto the reference of the object, and leaks a bit of memory.

Same problem with c# events. [[effective c#]] refers to it as “runtime coupling despite compile-time loose coupling”. Recall an event
is a pseudo field in a class, and the fields’ type is a delegate, which is a list of 2-pointer constructs. First pointer usually points to a listener object. Imagine a bunch of large listener objects are added to the delegate’s inv list (registered for event), and one of them is no longer needed. You want its memory freed, but the event source object still holds a reference via the delegate instance. See [[effective c#]] item 23. One tip is to unregister in the listener’s Dispose()

I feel the dotnet event/delegate language construct has no exact java counterpart at the language level, but at runtime, swing event
paradigm == c# event paradigm. Fundamentally the same paradigm. Part of the paradigm is that the event source object holds a
collection of subscriber Objects. If the GUI stays up for 22 hours then the subscriber Objects are held “hostage” for that long, and
cannot be garbage collected.

swing box layout – hearsay

To overcome the first Box layout confusions, Let’s start with Y-axis layout – top-down insertion of JComponents.  (X-axis alignment would mean left-to-right insertion).

Each JComponent calls myComponent.setAlignmentX() in Y-axis layout. Note the X vs Y. They must be that way. This is a bit confusing. Here’s my explanation — Top-down insertion means inserting a new component underneath the last component, but if new component is tiny shall we push it to the left or to the right? The new component must specify “Put me to left” or “Put me to the right”.

setAlignmentX(Component.RIGHT_ALIGNMENT) actually uses a float constant == 1.0. In fact, all setAlignmentX/Y methods take a float input. 0.5 always means center. LEFT_ALIGNMENT (== 0.0) means “push me to far Left”.

(Now hold your breath — in X-axis layout, 0.0 means “push me to the top”. This confused the hell out of me initially.)

The above is the box layout behavior when all components in the layout share the Same alignment number (be it 0.5, 1.0 or whatever). The behavior is completely different when the alignment numbers are non-uniform.

Popular combinations —
— right-justified:
new BoxLayout(…, Y_AXIS);
everyJComp.setAlignmentX(1.0)

— centered:
new BoxLayout(…, Y_AXIS);
everyJComp.setAlignmentX(0.5)

never edit table model on non-EDT?

A Swing interviewer asked me

Q: Can a non-EDT thread ever writes to the underlying data-structure of a (table/tree/list) model? 
A: If it does, we are at risk. EDT could be reading it — uncoordinated and unexpected. EDT might see corrupted data. Classic reader/writer race scenario. Murphy’s Law — if it could happen it will.

(In theory, EDT can also update the data due to a message listener or a DB operation –writer/writer race, but) This one scenario alone is reason enough. All underlying data queried by EDT should Never be modified outside EDT.

In one real world live trading app though, some MOM listener threads do indeed update underlying data structure. When that happens, users are not allowed to trigger a refresh — we can disable some buttons. After the update, we send invokeLater(fireXXX()) to refresh the view.

You may want to lock-protect the underlying data, but then EDT might be blocked. Yet, this is widespread. Look at DefaultTableModel in which EDT does access the underlying Vector, which is lock-protected. If the Vector is large, growing it (perhaps 2 folds) can take log(N) time, and EDT would be blocked for that duration. However, in practice this latency is probably below 50ms and unnoticeable.

As a minimum requirement, ALL models need to be thread-safe. That often entails locking or CAS or copy-on-write.

Swing models normally do not use large data structures (since a screen can’t realistically show even 1000 rows). If it does, update should ideally be designed with a worker thread, to populate a replacement data structure, and then ask EDT to swap it in. Many non-ideal situations exist in practice, which calls for specific techniques and tactical solutions.

tabbing policy – swing

See http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html

The policy of a Swing application is determined by LayoutFocusTraversalPolicy. You can set a focus traversal policy on any Container by using the setFocusCycleRoot method.

Alternatively you can pass focus-traversal-policy-providers to the FocusTraversalPolicy() methods instead of focus cycle roots. 

Use the isFocusTraversalPolicyProvider() method to determine whether a Container is a focus-traversal-policy-provider. Use the setFocusTraversalPolicyProvider() method to set a container for providing focus traversal policy.

GUI (wpf/swing..) design is more OO

Background: “non-GUI” can mean anything — including but not limited to web, database-centric, MOM, workflow, number-crunching, data transfer/transformation gateway, market-data-driven … To avoid over-generalization and to provide some concrete focus, I’d say let’s look at telecom/business systems. This blog post is about my general observation that GUI systems are “more inherently” object-oriented.

But why bother? Well, if anyone is learning any OO design pattern, the best example is often found in GUI space. GUI architects use more OO design principles than in non-GUI. A serious GUI OO design should. If you want to improve on an OO design for a GUI app, or if you start from scratch, use OO design patterns liberally.

Here are my observations as to why GUI design is more inherently object-oriented —

#1) main characters — there are relatively few objects as Models, ViewModels, Views, timers, singleton collections… Mostly stateful, singleton domain entities. OO design pattern is most useful in such a context.
** transient objects —- In most non-GUI systems most objects are transient (as revealed by a profiler). In GUI, quite a few objects — not just the jcomponents, listeners and events — have well-defined life cycles from creation to destruction. Can you say the same about non-GUI apps? In non-GUI, there are rather few long-living domain objects.
** Domain objects —- (More than in non-GUI apps) majority of classes in a GUI system including the main characters and numerous non-visual objects map nicely into domain objects. This is a boon to OO designers, with profound consequences. OO analysis is more worthwhile, more natural and more justified.
** ownership – in GUI an object is often “owned” by another in a strict sense. Given the “main characters”, ownership is often well-defined.
** complex interaction – there’s more inter-object cooperation and interaction in GUI systems. In some methods, you easily identify some of the “main characters”.

– necessity —- In many non-GUI projects, sometimes you can make do without OO. OO is more necessary (and natural) to GUI projects. I think GUI developers often grow into serious OO designers.
– state — visual components (often singletons) are first-class objects in the purest sense. Each visual object needs a supporting cast of other objects such as the Model or ViewModel objects. They all have a large number of well-defined states (properties).
– modular —- OO is at its best if you need to divide up a big project into modules each for a different developer. Large GUI projects often have natural demarcations and well-defined modular interfaces. Non-GUI large OO projects have a few clear demarcations + many more unclear demarcations.
– Reusable component —- GUI system can use/create many reusable components. Plug-n-play.
** EJB were hyped as shrink-wrapped commercial components but I don’t think they are. GUI components are the best example of commercial reusable OO components.

– actors —- are more prevalent in GUI Entity-Relation design. GUI OO design includes a real “actor”, and long-living domain objects associated with the actors. Other OO designs seldom have one. Web site is a different story — the domain objects related to a “session” are often short-lived.
– asynchronous, message driven —- such systems are more amicable to OO modelling, partly because each sender/receive maintains its own state.
– Sequence diagram —- useful to event-driven GUI.
– STA —- A fundamental reason why GUI systems use “Single-Threaded Apartments” is the long-living domain objects. Need to protect their “consistency”
– Encapsulation —- (and Object State) Most important GUI objects have well-defined, often with standardized stateful fields. Not so in non-GUI.
– abstract interfaces —- many classes must support the same “interface”. We often need to treat the a bunch of Types the same way. This calls for interfaces.
– Inheritance
– Design patterns —- map nicely to GUI OO, more nicely than non-GUI OO. See http://bigblog.tanbin.com/2011/01/swing-1-primary-design-pattern.html for a list of design patterns in Swing

tabbing policy in swing, briefly

See http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html

The policy of a Swing application is determined by LayoutFocusTraversalPolicy. You can set a focus traversal policy on any Container by using the setFocusCycleRoot method.

Alternatively you can pass focus-traversal-policy-providers to the FocusTraversalPolicy() methods instead of focus cycle roots. Use the isFocusTraversalPolicyProvider() method to determine whether a Container is a focus-traversal-policy-provider. Use the setFocusTraversalPolicyProvider() method to set a container for providing focus traversal policy.

high volume low latency trading GUI techniques

thread pool??
heavy processing done in the background?
paging — table to speed up table updates
subset – each user selects a subset of the symbols
multiple sorted views of the same underlier data?
avoid fireTableDataChanged(). Favor the smaller fireXXX() methods
keyboard shortcuts
sorting — often needed by user, given the large data volume.
minimize hand movements

content of a typical AWTEvent object

* source (actually a pointer thereto)
* exact type of event — getID, not getClass(). Value could be mouseRelease, losingFocusDueToClick …
* timestamp

What about the most common events?

MouseEvent contains location information.

Table model event contains firstrow/lastrow, which column. The event also contains an enum field about what type of change — delete, insert etc

JTable (etc) how-to

http://www.java2s.com/Code/Java/Swing-JFC/Creatingamodalprogressdialog.htm – modal progress bar, as an alternative to a glass panel

AWT vs swing #my take

I believe each awt component (you manipulate in java classes) maps to one and only one native screen object — probably the
so-called peer object. Native screen object is tied to the display hardware and registered (created?) with the hardware
wrapper-layer known as the OS. It takes up memory (among other resources) on the display hardware.

A lightweight component in your java source code is simply Painted as a graphic on the ancestor’s screen object (which is tied to a
heavyweight ancestor), so it doesn’t occupy additional resources on the display hardware. It’s “light” on system resources.

Also, since it’s painted as a graphic by java, the appearance is controlled by java and consistent across platforms. In contrast,
the heavy weights look native and consistent with native apps like Powerpoint. There are pros and cons. Some praise the java
consistent look and feel. Some say swing looks alien on windows.

When I say the “native screen object” corresponding to a jtable, i mean the image painted on the (heavyweight) jframe. I believe
multiple lightweights on the same heavyweight all share the same native screen object i.e. the peer object.

when to use Action !! ActionListener

I struggled for years to understand the real reason to use Action rather than ActionListener, and finally found http://www.developer.com/java/other/article.php/1146531/Understanding-Action-Objects-in-Java.htm .

Truth — action is more sharable, though it's unclear how until you read the url.

Myth — Action instance holds icons, text, tooltip etc to be shared among jcomponents. In reality we often use Action without icons etc

Myth — Action is shared by jcomponents. In reality we also put Action instances into ActionMap, nothing to do with jcomponents.

Truth — the disable/enable feature is important — all “users” of the Action instance are enabled/disabled together — the most convincing justification.

ActionListener can also achieve sharing. It is straightforward to instantiate an ActionListener and register it on a menu item and a button. This will guarantee that action events will be handled in an identical way regardless of which jcomponent fires the event. However, such a shared action listener can't send property change notifications for enabling/disabling.

In contrast, when some object adds our Action instance, this object will be enabled/disabled upon property change notification from our Action.

left hand sending event to right hand – swingWorker

First, remember SW is stateful, and publish() and process() are non-static methods.

The publish() method posts a stream of events to the event Queue. Each event holds a hidden pointer to “this” i.e. the SW instance. EDT recovers the pointer and basically calls this.process().

Both publish() and process() are called on the same (stateful) SW instance, but on different threads. The 2 instance methods are like the left and right hands, designed to interact between themselves.

In SwingWroker, everything else is secondary — doInBackground(), done(),and type params — The 2 type params are interesting — T and V can be identical or T can be a collection of V.

T – the result type returned by doInBackgroun()
V – the type of intermediate results of publish() and process()

where (in your code) to run input validation

1) click-away, tab-away, or postActionEvent()

public boolean stopCellEditing() {// triggered even if text field content unchanged!

2) ENTER key hit during editing

ftf.getInputMap().put(KeyStroke.getKeyStroke(
KeyEvent.VK_ENTER, 0),
“check”); //VK_ENTER -> check -> actionInstance callback

ftf.getActionMap().put(“check”, actionInstance); // where actionInstance has the callback method running the validation

Here are the High-level Steps adding custom validation logic into a table cell editor
* You write a customized editor class to return on-demand a JFormattedTextField instead of the JTextField as the jcomponent
* in the JFormattedTextField object, you inject a formatter factory,
* the factory is initialized with a NumberFormatter
* the NumberFormatter is initialized with a NumberFormat (no “ter” suffix)
* you configure one of these format thingies to use your custom logic

http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#validtext has good coverage of user input validation using TCE

cell renderer to fit row height to content

int rowHeight = table.getRowHeight(); 
for (int aColumn = 0; aColumn < table.getColumnCount(); aColumn++) {
  Component comp = aColumn == column ? ret : table.prepareRenderer(table.getCellRenderer(row, aColumn), row, aColumn);
  rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
}
table.setRowHeight(row, rowHeight);

Inside getTableCellRendererComponent(), before returning, scan all cells on the current row to get the max height. Configure the current row to use that height.

How about column width? I feel there are too many rows to scan, but Yes I think it’s doable.

show a swing GUI at unblocked location

By default, your swing app pops up on top left corner, right behind your IDE – annoying. To make it show up somewhere unblocked, I often do

final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((int)(screenSize.width*1.1), screenSize.height/2);

This assumes I have another monitor on my right and puts swing an inch off my main monitor.

ActionListener^Action

javadoc on Action.java says

Note that Action implementations tend to be more expensive in terms of *storage* than a typical ActionListener implementation class, which does not offer the benefits of centralized control of functionality and *broadcast of property changes*. For this reason, you should take care to only use Actions where their benefits are desired, and use simple ActionListeners elsewhere.

I feel ActionListener objects are typically stateless. I feel they are pure functor objects. The word “Action” in “ActionListener” means very much like the generic “Event”. However, the word “Action” in Action.java seems to mean something else, such as the Control in Microsoft lingo.

Anyway, i feel the word “Action” is ambiguous and overloaded. Let’s avoid it but do understand its various meanings.

swing OMS screen (PWM), briefly

PWM screen, used till today (2012). Handles Eq, FX, FI, derivatives (esp. options), futures….

Real time OMS — “order state management”, including but not limited to
* real time status updates
* order entry
* manual trade booking

* manual order cancel/mod before fully executed

Web GUI won’t provide the responsiveness and volume —

At least 30,000 orders/day in US alone. 50-200 executions/order, executed in-house or on external liquidity venues. Typically 10 MOM messages per execution.
– new order placed
– acknowledged
– partial fill
– cancel/mod

Each swing JVM has its own MOM subscriber(s).

This codebase isn’t part of the IC build and has a frequent release cycle.

table cell render – per column, per row, per data type

Typically, you associate a table cell render (Instance, not class) on a column. (A column is a homogeneous data type.)

You can also associate a render object to a class (such as Account or Student).

It's less natural to associate a render to a row. You can, however, adapt the render behavior to a row, perhaps based on the row number, or any property of the actual “value” object

swing automated test, briefly

3) http://www.codework-solutions.com/testing-tools/qfs-test/ says …event is constructed and inserted artificially into the system’s EventQueue. To the SUT it is indistinguishable whether an event was triggered by an actual user or by QF-Test. These artificial events are more reliable than “hard” events that could be generated with the help of the AWT-Robot, for example, which could be used to actually move the mouse cursor across the screen. Such “hard” events can be intercepted by the operating system or other applications.

2) http://jemmy.java.net/Jemmy3UserTutorial.html and http://wiki.netbeans.org/Jemmy_Tutorial explain some fundamentals about component searching. Jemmy can simulate user input by mouse and keyboard operations.

1) java.awt.Robot is probably the most low-level — Using the class to generate input events differs from posting events to the AWT event queue —  the events are generated in the platform's native input queue. For example, Robot.mouseMove will actually move the mouse cursor instead of just generating mouse move events.

win32, MFC, WPF, winforms… vs Java/swing

Earliest/lowest support is win32api — a platform specific C [1] API. No counterpart in Java because JVM hides all platform-specific complexities, though the win32 JVM is written against win32api.

[1] C with Microsoft extensions, but not C++. I guess It’s a proprietary language based on ANSI-C.

win32api functions are like system calls AND standard library functions in unix. Plain old C functions, as low-level functions must be. All windows/unix applications rely on system API in C as not every app uses C++.

MFC is a c++ thin object wrapper over win32api functions, therefore platform-specific too. No counterpart in java. Borland used to offer a MFC competitor (viz OWL), but it also relies on win32api. So win32api is a choke-point, but MFC isn’t.

Similarly, winforms is also a wrapper over win32api (not over MFC). Unlike MFC, winforms was created for the dotnet virtual machine.

Someone on Stackoverflow said — Most application frameworks for Windows (at least partially) wrap the win32api. Thus, the .NET and JVM, likewise any other programming languages under Windows, are (or contain) wrapper libraries over win32api.

Winforms and WPF built on top of a virtual machine — the dotnet framework, and are (partially?) shielded from platform-specific complexities. I think these are like the swing library.

However, winforms is a dotnet wrapper over win32api, therefore faster than WPF.

———– gcc ————–
http://gcc.gnu.org/wiki/WindowsBuilding

GCC also goes through the choke point viz win32api. Mingw includes
* w32api (not spelt “win..”): This is a bunch of files, a free (compatible) implementation of the MS win32api, equivalent to the Windows SDK, which provides the system-level (OS level?) interface needed by mingw-runtime. It is possible, with some modifications, to use Microsoft’s Platform-SDK instead.

* mingw-runtime (version 3.12 or higher): This is a bunch of files, the equivalent of libc on Unix which provides an interface to Microsoft’s C runtime that is shipped with Windows.

——— how many ways to write an equivalent GUI app ——-
* write a C app against win32api direclty
* write a c++ app against MFC (wrapper over win32api) — no virtual machine at all
* write a c#/c++ winforms app, running in the virtual machine
* write a c# WPF app, running in the virtual machine
* write a mingw C/C++ app, against w32api — no virtual machine at all
* write a swing app, running in the JVM

However, if you want a windows app without a GUI, then you need a console app. You can use C++ without any of these complexities. Just use STL/boost. Windows programming != GUI programming.

challenges in your swing projects@@

Challenge: layout. If it can take a few hours to implement new biz logic it can take 2 days to get the layout exactly right. Dotnet solutions probably takes half a day only. Sub-panels take memory. WYSIWYG layout? WPF separates layout and code into separate physical files

Challenge: memory consumption is higher in swing than other GUI frameworks. Many times a swing app take up 900MB and will not be able to grow further.

Challenge: threading. Manageable unless messaging rate is very high.
Challenge? robust performance. App should remain fast and responsive in the face of various hazards — slow DB/network; memory leak; slow action listeners; ….
Challenge? bloated fields and method params
Challenge? memory leak due to listeners. Swing is a memory hog.
Challenge? EDT overloaded? 
Challenge? code duplication — a lot of similar callbacks
Challenge? a long and ever-growing class with lots of inner classes — including invokeLater() and callbacks

swing topics

table sort/filter – pre-1.5
table sort/filter -post-1.5
layout managers?
custom table cell renders / editors
grid,
tree table – jide docs
tree table – swingx
view factory
editor kits
custom table model
StyledDocument

large data volume, high message rate
design patterns
swing automated test — scripting
large system tests — maybe there’s nothing technical to worry about.
swingx, jide, jgoodies
— fx
timer
swing worker

Does this person have real experience or home projects only?
High-level design and communication — can he?
trouble-shooting, debugging experience. Common traps?
best practices?

invokeLater() – impossible to refactor@@

Q: if there's a block inside my method, we can wrap an invokeLater() around it — anon inner class. But is this always possible, assuming local vars are final.

What if a local var must be non-final, but this variable is in the target block? I feel we can create a “final” clone of this variable and use it in the target block.

What if a variable is modified in the target block? I feel we can create a mutable clone and make it a local-var, local to the invokeLater() (actually the run method).

What if a variable is modified in the target block but needed after the block? What if the target block has side effects on local variables?

What if the target block creates objects to be used after the block?

dual purpose of EDT – up/downward updates

A} I used to know EDT as the only thread to “put THINGS on screen”.

B} Now I feel EDT is the only thread to process all user inputs.

}}} In a nutshell, I feel EDT is the choke point for upward/downward updates to/from screen (+ keyboard + mouse)

— For Upward To screen
I guess it relies on paint() and lieutenants

— For Downward From screen,
Q: do user inputs always require 1) events and 2) listeners?
%%A: I think so. Well we know all events are in EDT Queue and all callbacks are invoked on EDT.

isShowing(), isDisplayable(), paint(), native visual object

There’s a link between a JComponent and its corresponding “native visual object” on screen.

1) http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Component.html#isDisplayable() mentions the native object

2) http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Component.html#isShowing() is among the most reliable indications of the link.

3) http://java.sun.com/products/jfc/tsc/articles/painting/ seems to hint that paint() is one of the lower-level methods connected to the mysterious native object. Low-level operations such as the screen rendering when

* a previously obscured portion of the component has become exposed. — we can debug this process
* a button determines that it needs to paint a “depressed” button visual.

4) http://bigblog.tanbin.com/2010/06/state-of-data-model-vs-state-of-visual.html describes the link.

Best online intro to swing Realization

http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Component.html#isDisplayable() says

Determines whether this component is displayable. A component is displayable when it is connected to a __native__ screen resource.

A component is made displayable either when it is added to a displayable containment hierarchy or when its containment hierarchy is made displayable. A containment hierarchy is made displayable when its ancestor window is either packed or made visible.

http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html is less precise
Realized means that the component’s paint() method has been or might be called. A Swing component that’s a top-level window is realized by having one of these methods invoked on it: setVisible(true), show(), or (this might surprise you) pack(). Once a window is realized, all components that it contains are realized. Another way to realize a component is to add it to a container that’s already realized. You’ll see examples of realizing components later.

–specfic example for some text component

public boolean isShowing() {
  return getTextComponent().isShowing();
}

This code determines if the object is Showing. This is determined by checking the visibility of the object and its ancestors. Note: this will return true even if the object is obscured by another (for example, it is underneath a menu that was pulled down).

public boolean isVisible(){
  return getTextComponent().isVisible();
}

This code determines if the object is Visible. Note: this means that the object intends to be visible; however, it may not be showing on the screen because one of the objects that this object is contained by is currently not visible. To determine if an object is showing on the screen, use isShowing().

EDT and non-EDT delegating to each other

This is a very common swing pattern, so better recognize it. Both techniques are often necessary rather than nice-to-have. Every swing developer needs to master them.

X) a regular thread often passes Runnable tasks to EDT via the event queue. See invokeAndWait() etc.

Y) EDT often passes slow tasks to helper threads so as to keep the GUI responsive. Tasks running on EDT should be quick. For road hogs, EDT can use a thread pool, or SwingWorker thread.

Q: data sharing? Race conditions?
A: I feel most swing apps are ok. The jcomponent objects are effectively singletons, accessible from multiple threads, but usually updated on EDT only.

table events and fire* methods

Q: is there any table event directly linked to the jtable object, without the table model object?
%%A: i doubt it.
Note all listeners are registered on the table model object, not the jtable object. P705[[def guide]]

Before studying the fire* methods of swing tables, better get familiar with the typical TableModelEvent constructors. A few examples

TableModelEvent(source); // all rows changed
TableModelEvent(source, HEADER_ROW); // Structure change, reallocate TableColumns
TableModelEvent(source, 3, 6); // Rows 3 to 6 inclusive changed
TableModelEvent(source, 2, 2, 6); // Cell at (2, 6) changed
TableModelEvent(source, 3, 6, ALL_COLUMNS, DELETE); // Rows (3, 6) were deleted

Now we are ready to compare the various fire* methods

fireTableChanged(TableModelEvent e) // is internal workhorse method used by other fire* methods
fireTableStructureChanged(void) // column (structural) change.
fireTableDataChanged(void) // no arg, so all rows changed. But no column (structural) change.
fireTableRowsUpdated/Inserted/Deleted(firstRow, lastRow)

I don’t see any fire* method about a single cell. I guess you can construct such an event and pass it to fireTableChanged(e)

swingWorker/Timer example

public class TimerSwingWorker extends SwingWorker {
final Timer newsTimer = new Timer(millisec2sleep, new ActionListener() {

public void actionPerformed(ActionEvent notUsed) {

StaticSwingUtil.assertIsEDT(); 

// each periodic timer event triggers EDT to instantiate and starts a new
// *scanner* worker, which runs only once.
// Worker will contact EDT.
new ScannerWorkerThread(jta, command2getUpdates, ” <- detected ").execute();

}

}); // newsTimer instantiated. Once started [see doInBackground()], newsTimer will fire periodic “news” events
// Note all timer instances share the same timer thread.
@Override
public Void doInBackground() {
StaticSwingUtil.assertNotEDT();
this.newsTimer.start(); // now our timer will start firing periodically

ComponentUI instantiation in jcompopnent ctor

Experts say every(?) swing component’s ctor calls this.updateUI(). I was told (verified in jtable and jtree) that each class’s updateUI() calls something like

setUI((TableUI)UIManager.getUI(this))
setUI((TreeUI)UIManager.getUI(this))

This static method getUI() is something like a global hashtable lookup. If you look at its implementation, this getUI() basically calls createUI() reflectively. I believe it almost always instantiates a new ComponentUI instance.

In conclusion, swing component’s ctor indirectly instantiates a new ComponentUI instance. Note UI delegate instantiation is NOT delayed to painting time.

real world high-volume mkt-data gui – tips

Suppose a given symbol (say EURUSD) bid/ask floods in at 1000 updates/sec (and last-executed at a fraction of that messaging rate). We need to display all of them in a table. We also need to update some statistics such as moving average, best bid/ask.

Suppose we don’t have the option to skip some quotes and periodically poll the data source [1].

I feel This is technically impossible. It’s important to identify unrealistic requirements.

I feel if a (institutional) client wants all the 1000 updates in rea time, she should get a “bank feed”, rather than rely on the GUI we build for them.

[1] A common technique to display a feed with more than 1 update/sec.

what swing components must a trading app use

Absolutely must —
* top-level container? Yes, mostly JFrame, as the other 2 top-level containers are less useful or popular
* content pane
* JComponent, the parent of most UI components
* layout manager is an absolute must, since every content pane needs a layout manager, unless you choose absolute positioning

There are non-UI objects that are absolute musts —
– invokeLater() etc. Without it swing might appear to be functional, but i don't feel safe.
* UI events and listeners

If you are expecting more, I'm afraid those are the only ones I know. But here are a few “unavoidables”
– jtable? row/column data. Why is Excel by far the most important and sophisticated among Office apps?
– text panes?
– jpanel? indispensable for grouping components

##classical engineering fields #swing?

At 60 a mechanical engineer can be productive. These finance IT fields are similar. High value, tech-heavy and finance-light ==> Portable(!), optimization/engineering/precision ==> Detail-Oriented.

Socket – C, Non-blocking IO
Mainframes
RV, MQ
Unix, syscalls, esp. kernel hacking – C
low latency – C
SQL tuning
DBA? new tools emerge
regex
memory management – C/C++ only. Other languages are “well-insulated”

— these aren’t
windowing toolkit like motif, swing, wpf ? churn rate!
threading — new tools make old techniques obsolete
MSVC

sort a jtable by any column you click

jdk 1.6 added TableRowSorter.java, but here are some alternative ideas, often relying on setModel()

I feel this is similar to making a “bag” of java beans sortable by each field. Once sorted, you can iterate over the beans and populate a new table model. The ctor taking 2D array, or the ctor taking a vector-of-vector will suffice.

One sort solution – pass the collection into a sorted map with any custom comparator. Does the map allow equal members? Need to make sure equals never returns true, but compare() can return 0.

One sort solution – Collections.sort() with a comparator. This can allow equals() to return true.

If there are 9 columns in jtable, then the bean has 9 fields. We need 9 custom comparator classes.

I feel in business apps it’s unlikely but What if there’s no bean class? Each rowData object would be a vector or array. I feel you can still use Collections.sort with a custom comparator. One basic solution creates 9 custom comparator instances for sorting by Column1, Column2… Column9. Comparator3 would use the 3rd cell of each rowData.

I feel in business apps it’s unlikely but What if the jtable columns are dynamic so the column count is unknown at compile time? Then I feel we can use a vector of comparator objects. Or perhaps we can instantiate each singleton comparator on demand. Comparator class would need an _immutable_ int field this.indexOfSorterCol, to be used in the compare() method.

single-threaded UI update – wpf vs swing

In a WPF app every visual “element” object has a “owning” thread. It can be modified only by the owning thread. This sounds like “every child has a mother”. Indeed WPF lets you have 2 owning threads if you have 2 unrelated window instances in one Process[3]. In practice, most developers avoid that unnecessary flexibility, and use a single owning thread — known as a dispatcher thread.

[3] each having a bunch of visuals.

In WPF, Anytime you update a Visual “element”, the work is sent through the Dispatcher to the UI thread. The control itself can only be touched by it’s owning thread. If you try to do anything with a control from another thread, you’ll get a runtime exception.

myCheckBox.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate(){myCheckBox.IsChecked = true;}
)
);

Very similar to invokeAndWait(new Runnable()…. There’s also a counterpart for invokeLater().

make a series of random colors – no 2 similar colors in a row

brightness — Colors should not be too light to read on a white background.

saturation — push to the max

private Color makeColor() {
float piePieces = 50;//how many pizza slices in a pie
for (;;) {
int tmpHue = this.rand.nextInt((int) piePieces + 1);
if (Math.abs(tmpHue - this.intHue) / piePieces > 0.11) {
// 0.5 means exact opposite color
this.intHue = tmpHue;
float hue = tmpHue / piePieces; // 0 to 1
return Color.getHSBColor(hue, 0.99999f, 0.77f);
}
}
}

swing (AWT?) write once run anywhere

Swing is indeed write-once-run-anywhere — anywhere JVM is available — like linux, Mac, and Solaris [1]. However, http://programmers.stackexchange.com/questions/47154/what-drawbacks-does-java-swing-gui-framework-have raised some interesting points —

Swing generalizes [2] your underlying architecture to provide you with a platform-neutral user experience. About the only heavyweight component (provided by the OS) is the JFrame container and the rest is pretty much handled by the Swing tookit. (I think JDialog is another heavyweight.)

In contrast, AWT asks the OS to draw all of it’s UI components which means it’s faster in a lot of ways as you are using the native UI components specific to the OS. SWT tries to achieve a middle ground.

The Swing look-and-feel isn’t particularly attractive as it looks alien to most OS platforms.

[1] I think some JVM implementations may not support windowing at all. Look at some early Java-powered phones.

[2] http://en.wikipedia.org/wiki/Abstract_Window_Toolkit

reoffer engine — basic questions you are expected to know

Q: why wpf and swing, rather than browser-based?
A: real time updates of every position
A: traders need to switch among the grids without reloading from server. We have a local cache. Separate jvm from swing, and data-binding for wpf.

Q: what if 2 updates come from different sources and both trigger repricing. How does the classic system schedule them?
A: some cache triggers are single-threaded, some are multi-threaded. There's an incrementing version number.

Q: why is PNL updated in real time? isn't EndOfDay enough?
A: nice to have.
A: We only persist EOD pnl data

Q: how does libor or other benchmarks affect pricing?
A: Some positions are priced with a spread on benchmarks

Q: how many traders?
A: about 120

Q: what do the middle office do with your app?
A: MSRB
A: faxp
A: they might look at PnL on our Swing app

Q: how many middle office people?
A: Fewer than traders

Q: what other users use our app?
A: Trading floor support
A: FA

Q: how does our system calculate or use credit risk data?
A: we don't calculate anything using credit risk data
A: each bond has its own yield curve. Typically a spread on Libor. If you are an AAA bond, then your curve might be Libor itself. If you are BBB, then Libor + some spread. The spread depends on your credit rating.

Q: I thought prop traders manage their reoffer pricing using their own algorithm
A: prices maybe
A: marks are sometimes calculated in ARB and fed into Autoreo. Then Autoreo uses those marks for reoffer pricing.

Q: how does our trader hedge?
A: swaps, swaptions, caps/floors, CDS, treasuries, futures, stocks,

Q: What if we send out a wrong (very low) offer price and it's lifted by a buyer? How do we back out?
A: TMC can cancel it for us (so-called long-term “relationship”) , but in most cases, you can't simply cancel a trade simply because you want to change your mind.

Q: in classic, how does one cache trigger update cache in another JVM?
A: async by JMS subscription, and synchronously by RMI. Each cache JVM has a cache port.

Q: how does the swing app get notified when server side gets a new price, benchmark, pin, spread, new trade etc?
A: local cache subscribes to JMS

Q: bid/ask spread indicates liquidity?

swing/wpf #1 primary design pattern?

Someone asked me to name the single most important design pattern in swing. I feel a number of design patterns are equally fundamental and widespread in swing

* producer/consumer — main pattern in thread communication including task/event processing among threads. Low-level.
* observable — main pattern in communication between UI components
* MVC/MVVM — main pattern in component object composition or each UI component

Other patterns —
Pattern command — as wpf commands and in the form of runnables like invokeLater()
Pattern singleton — not strictly, but a lot of swing objects are singletons by nature.
Pattern Composite
Pattern Builder
Pattern factory
Pattern mediator — http://www.howdoicode.net/2012/07/wpf-view-model-communication.html
Pattern visitor — to visit a family of visual components

will swing be pushed out from front office?

Is swing slow and ugly? only before java 5.  Search for “java swing” in eFC.

– I think on windows WPF has an inherent advantage due to excellent integration with win32.
+ If server-side is java (not c++ or c#), then i feel swing has an inherent advantage over WPF. RMI, JMS, serialization, shared domain entity classes, distributed memory…
+ requires no installation
+ free and available out of the box

swing IV questions

Q: 
Q: jide, swingx?
Q: paint vs repain?
Q: how do you create your own jcomponent class? 
Q: what multi-threading challenges in your projects? What strategies or best practices?
Q: describe your swing projects and the challenges
Q: how do you load lots of data in the background but keep the app still responsive?
Q: undo? No one asked

Q: how do you use property change events?
A: AbstractAction blog

pack() – quite different from revalidate, repaint etc

I believe system repeatedly executes revalidate() and repaint(), …. but pack() only once.

pack() is all about
1) sizing visual components (imprecise wording) but it has a side effect of
2) realizing a jcomponent.

Best summary (found online) for 1) —

pack() compacts the window, making it just big enough.”The pack method sizes the frame so that all its contents are at or above their Preferred sizes.”

JButton sizing under various layout managers

Flow layout will honor button’s preferred size.(Box layout doesn’t. Border layout doesn’t. Grid layout doesn’t. See also post on wpf vs swing layout. WPF uses min/max.)

    public static void main(String[] args) {
        JFrame frame = new JFrame(“test”);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        for (int i = 1; i < 4; i++) {
            JButton btn = new JButton(String.valueOf(i));
            btn.setPreferredSize(new Dimension(i * 60, i * 30));
            panel.add(btn);
        }
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html#size says —
Although BoxLayout pays attention to a component’s maximum (not preferred) size, many layout managers do not. For example, if you put a button in the bottom part of a BorderLayout, the button will probably be wider than its preferred width, no matter what the button’s maximum size is. BoxLayout, on the other hand, never makes a button wider than its maximum size.

For BoxLayout, I realize it’s tricky to control the height/width. One proven solution is setPreferred()+setMax(). If you only setMax(), then height is uncontrolled.

    public static void main(String[] args) {
        JFrame frame = new JFrame(“test”);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));//or Y
        for (int i = 1; i < 4; i++) {
            JButton btn = new JButton(String.valueOf(i));
            final Dimension dim = new Dimension(i * 40, i * 60);
            btn.setPreferredSize(dim);
            btn.setMaximumSize(dim);
            // btn.setMinimumSize(dim);
            panel.add(btn);
        }
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

swing PLAF, native peer object ^ UI delegate

LAF concept (and implementations) is at the heart of the swing MVC. It is beneath just about every JComponent and UI delegate class. I think the concept of swing component’s painting and realization are relevant, if not a cornerstone of LAF implementation. UI delegates are instantiated when JComponent is instantiated, according to my debugging. When a component is “realized”, i believe its corresponding UI delegate “enters” a new state as it is painted on screen and can take user input.

http://java.sun.com/products/jfc/tsc/articles/painting/#background
“lightweight” component is one that reuses the native window of its closest heavyweight ancestor.

I think that ancestor is usually a jframe instance

http://jan.newmarch.name/i18n/input/input.html
a Swing object does not rely on an associated peer object. This article also covers event queue.

http://java.sun.com/products/jfc/tsc/articles/architecture/
As an application developer, you should think of a component’s view/controller responsibilities as being handled by JButton, JTree,.. The component class then delegates the look-and-feel-specific aspects
of those responsibilities to the UI object of the look-and-feel.

Pluggable look-and-feel means the portion of a component’s implementation that deals with the presentation (the look) and event-handling (the feel) is delegated to a separate UI object of the look-and-feel,
com.sun.java.swing.plaf.windows.WindowsScrollBarUI is a concrete class for such an UI object

The UIManager is the API through which components and programs access look-and-feel information (they should rarely, if ever, talk directly to a LookAndFeel *instance*). UIManager is responsible for keeping
track of which LookAndFeel classes are available, which are installed…

making sense of swing models

Justification for models: created by swing team in the MVC fashion to promote modularized separation of concern. However, controller and view are too frequently coupled because a view-agnostic controller is rare and hard. Model, however, is easily “separable” and “decouplable” in the OO sense.

Example — Logically, a jtable is a view with an object holding its data. That object is the table model. In fact jtable api encourages[1] us to use the table model.

Example — a jtextComponent is a view with an object holding its data. That object has its own type name — “Document.java”

Other swing components are more “relaxed” and let you live with or without models.

Most models fall into 2 categories. Note a model must always sit behind a UI component, otherwise it’s nothing but a regular java object.
1) domain data model, which represents entities in the business domain. See examples above.
2) UI device model – it represents state of the UI component only. Eg toggle button model

[1] you can hardly use a jtable without a table model.

easiest way to display a DB record in jtable

DefaultTableModel model = new DefaultTableModel(new Object[] {“Col”,”Value” }, 0);

model.addRow(new Object[] {selection});

Map map = new JdbcTemplate().queryForMap(“select * from table1 where …”);

for (Map.Entry entry : map.entrySet()) {
  model.addRow(new Object[] { entry.getKey(),
  entry.getValue() });
}
this.table.setModel(model);
this.table.repaint(); // thread safe

swing timer – simple eg

This creates an anon action listener and pass it to timer ctor.

Q: what does the listener perform?
a: anything

new Timer(millisec2sleep, new ActionListener() {
public void actionPerformed(ActionEvent notUsed) {
TimerSwingWorker.this.scanTables(command2getUpdates, " <- detected ");
}
}).start();

GUI for fast-changing mkt-data (AMM

For a given symbol, market data MOM could pump in many (possibly thousands of) messages per second. Client jvm would receive all updates by regular MOM listener, and update an small (possibly one-element) hashmap — by repeated overwriting in the memory location. Given the update frequency, synchronization must be avoided by either CAS or double-buffering, in the case of object or a long/double. For an int or float, regular volatile field might be sufficient.

Humans don’t like screen updated so frequently. Solution – GUI worker thread (like swing timer) to query the local cache every 2 sec — a reasonable refresh rate. It will miss a lot of updates but fine.

(Based on a real implementation hooked to a OPRA feed)

JComponent repaint(), validate(), pack(), realization and UI delegates

See below for other people’s definitions, but
– I think validation means a re-layout of children within a container pane. Required after changes therein. See javadoc.
– I think pack() compacts a container to the minimum size needed to display all children according to their preferred size. It has an important side effect of realizing the host JComponent.
– Repaint() is more common but underlying paint() operation is a low-level (more native), physical operation that takes care of the nitty gritty of displaying a jcomponent via its LAF UI delegate.
– I guess realization means isDisplayable? Note UI delegate objects are instantiated much earlier. [1]

[1] If you do a new JLabel() first thing in main(), and put a breakpoint on ComponentUI.java ctor, you will see that UI delegate objects are instantiated well before setVisible.

JComponent.paint(Graphic) is so sacred that it is EDT-only. Repaint() is usable from any thread, to schedule paint() on EDT.

“The validate method is used to cause a container to lay out its subcomponents again.” When changing container’s content, you have to call *both* (in either order)

* revalidate()
* repaint() to request a repaint for this container

“The following JComponent instance methods are safe to call from any thread: repaint(), revalidate(), and invalidate(). The repaint() and revalidate() methods queue requests for the event-dispatching thread to call paint() and validate(), respectively. The invalidate() method just marks the host component and all of its direct ancestors as requiring validation.”

Pack-and-show is a common idiom. JFrame.pack() is one of the birth methods whereby all child components become realized, whether hidden or visible. JFrame.show() and JFrame.setVisible() actually make them visible. These 2 methods are birth methods too as they makes subcomponents realized and visible. I think pain() is an underlying birth method but is invoked only from other birth methods.

http://java.sun.com/products/jfc/tsc/articles/painting/#background is a detailed article on painting

AbstractAction – brief intro

(Outdated. See other posts.)
A typical Action instance is a combination of
+ a stateless action listener
+ a stateful lookup table of _instance_ properties for a toolbar button. Properties include text label, icon, tooltip, shortcut key binding… [2]

Action instance gets wrapped [1] in the toolbar button instance. At the same time, a menu item instance can be another wrapper over the same Action instance. Those properties become shared, effectively[4].

Therefore, our Action instance becomes _master_ of 2 slaves. When you putValue(somePropName, someNewVal), you update master lookup table[3]. This lets you centrally control the button/menu item that must perform the same action.

The official java tutorial http://download.oracle.com/javase/tutorial/uiswing/misc/action.html has sample code.

[1] How do you wrap the Action instance in a toolbar button instance?
+ call ctor new JButton(myAction) or new JMenuItem(myAction)
+ As a shortcut, When you call add(myActionInstance) on a JToolBar, the toolbar button instance is instantiated as a wrapper object. Same thing when adding to a JMenuBar.

[2] You can add your own properties
[3] Exactly one property has its own setter/getter — setEnabled().
[4] actually the button (or menuItem) instance has its fields “mastered” by the Action properties. Achieved by PropertyChangeListeners. P47 [[Zukowski]]

non-trivial layout – swing ^ dotnet

In Swing, The lazy way to achieve precise layout is subpanels, but memory-heavy. If you use multiple frames, the number of subpanels can multiply.

The memory-wise solution is layout manager wizardry. GridBag is the most complex, impractical according to some. Microsoft has many more layout features, including xaml. Winforms uses anchorage.

I feel the wpf layout panel is like a panel with a specific layout manager … I feel it works better than swing. “Your chosen container determines the layout”, said one wpf book.

Netbeans offers layout assistance, but is still way behind Microsoft solutions.

basics – editable JComboBox

Editable combo box fires an event
1) when the user chooses an item from the menu and
2) when the user types Enter.
3) How about fire-as-you-type, on document change. Document is the model behind the text input editor. You need a DocumentListener —

JTextComponent tc = (JTextComponent) combo.getEditor().getEditorComponent(); // returns a text component just like the one behind a text field/area
tc.getDocument.addDocumentListener()

See http://stackoverflow.com/questions/1252698/how-can-i-know-when-the-text-of-an-editable-jcombobox-has-been-changed

Warning — menu remains unchanged when the user enters a value into the combo box. If you want, you can easily write an action listener that adds a new item to the combo box’s menu each time the user types in a unique value. This requires a MutableComboBoxModel.

swingWorker doInBackground() — basic tips

1) for a novice, it’s a practical defensive practice to catch Throwable in this method, otherwise the exception might be hidden somewhere.
2) if nothing to return, then Void is ok.
3) this method always runs on a non-EDT thread, so the assert helps document that.

public Void doInBackground(){
StaticSwingUtil.assertNotEDT();
try {
// time-consuming scan
scanTables(this.command, this.tagLine);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}

a holder of JComponent singletons

package updatable.TextPane;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JComponent;
/**
* In most swing apps, there are a fixed number of jcomponent objects, effectively singletons.
* Many of them are accessed from multiple “client” classes. Sometimes you can’t pass them as arguments,
* therefore many become fields of the client classes, which is messy.
*

* This class holds 1 or more singleton jcomponents. Helps you avoid keeping a lot of fields.
*
 */
public class JCompSingletons {
                static private final Map mixed = new ConcurrentHashMap();
                static public void add(String s, JComponent c,
                                                Class type) {
                                if (!type.isInstance(c)) throw new IllegalArgumentException(“wrong type specified”);
                                mixed.put(s, (T) c);
                }
                static public T get(String key, Class type) {
                                JComponent ret = mixed.get(key);
                                if (!type.isInstance(ret)) throw new IllegalArgumentException(“wrong type specified”);
                                return (T) ret;
                }
}

topFrame.setVisible() on EDT?

topFrame.pack();
topFrame.setVisible(true);

I find it ok to ignore the swing tutorial advice, and call setVisible() on the main thread, without invokeLater(). I don’t think we violate the single-threaded rule — Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread. A Swing component that’s a top-level window is realized by having one of these methods invoked on it: setVisible(true), show(), or (this might surprise you) pack().

swing features that exceed browser

Q: in the web2.0 era, why use swing or any thick/fat client?

spreadsheet — (dozens of) Spreadsheet features. Just compare Excel against google docs.
fast, automatic screen update based on incoming messages
state — sophisticated state maintained inside client JVM.
threads — create multiple threads in client JVM, to do arbitrarily complex things.
DB — access database
Caching — large amount of database records locally.
access ejb, rmi, webservices
disk — access local hard disk
call OS commands or run any executable
MOM — multiple MOM listeners
precise control of real estate — squeezing in the maximum amount of info in a window.

jtable sort, edit, delete, column-move using client (save the server) CPU
swing timer
Better utilization of client machine processing power.
visual rendering using client machine’s CPU
drag and drop
context menu
fully customizable keyboard shortcuts
movable split pane

swing client/server communication – MOM or RMI

See also http://bigblog.tanbin.com/2011/02/swing-server-communication-for-wall-st.html

1) MOM – server ==> swing? Best example is market data and trade blotter
2) MOM – swing ==> server? Good for some non-urgent updates originated on UI. How about the server response?
2a) perhaps UI doesn’t care about the response
2b) In Neo, the WPF client sends a message to server and returns. A separate onMsg() thread waits for the server response.

Some user operations must use a synchronous call (like EJB or web service) rather than MOM —
3) separate swing thread to call server and then update UI (by publishing to event queue, or invokeLater)
4) action listener running on EDT makes a synchronous blocking call to server, making the UI temporarily non-responsive.

What if server pushes data to swing but needs some client response? I feel this is less common. Swing could run an RMI server and MOM listener. I feel MOM is better.

1 queue, 1 EDT thread, 2 full time jobs

The event-dispatch-thread has 2 distinct responsibilities and does nothing else.
1—-) EDT updates the state of UI components, which propagate to the screen
2 —) EDT runs all the event callbacks — EDT’s event queue receives events from user input which trigger other events. Those secondary events go into the EDT queue and are handled on the EDT itself.

EDT queue receives events both from the underlying peer classes and from trusted application classes.
EDT queue receives events from timers
EDT queue receives events from your custom fireTableDataChanged()
EDT queue receives events from your custom invokeLater() when you finish reading/write to DB, file system or network
EDT queue receives events from your custom invokeLater() when you return from wait(), sleep() or join()
Any potentially blocking operation should be on a non-EDT. At end of the operation, you should call invokeLater to fire event to EDT.

When EDT blocks, traffic stops both ways
– down) user inputs can’t go down the system (from peer object?)
– up) updates can’t show up on screen (to peer objects?).

I feel this is an event producer-consumer pattern with the queue as the buffer. Note the FIFO queue enforces strict order among the events — http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/EventQueue.html

state of data model vs state of a visual component

Say myTable has a table model encapsulating a “vector3” holding 3 beans for 3 data rows. The actual visual image on screen is a native/physical/screen object outside JVM. Since objects all occupy memory and have individual states, the visual object and vector3 both hold data for the 3 beans.

Q: are there 2 copies of each bean?
%%A: I think so. The visual object is tightly guarded by kernel[1] since it’s a shared hardware resource. i guess No application is allowed to directly modify visual objects. Java Application can freely modify a java vector, but vector3 object has to be distinct from the visual object. Therefore, for each attribute[1] of the beans in vector3, there’s a copy of it in the visual object.

Q: Similarly, when a user types a letter “K” into a cell in myTable, it’s probably saved in the visual object’s memory (otherwise it will be lost in a clock cycle), but is there another distinct java object inside vector3, to be updated to “K”? The keyboard input generates an event encapsulating the text. Probably a copy of the text. But how about the bean in vector3? Is it directly modified by the keyboard input?

%%A: I would say no. It’s extremely rare to have a variable directly updatable by hardware. In C It’s known as __volatile__ variable. I think it’s more common to have a java thread [4] updating vector3. Code running in that thread is regular java code. In contrast The visual object is tightly guarded and owned by the OS[3], not directly exposed to applications.

In a jtable, I confirmed that a special thread[4] updates vector3 (real data structure of the table model), then fires an event to the listeners.

Q: But what if a MOM thread also updates vector3?
%%A: veterans told me we need locks as “guard” over vector3. When users are editing a jtable, MOM thread should not touch it.

[1] Each non-primitive attribute has to be represented or serialized as primitive int/float/char, for it to be usable in the visual.
[3] Remember OS/kernel was created as a chokepoint access layer over shared hardware
[4] my test shows it’s EDT

3 types of swing "classes" in containment hierarchy

Every (yes Every) swing application can be /usefully/ described as a hierarchy of containment, even if 2-level. I only encountered 3-levels or more. A hierarchy always has exactly one INSTANCE of a top-level
class.

Simplified classification — each everyday swing class is exactly one of these 3 —
1) top-level container class, usually JFrame.java
2) branch container class, like JPanel.java, JScrollPane.java,JTextPane.java, JSplitPane.java
3) leaf class, like jtable

As you can see, swing provides exactly 2 types of container classes — top-level vs branch. Both types are few in number and so widely used they are unavoidable. Better know then well.

Layout managers mostly target a branch container. I doubt they target top-levels since the top-level usually contains just a single content pane, so no layout required, presumably. I feel WPF is similar — The WPF top-level window holds exactly one container, which is a layout-control-panel.

Q: can we make do without branch containers?
A: I don’t think so, since a jframe has a content pane which is a jpanel.

A top-level swing class is always heavyweight; a branch or leaf class is lightweight. See P 362 [[java cookbook]]

Q: can a branch class be used as top-level or leaf?
A: I don’t think so. A branch container class can’t be top-level (not heavyweight) and should not be a leaf because it doesn’t display useful content by itself.

update jtable from inside an event listener: short sample

Note: one event only. In other cases, the event listener (on EDT) often generate cascading events to update other JComponents
Note: the stateful listener, which is common. The simplest listeners are stateless functors.
Note: setModel — “swapping” in a new model

Note the jtable object vs the table model object. Different addresses!

The listener ctor can receive the jtable object and save it as a field —
public SelectionChangeListener(JTable table) {
   this.table = table;
}
// now in the event handler
DefaultTableModel model = new DefaultTableModel(…);
this.table.setModel(model);
this.table.repaint(); // must run on EDT???

some methods should always/never run on EDT

If a method *might* run on EDT, then don’t invokeAndWait() on it. You can invokeLater() on it though. See [[java threads]]
If a method should always/never run on EDT, then those methods should call this assertion method below to make an assertion.
      public static boolean assertIsEDT() {
            boolean isEDT = javax.swing.SwingUtilities.isEventDispatchThread();
            if (!isEDT) {
                  // Always create new Exceptions as local variables, never fields
                  AssertionError e = new AssertionError(“One of the methods in this call stack is “ +
                              “found running on a wrong thread. This method is designed as EDT-only.”);
                  e.printStackTrace();
                  throw e;
            }
            return isEDT;
      }
      public static boolean assertNotEDT() {
            boolean isEDT = javax.swing.SwingUtilities.isEventDispatchThread();
            if (isEDT) {
                  AssertionError e = new AssertionError(“One of the methods in this call stack is “ +
                              “found running on the EDT. This method is designed as a never-EDT method.”);
                  e.printStackTrace();
                  throw e;

            }
            return isEDT;
      }

GUI-server communication — HFT (Piroz)

Mostly based on a veteran’s input…

Most GUI clients I have seen use some sort of messaging and you want that to be as asynchronous as possible.  There is no reason to keep the user waiting.  User clicks on something, the client sends a message to the server and the client is now waiting for a response.  When a response comes in (on a separate thread), the GUI takes it and displays whatever it needs.  Some people stick a unique request id in the message so when the response comes they can figure out to which request it belongs.

You also have subscription cases where you subscribe to prices for a security and the server will tell you listen to this channel for all updates.  That should be encapsulated in some sort of handshake.
RV, 29West and JMS are good choices.

swing/server using 2 http requests (trading

A third party trading platform (like FXAll, tradeweb, Bloomberg, creditex, espeed, brokerTec) could install a swing GUI on traders’ screens. Every time a trader requests info from the remote server, there are 2 swing threads involved —

– one responsible for synchronously uploading the request message, via an http tunnel through firewall
– another responsible for synchronously downloading the response message – http tunnel. I guess this requires a URL including a requestID.

If server is busy or slow, then the 2nd synchronous call should take place after some delay. Otherwise it would block for a long time.

Q: I wonder how server could push market data to swing? I feel the http tunnel means the http client can’t be a server.
%%A: i guess the client makes periodic requests for updates. This is not really real time.

top 3 layout managers by importance

1) border layout — the default for the the content pane (jpanel) of a jframe. A country with a border and 4 neighbours.

2) flow layout — the default in JPanel [2]. Tend to be the simplest layout. Good for simple apps.

3) grid bag — last resort if you want more (almost absolute) control than available in other layouts, but I feel there’s a simpler alternative — nested-layout ie nested subpanels each with a layout manager.

[2] However, the jpanel in jrootpane gets a BorderLayout
In numerous current textbooks, the top 4 layouts are border, flow, grid and box. Most of them mention grid bag as a last option. Few mention card, spring etc.

root objects – garbage collector(swing

Conceptually, think of the GC daemon waking up and scanning all threads and all static fields.

1) call stacks [3] — Most obvious category of root objects are “objects of unfinished method CALLs”. For each unfinished CALL on each call stack, root objects include:
– every argument of reference type
– every local var (except primitives)
– that class object /hosting/ the static method
– that instance hosting the instance method

[3] I prefer “call stacks”. A “thread” is more than a call-stack — see blog post on call stack.

2) static fields — 2nd most obvious type of root objects are “static fields[1] of loaded classes” . Technically, static fields are 2nd-level nodes whose parent nodes are “class-objects”[2]. However, static fields are a more tangible thing to programmers.

[1] except primitive static fields
[2] Every loaded class has a class-object which persists in memory forever => class loaders can introduce mem leaks. Not sure about class-unloading(???)
eg: System.out
eg: Math.PI
eg: most if not all constants defined as “public final static”
eg: D.seen in my debugger. On demand [1], D.java class [2] is loaded by JVM. During class loading, every single static vars must be initialized. D.seen is a HashMap, so the default initial value of D.seen is null, but in a subsequent method, we call new HashMap(). This HashMap becomes a root object.

[1] If you don’t use it, the D class is not loaded.
[2] (By the way, no D() constructor call needed.)

Q: Why is Math.PI always reachable after class loading?
A: Anyone can access PI any time.

Q: what if D.seen is not public?
A: D.d() is a public static method that relies on D.seen. Anyone can call D.d() any time. D.seen must remain in memory forever.

3) jni. It’s good to know how jni relates to other java technologies

other groups of root objects?

Now, some non-root objects. Special Attention needed with:
B) static collections such as a cache
A) event listeners + observers. Persistent collections. We need to remember to unregister/unsubscribe listeners or observers. Swing is particular prone to memory leak.