Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of

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.

  • + Share This
  • 🔖 Save To Your Account