Advertisement
jdalbey

Demo of JTable with background

Oct 6th, 2015
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 9.14 KB | None | 0 0
  1. import javax.swing.*;
  2. import javax.swing.table.*;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.io.*;
  6. import java.net.*;
  7. import javax.imageio.ImageIO;
  8. /**  Skeleton GUI for grid-based games.
  9.  *   GUI has a status area, and a 2d playing area.
  10.  *   The GUI will display the game and handle mouse clicks, dispatching
  11.  *   them to the appropriate button or cell of the board.
  12.  *   The game displays a 10x10 grid of rose images.
  13.  *   Clicking on a cell removes the rose and allows the background image
  14.  *   to show through.
  15.  *   The move counter on the status bar increases with each click.
  16.  * @author jdalbey
  17.  * @version 2015.10.8b
  18.  */
  19. public final class JTableDemo extends JFrame
  20. {
  21.     /* Main components of the GUI */
  22.     private JTable table; // DO NOT CHANGE THIS LINE
  23.     private JLabel status; // DO NOT CHANGE THIS LINE
  24.     // The underlying data model - AbstractTableModel would be better
  25.     private Object[][] myBoard;
  26.     private String[] columns = {"", "", "", "", "", "", "", "", "", "", };
  27.     private int clickCount;  // Counter for mouse clicks
  28.     // The images to be displayed
  29.     private ImageIcon background;
  30.     private Piece rose;
  31.     /* Image dimensions, in pixels */
  32.     public final static int kImageWidth = 65;
  33.     public final static int kImageHeight = 43;
  34.     public final static int kGridSize = 10;
  35.  
  36.     /** Create the demo.
  37.      */
  38.     public JTableDemo()
  39.     {
  40.         super();
  41.         myBoard = new Piece[kGridSize][kGridSize];
  42.     }
  43.  
  44.     /** Place all the Swing widgets in the frame of this GUI.
  45.      */
  46.     public void layoutGUI()
  47.     {
  48.         setTitle("Swing JTable Demo");
  49.         loadImages();
  50.         newGame();
  51.         table = new ImageJTable(myBoard, columns);
  52.  
  53.         // Define the layout manager that will control order of components
  54.         getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
  55.  
  56.         // Create a panel for the status information
  57.         JPanel statusPane = new JPanel();
  58.         status = new JLabel("###");
  59.         status.setName("status");  // DO NOT CHANGE THIS LINE      
  60.         statusPane.add(status);
  61.         statusPane.setAlignmentX(Component.CENTER_ALIGNMENT);
  62.         getContentPane().add(statusPane);
  63.  
  64.         /* Define the characteristics of the table that shows the game board    */
  65.         // Set the dimensions for each column in the board to match the image
  66.         for (int col = 0; col < kGridSize; col++)
  67.         {
  68.             TableColumn column = table.getColumnModel().getColumn(col);
  69.             column.setMaxWidth(kImageWidth);
  70.             column.setMinWidth(kImageWidth);
  71.         }
  72.         // remove editor makes table not editable
  73.         table.setDefaultEditor(Object.class, null);  
  74.         // define how cell selection works
  75.         table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  76.         table.setCellSelectionEnabled(false);
  77.         // other miscellaneous settings
  78.         table.setName("table");  // DO NOT CHANGE THIS LINE      
  79.         // Read "How to use Tables" in Java Swing Tutorial
  80.         table.setDefaultRenderer(Renderable.class, new PieceRenderer());        
  81.         table.setRowHeight(kImageHeight);
  82.         table.setOpaque(false);
  83.         table.setShowGrid(false);
  84.         table.setAlignmentX(Component.CENTER_ALIGNMENT);
  85.         // Add a custom mouse listener that will handle player's clicks.
  86.         table.addMouseListener(myMouseListener);
  87.         // finally, add the table to the content pane
  88.         getContentPane().add(table);
  89.         pack();
  90.        
  91.         setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  92.     } // end layout GUI
  93.  
  94.     /* Listener to respond to mouse clicks on the table */
  95.     private MouseAdapter myMouseListener = new MouseAdapter()
  96.         {
  97.             public void mouseReleased(MouseEvent ev)
  98.             {
  99.                 // obtain the selected cell coordinates
  100.                 int col = table.getSelectedColumn();
  101.                 int row = table.getSelectedRow();
  102.                 // left mouse click
  103.                 myBoard[row][col] = null;
  104.                 clickCount++;
  105.                 // update the status bar
  106.                 status.setText("" + clickCount);
  107.  
  108.                 repaint();
  109.             }
  110.         };  // end mouse listener
  111.  
  112.     /* Load the images to be displayed */
  113.     private void loadImages()
  114.     {
  115.         // Only for the demo we load images from the internet, but it's
  116.         // really s l o w ... your app must load images from the Jar in
  117.         // which it's distributed, something like this:
  118.         // Toolkit.getDefaultToolkit().getImage(this.getClass()
  119.         //        .getResource("images/" + "bkgd.jpg")));
  120.         final String kSite = "http://i.imgur.com//";
  121.         try
  122.         {
  123.             Image roseimg = ImageIO.read(new URL(kSite + "F4VnDdf.jpg"));
  124.             Image back = ImageIO.read(new URL(kSite + "nORa16t.jpg"));
  125.             // Create a piece, assigning it the symbol "O"
  126.             rose = new Piece("O", new ImageIcon(roseimg));
  127.             background = new ImageIcon(back);
  128.         }
  129.         catch (IOException ex)
  130.         {
  131.             System.out.println("Couldn't read images. No network connection?");
  132.         }
  133.     }
  134.  
  135.     /* Start a new game by putting new values in the board */
  136.     private final void newGame()
  137.     {
  138.         // Initialize every row
  139.         for (int row = 0; row < kGridSize; row++)
  140.         {
  141.             // Initialize every column
  142.             for (int col = 0; col < kGridSize; col++)
  143.             {
  144.                 myBoard[row][col] = rose; //cellvalue;
  145.             }
  146.         }
  147.         clickCount = 0;
  148.  
  149.     }
  150.  
  151.     /** Our custom JTable has special features for displaying images and
  152.      *  a background.
  153.      */
  154.     private class ImageJTable extends JTable
  155.     {
  156.         public ImageJTable(Object[][] rowData, Object[] columnNames)
  157.         {
  158.             super(rowData, columnNames);
  159.         }
  160.         //  Tell JTable it should expect each column to contain Renderable things,
  161.         //  and should select the corresponding renderer for displaying it.
  162.         public Class getColumnClass(int column)
  163.         {
  164.             return Renderable.class;
  165.         }
  166.         //  Allow the background to be displayed
  167.         public Component prepareRenderer(TableCellRenderer renderer, int row,
  168.         int column)
  169.         {
  170.             Component component = super.prepareRenderer(renderer, row, column);
  171.             // We want renderer component to be
  172.             // transparent so background image is visible
  173.             if (component instanceof JComponent)
  174.             {
  175.                 ((JComponent) component).setOpaque(false);
  176.             }
  177.             return component;
  178.         }
  179.  
  180.         // Override paint so as to show the table background
  181.         public void paint(Graphics gfx)
  182.         {
  183.             // paint an image in the table background
  184.             if (background != null)
  185.             {
  186.                 gfx.drawImage(background.getImage(), 0, 0, null, null);
  187.             }
  188.             // Now let the paint do its usual work
  189.             super.paint(gfx);
  190.         }
  191.  
  192.     } // end ImageJTable
  193.  
  194.     /** Local main to launch the GUI.
  195.      * @param args command line arguments (none expected)
  196.      */
  197.     public static void main(String[] args)
  198.     {
  199.         // Create the GUI
  200.         JTableDemo frame = new JTableDemo();
  201.         frame.layoutGUI();   // do the layout of widgets
  202.  
  203.         // Make the GUI visible and available for user interaction
  204.         frame.pack();
  205.         frame.setVisible(true);
  206.     }
  207.  
  208.  
  209. }  // end JTableDemo
  210.  
  211. /** A piece occupying a cell in the table. */
  212. final class Piece implements Renderable
  213. {
  214.     // It's a bad idea to keep the image in the piece
  215.     private ImageIcon piece;  // the image for this piece
  216.     private String symbol; // the symbol for ths piece
  217.     public Piece(String symbol, ImageIcon img)
  218.     {
  219.         this.symbol = symbol;
  220.         this.piece = img;
  221.     }
  222.     @Override
  223.     public String getText() { return symbol; }
  224.     @Override
  225.     public String toString() { return symbol; }
  226.     /** Return the icon for this piece */
  227.     // Yuck, find a better way to associate the image with the piece
  228.     ImageIcon getIcon() { return piece; }
  229. }
  230.  
  231. /** A cell renderer for the cells on the game board.
  232.  *  Read "How to use Tables" in the Java Swing Tutorial.
  233.  */
  234. final class PieceRenderer extends DefaultTableCellRenderer
  235. {
  236.     /** Construct a CellRenderer that will use the images specified. */
  237.     public PieceRenderer()    { super(); }
  238.  
  239.     /** Set the value to be displayed in the JTable for the given cell.
  240.      * @param cell a Piece instance
  241.      * @throws ClassCastException If cell is not an instance of Piece.
  242.      */
  243.     @Override
  244.     public void setValue(Object cell)
  245.     {
  246.         setHorizontalAlignment(CENTER);
  247.         setIcon(null);
  248.         setText(null); // default case
  249.         // Error check for null cells
  250.         if (cell != null)
  251.         {
  252.             Piece piece = (Piece) cell;
  253.             // Yuck, this is ugly, shouldn't store the icon in the piece
  254.             // Should get the icon some other way
  255.             setIcon(piece.getIcon());  
  256.         }
  257.     } // end setValue
  258.  
  259. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement