|
Swing FAQsWe want to hear from you! Please send us your FEEDBACK. The following responses to Frequently Asked Questions (FAQs) may contain actual software programs in source code form. This source code is made available for developers to use as needed, pursuant to the terms and conditions of this license.
1. Where can I find beginners information? See the Java Tutorial's Swing pages at: http://java.sun.com/docs/books/tutorial/uiswing/
2. When I type into a JTable cell why does it not gain focus? When clicking into a cell it gains focus, but when moving the cursor to a cell it does not gain focus to type into. A new property has been added into the Java[tm] 2 Platform, Standard Edition version 1.4 (Merlin) to solve this, namely surrendersFocusOnKeystroke to maintain backward compatability. See: http://java.sun.com/j2se/1.4/docs/guide/swing/SwingChanges.html#JTable
3. How could I set colours for JTable row, columns or cells? Each cell is rendered using a DefaultTableCellRenderer , by subclassing this class you can specify criteria to modify the renderers parameters. The code below demonstrates how to do this. It could also be taken further so that the MyCellRenderer could contain methods to set affected rows, colours, borders and text settings. import javax.swing.*; class TableTest extends JFrame { TableTest() { final MyCellRenderer mcr = new MyCellRenderer(); JTable myTable = new
JTable(new MyTableModel()) { getContentPane().add(new
JScrollPane(myTable)); public static void main(String args[]) { new TableTest();
class MyTableModel extends AbstractTableModel { String[] columnNames = {"Name", "Age", "Sex"};
public Object getValueAt(int row, int col)
{return columnData[row][col];} class MyCellRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent
// Obtains default
cell settings if (row % 2 == 0)
cell.setBackground(Color.blue); if (column % 2 == 0) cell.setBackground(Color.green); return cell;
4. How could I create a row header column in my JTable? View [ RowHeaderExample.java] The solution here is to create a component that 'lives' in the row header section of a JScrollPane. The component that is added to the row header is a JList. JList has a
5. Which model should I select for my JTable? The hierarchy of the table models provided are: javax.swing.TableModel Starting with javax.swing.table.TableModel, this interface provides the following: Listener registration, cell value accessors, column names, class accessors and is the base for creating a table model. The main advantage with implementing the TableModel interface is that the definition of the methods can be customised along with the internal representation of data leading to scalable, and variable efficient applications. javax.swing.table.AbstractTableModel AbstractTableModel is an easy way to use data if it is already tabular. By overriding the three simple methods getValueAt, getColumnCount and getRowCount, the table model is available. AbstractTable model also provides event firing methods such as fireTableDataChanged, fireRowsUpdated and so on... Again with AbstractTableModel as with the TableModel above, the internal representation of data can be static (free to choose storage), or dynamic so efficient applications result. By using a 'cache'as opposed to generating content for the getValueAt method, the performance is greatly improved in display and scrollability. javax.swing.table.DefaultTableModel Without specifying in the JTable's constructor, this is the default table model used. DefaultTableModels internal representation of data is as a Vector of Vectors. This is good if the data to be used is not already tabular, as conversion from the original set is a performance issue. Once the data is set though, performance such as scrolling and display should be good as the data is cached. If the data is large or if cached already (such as by a database) then replication of cached data could be an inappropriate choice. An advantage of using DefaultTableModel is its mutability. Implementation of setValueAt and its row/column modifiers including insert, add and remove, allow easy change of data after table construction. Another advantage of this is that the design is good, all being encapsulated locally.
6. How do I stop the user from moving the JTable header or sizing the table columns? For restricting column movement use For restricting column resizing use For individual column resizing use NOTE:This does not work (due to a feature) prior to the Java 2 Platform, Standard Editiion, version 1.3 (Kestrel).
7. How can I fix rows in my JTable so they are always visible? You can achieve this if you create two separate tables from the same data. For example, if you wanted the last two rows to be fixed you could override one model to return all the rows except the two fixed, and the second model to return only the values of the fixed rows, such... AbstractTableModel fixedModel = new
AbstractTableModel() { AbstractTableModel model = new AbstractTableModel()
{ The tables are then added, setting the fixed table to not have a column header. You may also further customise this by adding scroll checking as in the following example, and even column moving etc. View [ FixedRowExample.java]
8. How can I fix columns in my JTable so they are always visible? You can achieve this if you create two separate tables from the same data. For example, if you wanted the first two columns to be fixed you could override one model to return all the columns except the two fixed, and the second model to return only the values of the fixed columns, such... AbstractTableModel fixedModel =
new AbstractTableModel() { AbstractTableModel model = new AbstractTableModel()
{ The tables are then added, the fixedTable is added to the RowHeader column of the scrollpane. You may also further customise this by adding selection syncronisation as shown in the following example... View [ FixedColumnExample.java]
9. How can I set tooltips on my JTable header? You can set a tooltip per renderer using the component.setToolTipText(..) method. By default the table header has one default renderer so you cannot use this method. By subclassing the JTableHeader class and overriding the getToolTipText(MouseEvent e) method you can return a String tooltip according to which column header the mouse is over. [ ToolTipHeaderTableExample.java]
10. How could I hide/show columns in my JTable? This can be achieved a number of ways in various levels of complexity. There are three methods to do this, namely: public void removeColumn(TableColumn column)
These are provided from the TableColumnModel that is obtainable from JTable by the method "getColumnModel()". One issue that should be noted is that there is a difference between hiding a column and removing a column from view; if you remove the column and add it again, it is added to the right of the existing columns, not where it was originally. You could store the position of the original column index but this does not account for column reordering. One solution is to track the columns, such as in a Vector, and create rules governing the hidden columns. A second issue is the TableColumn is no longer referenced, so either a store of hidden columns is needed or the creation of new TableColumns is used.
11. How do I stop JTable rows/columns/cells being editable? Using DefaultTableModel as an example: class MyTableModel extends DefaultTableModel { public boolean isCellEditable(int row, int column) {
return false; table.setModel(new MyTableModel()); By subclassing the table model you are able to overide the isCellEditable method to produce the results you require.
12. Where can I learn more about Swing - courses and books, for example? Books: http://java.sun.com/docs/books/javatutorial/jfc.html Courses: http://suned.sun.com/ Online Resources: Homepage
13. What is the difference between AWT and Swing? The Swing components are implemented with absolutely no native code, and as such, have more functionality and capabilities. Here are some useful URLs explaining in more detail: How Are Swing Components
Different from AWT Components? Which releases contain
the Swing API?
14. How can I use threads with Swing? In general Swing components are
not thread safe - that is, they can
only be accessed by only one thread at a time. This was done for many
reasons including... There are a number of documents that explain this in depth: The Swing Connection
site The Java
TM Tutorial
15. Which browsers support the latest Java runtime environment with Swing? The latest Netscape Navigator [tm] 6.x browsers contain Sun's Java 2 Platform, Standard Edition version 1.3 runtime environment with the Java Plug-in as part of the installation options - either "Full" or "Custom" installs. Another option is to download the latest small (around 5 Mb) Java runtime environment with the plugin from http://java.sun.com/j2se/ to use with the latest browsers including Netscape Navigator TM and Microsoft's Internet Explorer. Once your Swing applet's HTML is converted for use with the Java[tm] Plug-in, your clients will be asked if they would like to download the Java[tm] Runtime Environment if they do not already have it installed.
16. Why can I not use a certain Look and Feel - such as Microsoft Windows? I get the following exception (selecting the Microsoft Windows Look and Feel): javax.swing.UnsupportedLookAndFeelException:
[The Microsoft Windows Look and Feel - com.sun.java.swing.plaf.windows.WindowsLookAndFeel]
not supported on this platform There are a number of reasons why a Look and Feel (L&F) may not want to run on a particular platform. For example, the L&F might not be written in 100% Pure Java TM; instead, it might depend on platform-specific features. There may also be competitive or legal reasons for restricting the use of a L&F to certain platforms. One solution is to select a cross-platform Look and Feel such as the Java Look and Feel (Metal). There is further information
here in the Java[tm] Tutorial:
17. I cannot use Swing in my Java applet! If you are using a browser such as Microsoft's Internet Explorer or Netscape Navigator[tm] 4.x then the Java implementation that is supplied is version 1.1.x, and as such does not contain the Swing classes. You will probably be receiving ClassNotFoundExceptions on the Swing classes. To run a Swing applet you will need to use the Java Plug-in (see homepage below) or alternatively, use the "appletviewer" application supplied as part of the Java 2 Software Development Kit (SDK). NOTE: In 1.2 the package naming for Swing changed from com.sun.java.swing to javax.swing now that Swing is a part of the Java API set. see: Tables of
Java 2 SDK Features Which Releases
contain the Swing API?
18. Where can I find Java[tm] Look and Feel icons? The Human Interface Group has provided a graphics repository conforming to the Java Look and Feel design guidelines. http://developer.java.sun.com/developer/techDocs/hi/repository/
19. How can I change the display mode, use full screen mode, use hardware acceleration...? With the forthcoming release of the Java 2 Platform, Standard Edition version 1.4 (Merlin) there are a number of additions and improvements regarding drawing performance and control. A new tutorial has been written to assist developers with the changes; here is an excerpt: "Do you want to use high-performance graphics in the Java platform development environment? Have you always wanted to program a game, but your images wouldn't move fast enough? Has your slide show program not worked properly because you had no control over the user's display resolution? If you've been asking any of these questions, then the full-screen exclusive mode API may be what you're looking for." Find the new tutorial here: http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html
20. Can I find out the UIManager settings? The User Interface Manager (UIManager) is responsible for the Look and Feel settings. This Java TM application lists the UIManager default settings and current values, grouping them into Objects. It had been tested with 1.2.2/1.3.x. import javax.swing.UIManager;
class UIList { public static void main(String args[]) {
// Groups of setting objects UIDefaults uiDefaults = UIManager.getDefaults(); for (Enumeration enum = uiDefaults.keys(); enum.hasMoreElements(); ) {
Object setting = enum.nextElement();
// If itemList has a group named setting name then just
}
// Print out each setting and value
21. What Swing bug fixes and changes have been made with the Java 2 Platform, Standard Edition, version 1.3.x? http://java.sun.com/j2se/1.3/docs/guide/swing/SwingChanges.html
22. What Swing bug fixes and changes have been made with the Java 2 Platform, Standard Edition version 1.4 (Merlin)? http://java.sun.com/j2se/1.4/docs/guide/swing/SwingChanges.html
23. We are experiencing focus problems in our Java program... "Prior to Java 2 Standard Edition, JDK 1.4, the AWT focus subsystem was woefully inadequate. It suffered from major design and API problems, as well as over a hundred open bugs. Many of these bugs were caused by platform inconsistencies, or incompatibilities between the native focus system for heavyweights and the Java focus system for lightweights. " For further information:
24. Where can I find out about exisiting bugs and how can I report one? Firstly,
check to see if the bug has or is being addressed here: If need be, report
a new bug here:
25. I've heard that Swing is lightweight and the Abstract Windowing Toolkit (AWT) is heavyweight. What's the deal? "We should not use AWT but Swing components people tell me"
These are recurring questions. Following is some brief high-level information to clarify the position. The AWT is the Java platform's original set of classes for developing user interfaces. They use heavyweight components (that is, components having a native counterpart) and toolkits for the user interface. There are a large number of drawbacks to heavyweight components. Among the many drawbacks are: poor performance, a native look and feel, non-configurablility, and a lack of consistent platform behaviour others. The AWT is part of the Java[tm] Foundation classes (a colaboration between Sun, Netscape[tm], IBM and Apple), that includes Swing, the Java[tm] 2D API, and Accessability. Swing is built 'on-top' of the AWT. That is to say only a few components use the AWT heavyweight components, and for good reasons. The majority of Swing components are lightweight and so can be customised, greater in number, different in look and feel, possess more functionality and so on. The use of AWT graphic components is regarded as legacy; class usage and method calls are still used and provide great utility and access services.
26. Can I get Java Developer Support[sm] from Sun Microsystems? "Whether you're a business manager trying to get to market quicker, or an individual software developer learning new Sun technologies and need assistance, our professional technical support staff and tools can help." http://www.sun.com/developers/support
| |||||||||||||||||||||||||||||||||||||||