Home > Articles > Programming > Java

Like this article? We recommend

Building a Panel

Now that we have a frame window, we want to start detailing the user interface. We want to show a poker table with players, cards dealt, some controls that allow the user to drive the application, and so on. Sticking with the single responsibility principle, we’ll create a new class for these details instead of pushing them into the HoldEm class. This new class will be a JPanel that we can readily insert into any Swing container.

Before building the panel itself, we want to ensure that the HoldEm frame contains it. Here’s the modified code in HoldEmTest:

public void testShow() {
  assertFalse(frame.isVisible());
  app.show();
  assertTrue(frame.isVisible());

  Container contents = frame.getContentPane();
  assertEquals(1, contents.getComponentCount());
  assertEquals(TablePanel.class, contents.getComponent(0).getClass());
}

and the HoldEm code:

private void initialize() {
  frame = createFrame();
  frame.setTitle(Bundle.get(HoldEm.TITLE));
  frame.setSize(WIDTH, HEIGHT);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  frame.getContentPane().add(new TablePanel());
}

Getting this test to pass will require creation of a TablePanel class. We’ll have it extend from JPanel.

We can now create TablePanelTest. Our initial goal will be to worry about what it contains when it’s created. We’ll verify that components exist on the panel, and that our TablePanel code correctly initializes these components.

We want a button that kicks off the deal. The code in TablePanelTest starts us off (see Listing 3). Our test verifies that we can extract a JButton from the panel, and that its text is correct. Note the use of the Bundle class.

Listing 3 TablePanelTest.

package ui;

import java.awt.*;
import javax.swing.*;
import junit.framework.*;
import util.*;

public class TablePanelTest extends TestCase {
  public void testCreate() {
   TablePanel panel = new TablePanel();
   JButton button = getButton(panel, TablePanel.DEAL_BUTTON);
   assertEquals(Bundle.get(TablePanel.DEAL_BUTTON), button.getText());
  }

  private JButton getButton(JPanel panel, String name) {
   for (Component component: panel.getComponents())
     if (component.getName().equals(name)) {
      assertTrue(component instanceof JButton);
      return (JButton)component;
     }
   return null;
  }
}

Testing whether a panel contains a given component is a lot simpler if we provide a unique name for each component. Swing lets us attach a name to all components. The code in getButton loops through all components contained within TablePanel and tries to find a match on component name.

Listing 4 shows the production code to get the test to pass. Interestingly, its DEAL_BUTTON constant does two things:

  • It’s used as the key into the resource bundle, for deriving the initial button text.
  • It’s also used as the name of the component itself.

I hope reusing the constant won’t cause us any trouble.

Listing 4 Adding a button to the view.

package ui;

import javax.swing.*;
import util.*;

public class TablePanel extends JPanel {
  public static final String DEAL_BUTTON = "TablePanel.dealButton";

  public TablePanel() {
   initialize();
  }

  private void initialize() {
   JButton button = new JButton(Bundle.get(DEAL_BUTTON));
   button.setName(DEAL_BUTTON);
   add(button);
  }
}

Why Bother?

Are these kinds of tests valuable? From a testing point of view, my experience says that they are. Yet, ensuring that a widget appears on the panel doesn’t seem so valuable—we’ll continue to visually inspect the application as we go. But as we grow the Texas Hold ’Em application, or any typical application, we’ll add dozens of components onto many screens, ultimately capturing hundreds or thousands of pieces of user interface detail. In this sea of Swing code, it’s easy for us to change code and break something. Also, having the tests gives us a form of documentation of what each user interface component should be doing.

As we drive the application through tests, our continual concern with refactoring will push us to create many utility methods. These utility methods will shrink the size of the application. They’ll also make our code—both test and production—easier to write! Without tests, we’d write fewer utility methods. That would make our code look like the Swing code in most systems, with rampant duplication. We’ll avoid that mistake.

Using test-driven development (TDD), we speed up code delivery as long as we adhere to continual refactoring. That runs counter to most peoples’ intuition, which is that TDD should slow us down because we have to write twice as much code (production code and now tests). Instead, we want to view TDD as something that enables us to streamline our coding.

As we continue, we’ll add code for component interaction. For example, we’ll write code to enable or disable buttons depending on other things that happen in the user interface. This common need can get pretty complex, with button state changing based on many other factors. It’s an area where tests are sorely needed.

If we write tests only for these more complex areas, we’d spend more time setting up the context that allows us to write these tests. Worse, we’d find that we probably didn’t do a good enough job of making the Swing classes testable. We might find that it’s almost impossible to write effective tests.

Remember that our rule is to drive everything through tests. Once we start getting clever about when to write such tests (and when not to write them), we start getting into trouble. Our design suffers as a result, and coming back later to a test-worthy design—when we need it—can be at prohibitive cost.

Fleshing Out the View

At this point, we have a working user interface. Bring it up by executing the main method on HoldEm. It doesn’t do much; it shows a frame window with a single button. Clicking the button does nothing. But at least we’re able to view the window, and we could start enhancing its visual appeal by introducing Swing layout code. We’ll worry about those aesthetics later, once we get enough components onto the panel.

Right now, we want to get the ring of player seats displayed onto the panel. My initial thought is that the easiest way to accomplish this is to represent each seat as its own JPanel. We’ll drop 10 seat panels onto the TablePanel. Each seat will contain its position (from 1–10) and either the player name or something indicating that the seat is empty. If later we need to do something better, such as paint seats directly onto the TablePanel, encapsulating seats in separate view objects should give us a simple migration path.

Listings 5 through 13 show the updated system. We’ve added SeatPanel as a production mix. We’ve also added both test and production utility classes.

Listing 5 HoldEmTest.

public void testShow() {
  assertFalse(frame.isVisible());
  app.show();
  assertTrue(frame.isVisible());

  Container contents = frame.getContentPane();
  assertEquals(1, contents.getComponentCount());
  TablePanel panel = (TablePanel)contents.getComponent(0);
  assertEquals(1 + HoldEm.SEATS, panel.getComponentCount());
}

Listing 6 HoldEm.

public static final int SEATS = 10;
...
private void initialize() {
  frame = createFrame();
  frame.setTitle(Bundle.get(HoldEm.TITLE));
  frame.setSize(WIDTH, HEIGHT);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  frame.getContentPane().add(new TablePanel(SEATS));
}

Listing 7 TablePanelTest.

package ui;

import junit.framework.*;

public class TablePanelTest extends TestCase {
  private static final int SEATS = 10;
  private TablePanel table;

  protected void setUp() {
   table = new TablePanel(SEATS);
  }

  public void testCreate() {
   SwingTestUtil.assertButtonText(table, TablePanel.DEAL_BUTTON);

   for (int i = 0; i < SEATS; i++) {
     String position = TablePanel.getPosition(i);
     SeatPanel panel = table.getSeatPanel(position);
     SwingTestUtil.assertLabelText(panel, SeatPanel.POSITION, position);
   }
  }

  public void testPosition() {
   assertEquals("1", TablePanel.getPosition(0));
   assertEquals("2", TablePanel.getPosition(1));
   assertEquals("3", TablePanel.getPosition(2));
   assertEquals("10", TablePanel.getPosition(9));
  }

  public void testGetSeatPanel() {
   final String position = "2";
   SeatPanel panel = table.getSeatPanel(position);
   assertEquals(SeatPanel.NAME + position, panel.getName());
  }

  public void testSeatPlayer() {
   final String player = "Joe S.";
   final String position = "2";
   table.seat(player, position);
   SeatPanel panel = table.getSeatPanel(position);
   SwingTestUtil.assertLabelText(panel, SeatPanel.PLAYER_NAME, player);
  }
}

Listing 8 TablePanel.

package ui;

import javax.swing.*;
import util.*;

public class TablePanel extends JPanel {
  private int seats;
  public static final String DEAL_BUTTON = "TablePanel.dealButton";
  public TablePanel(int seats) {
   this.seats = seats;
   initialize();
  }

  private void initialize() {
   JButton button = new JButton(Bundle.get(DEAL_BUTTON));
   button.setName(DEAL_BUTTON);
   add(button);

   for (int i = 0; i < seats; i++) {
     SeatPanel panel = new SeatPanel(getPosition(i));
     add(panel);
   }
  }

  static String getPosition(int index) {
   return "" + (index + 1);
  }

  public void seat(String player, String position) {
   getSeatPanel(position).setPlayerName(player);
  }

  public SeatPanel getSeatPanel(String position) {
   return (SeatPanel)SwingUtil.getComponent(
     this, SeatPanel.NAME + position);
  }
}

Listing 9 SeatPanelTest.

package ui;

import junit.framework.*;
import util.*;

public class SeatPanelTest extends TestCase {
  private static final String POSITION_TEXT = "1";
  private SeatPanel panel;

  protected void setUp() {
   panel = new SeatPanel(POSITION_TEXT);
  }

  public void testCreate() {
   assertEquals(2, panel.getComponentCount());
   assertEquals(SeatPanel.NAME + POSITION_TEXT, panel.getName());
   SwingTestUtil.assertLabelText(
     panel, SeatPanel.PLAYER_NAME, Bundle.get(SeatPanel.EMPTY));
   SwingTestUtil.assertLabelText(panel, SeatPanel.POSITION, POSITION_TEXT);
  }

  public void testSetPlayer() {
   final String name = "Joe Blow";
   panel.setPlayerName(name);
   SwingTestUtil.assertLabelText(panel, SeatPanel.PLAYER_NAME, name);
  }
}

Listing 10 SeatPanel.

package ui;

import java.awt.*;
import javax.swing.*;
import util.*;

public class SeatPanel extends JPanel {
  public static final String NAME = "SeatPanel.seatPanel";
  public static final String PLAYER_NAME = "SeatPanel.playerName";
  public static final String POSITION = "SeatPanel.position";
  public static final String EMPTY = "SeatPanel.empty";
  private final String position;
  private JLabel nameLabel;

  public SeatPanel(String position) {
   this.position = position;
   initialize();
  }

  private void initialize() {
   setName(SeatPanel.NAME + position);
   setLayout(new BorderLayout());
   addLabel(POSITION, position, BorderLayout.NORTH);
   addLabel(PLAYER_NAME, Bundle.get(SeatPanel.EMPTY), BorderLayout.SOUTH);
  }

  private void addLabel(String name, String text, String layout) {
   nameLabel = new JLabel(text);
   nameLabel.setName(name);
   add(nameLabel, layout);
  }

  public void setPlayerName(String name) {
   nameLabel.setText(name);
  }
}

Listing 11 SwingUtilTest.

package ui;

import javax.swing.*;
import junit.framework.*;

public class SwingUtilTest extends TestCase {
  private static final String NAME = "NAME";
  private JPanel panel;
  private JButton button;
  private JLabel label;

  protected void setUp() {
   panel = new JPanel();
   button = new JButton();
   button.setName(NAME);
   label = new JLabel();
   label.setName(NAME);
  }

  public void testGetButton() {
   panel.add(button);
   assertSame(button, SwingUtil.getButton(panel, NAME));
  }

  public void testGetButtonNotFound() {
   assertNull(SwingUtil.getButton(panel, NAME));
  }

  public void testGetButtonNotButton() {
   panel.add(label);
   try {
     SwingUtil.getButton(panel, NAME);
   }
   catch (ClassCastException expected) {
     assertEquals("javax.swing.JLabel", expected.getMessage());
   }
  }

  public void testGetLabel() {
   panel.add(label);
   assertSame(label, SwingUtil.getLabel(panel, NAME));
  }

  public void testGetLabelNotFound() {
   assertNull(SwingUtil.getLabel(panel, NAME));
  }

  public void testGetLabelNotLabel() {
   panel.add(button);
   try {
     SwingUtil.getLabel(panel, NAME);
   }
   catch (ClassCastException expected) {
     assertEquals("javax.swing.JButton", expected.getMessage());
   }
  }

  public void testGetComponent() {
   panel.add(button);
   assertSame(button, SwingUtil.getComponent(panel, NAME));
  }

  public void testGetComponentNotFound() {
   assertNull(SwingUtil.getComponent(panel, NAME));
  }
}

Listing 12 SwingUtil.

package ui;

import java.awt.*;
import javax.swing.*;

public class SwingUtil {
  public static JButton getButton(JPanel panel, String name) {
   return (JButton)SwingUtil.getComponent(panel, name);
  }

  public static JLabel getLabel(JPanel panel, String name) {
   return (JLabel)SwingUtil.getComponent(panel, name);
  }

  public static Component getComponent(JPanel panel, String name) {
   for (Component component: panel.getComponents())
     if (component.getName().equals(name))
      return component;
   return null;
  }
}

Listing 13 SwingTestUtil.

package ui;

import javax.swing.*;
import junit.framework.*;
import util.*;

public class SwingTestUtil {
  public static void assertButtonText(TablePanel panel, String name) {
   JButton button = SwingUtil.getButton(panel, name);
   Assert.assertEquals(Bundle.get(name), button.getText());
  }

  public static void assertLabelText(
     JPanel panel, String name, String expected) {
   JLabel label = SwingUtil.getLabel(panel, name);
   Assert.assertEquals(expected, label.getText());
  }
}

The utility classes and methods got there by virtue of relentless refactoring. The SwingUtil class initially got there by refactoring tests; its contents initially were in SwingTestUtil. Once we discovered that production code could reuse some of that code, we broke it out into its own class. SwingTestUtil is used only for testing, and as such doesn’t need tests. As a production class, SwingUtil does need tests. So we went back and covered all its behavior with a body of unit tests (refer to Listing 11, SwingUtilTest).

Each resulting class is small. None of these classes knows anything about the domain—they presume that another class will pass along the information needed, in as direct a form as needed. The SeatPanel doesn’t know anything about a Player object; it knows only of a String that represent a name it should display.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020