Welcome!

Java IoT Authors: Zakia Bouachraoui, Pat Romanski, Elizabeth White, Yeshim Deniz, Liz McMillan

Related Topics: Java IoT

Java IoT: Article

Implementing a Grid Layout Manager with Positionable Components

Implementing a Grid Layout Manager with Positionable Components

Why Write Custom Layout Managers? Layout manager objectifies the component layout strategy. It disentangles component layout code from the drawing code of the container of components. By isolating the implementation of a layout strategy in a separate class, a programmer can reuse it by simply assigning an instance of this layout class to the container that requires it. Without a layout manager the layout code would have to be embedded within drawing code of the container itself.

Java's AWT supports this concept in the LayoutManager interface and supplies five implementations that are sufficient in most situations. It's sometimes more efficient and effective, however, to implement one's own layout manager, designed specifically for a particular task, rather than struggling with the standard layout managers.

Let's say we need to draw components on a grid, for example, but need to specify the positions of the components arbitrarily at any time. On the first take we'd probably choose AWT's GridLayout as the layout manager - that is, until we discover that it will only position components in sequence. The programmer then would have no control over their positions. The alternative would be to use GridBagLayout, but that's way too complicated and difficult to control for such a simple task. The solution is to write our own LayoutManager. As you'll see, this isn't as difficult as it sounds and may be the best solution in many situations. This article introduces a grid layout manager with positionable components, and with flexibility and complexity somewhere between AWT's GridLayout and GridBagLayout.

Layout Manager Basics:LayoutManager Interface
AWT's LayoutManager interface declares the following methods that have to be implemented in a valid layout manager:

  • addLayoutComponent
  • removeLayoutComponent
  • layoutContainer
  • minimumLayoutSize
  • preferredLayoutSize

    AddLayoutComponent and removeLayoutComponent let the Container assigned with this layout add and remove a Component to and from the layout. LayoutContainer implements the layout strategy, changing the x and y pixel position and the dimension of the Components as necessary. MinimumLayoutSize and preferredLayoutSize let the Container find out the minimum required and preferred layout size given the Components to be laid out in it.

    AWT's Containers are assigned default LayoutManagers but a different one may be chosen using the Container's setLayout method. When you add a Component to a Container, the Container will in turn add it to its assigned LayoutManager. The same happens when you remove a Component. Whenever a Component is added or removed, the Container will call the layoutContainer of the assigned LayoutManager to update the position and size of all Components. If you need to lay out the Container again, you may invoke the Container's doLayout method to recompute the layout.

    PositionableGridLayout Class
    We call our grid layout with positionable components the PositionableGridLayout class. The minimumLayoutSize for this case should be the extent of the layout embodying the outermost component. That would be our preferredLayoutSize as well. In other words, minimumLayoutSize is the x grid position of the easternmost Component times the width of each grid and the y grid position of the southernmost Component times the height of each grid. This is shown in Listing 1.

    LayoutContainer calculates the pixel location of each Component given its grid position, and relocates it with a call to the Component's setBounds method if necessary.

    Note that we did not implement addLayoutComponent and removeLayoutComponent because nothing special needs to be done when a Component is added to or removed from the Container.

    Listing 2 shows the implementation of PositionableGridLayout for Java 1.1.

    Layout Constraints: PositionableGridConstraints Class
    An automatic LayoutManager - that is, one that would not allow the programmer to control the location and size of each Component - would normally be able to work alone. For a LayoutManager that allows the programmer to individually fix the location and size of the Components, however, an assisting class is required. Such is the case with AWT's GridBagLayout, which requires GridBagConstraints to work. In our example we need to be able to position any Component at an arbitrary location at any time. Following the example of GridBagLayout, we implement an assisting class, the PositionableGridConstraints, which allows us to specify the grid position of an added component.

    The PositionableGridConstraints class is fairly simple to implement. It mainly stores away the grid position of a Component.

    /**
    * Constructs a PositionableGridConstraints.
    */
    public PositionableGridConstraints( int gridx, int gridy, ... )
    {
    this.gridx = gridx;
    this.gridy = gridy;
    :
    }

    We need to assign the grid constraints to the Component, of course. Again, following the example set by AWT's GridBagLayout, we implement a setConstraints method in PositionableGridLayout whose purpose is to associate the grid constraints to a Component in a hashtable using the Component as the key, as shown in Listing 3. Listing 4 shows the implementation of PositionableGridConstraints.

    Using the PositionableGridLayout Class
    A good example of the use of the PositionableGridLayout class would be the familiar sliding puzzle. Initially, the tiles lie in a grid. As the user shifts the tiles' position, the application has to change the coordinate of each piece. Listing 3 shows the implementation of a simple 3x3 puzzle, the core of which follows it. Note in Listing 5 the convenience of being able to position Components by grid position instead of pixel location.

    Conclusion
    We've shown the use of LayoutManager beyond the standard AWT-supplied implementation. We've shown how customized LayoutManager can be a powerful tool for implementing unique Component layout strategy for any Container. In a future article we'll make use of the PositionableGridLayout class and the Widget interface class featured in an earlier issue of JDJ (Vol. 3, Issue 6) to implement a TreeViewer widget, a component for laying out trees in either horizontal or vertical format.

    Download Source Code
    The program in this article requires the callback and widget code from the Implementing Callback and Widget-izing AWT articles published in JDJ (Vol. 3, Issues 4 and 6, respectively). Full source code (including a complete version of Puzzle) can be downloaded free from www.wigitek.com. A more extensive version supporting programmer-defined Component size, autoadjustment and alignment for Java versions 1.0 and 1.1 is also available from Wigitek Corporation at the same Web site.

  • More Stories By Daniel Dee

    Daniel Dee has more than 10 years of experience working in the development of GUI software toolkits, starting with X Windows and then Java, since their inception. He is currently the president of Wigitek Corporation, a company providing software tools and consulting services for the development Java-based data-driven dynamic graphics software. He received an MS degree in Computer System Engineering from the University of Massachusetts.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    IoT & Smart Cities Stories
    Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
    Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
    In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
    Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
    Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
    René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
    Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
    Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
    If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
    Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...