Advertisement
jdalbey

Swing Grid GUI Demo

Oct 4th, 2014
722
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.61 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 menu, 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, except a few random cells that contain grapes.
  15.  *   Right-clicking on a cell reveals a lilly.
  16.  *   The move counter on the status bar increases with each click.
  17. * @author jdalbey
  18. * @version 2014.10.4
  19. */
  20. public class GUIDemo extends JFrame
  21. {
  22.     /* Main components of the GUI */
  23.     // DO NOT CHANGE THE FOLLOWING THREE LINES
  24.     private JTable table;
  25.     private JLabel myStatus = null;
  26.     private JMenuBar menuBar;
  27.     // The underlying data model
  28.     private Object[][] myBoard;
  29.     private String[] columns = {"", "", "", "", "", "", "", "", "", "", };
  30.     private int clickCount;  // Counter for mouse clicks
  31.     // The images to be displayed
  32.     private ImageIcon rose, grapes, lilly, background;
  33.     /* Image dimensions, in pixels */
  34.     private int kImageWidth = 65;
  35.     private int kImageHeight = 43;
  36.  
  37.     /** Create a GUI.
  38.      *  Will use the System Look and Feel when possible.
  39.      */
  40.     public GUIDemo()
  41.     {
  42.         super();
  43.         myBoard = new ImageIcon[10][10];
  44.         try
  45.         {
  46.             UIManager.setLookAndFeel(
  47.                 UIManager.getSystemLookAndFeelClassName());
  48.         }
  49.         catch (Exception ex)
  50.         {
  51.             System.err.println(ex);
  52.         }
  53.     }
  54.  
  55.  
  56.     /** Place all the Swing widgets in the frame of this GUI.
  57.      */
  58.     public void layoutGUI()
  59.     {
  60.         setTitle("Swing Grid Demo");
  61.         loadImages();
  62.         newGame();
  63.         table = new ImageJTable(myBoard, columns);
  64.        
  65.         // Define the layout manager that will control order of components
  66.         getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
  67.        
  68.         layoutMenus();
  69.        
  70.         // Create a panel for the status information
  71.         JPanel statusPane = new JPanel();
  72.         myStatus = new JLabel("###");
  73.         statusPane.add(myStatus);
  74.         statusPane.setAlignmentX(Component.CENTER_ALIGNMENT);
  75.         getContentPane().add(statusPane);
  76.  
  77.         /* Define the characteristics of the table that shows the game board    */
  78.         // Set the dimensions for each column in the board to match the image
  79.         for (int col = 0; col < 10; col++)
  80.         {
  81.             TableColumn column = table.getColumnModel().getColumn(col);
  82.             column.setMaxWidth(kImageWidth);
  83.             column.setMinWidth(kImageWidth);
  84.         }
  85.         // remove editor makes table not editable
  86.         table.setDefaultEditor(Object.class, null);  
  87.         // define how cell selection works
  88.         table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  89.         table.setCellSelectionEnabled(false);
  90.         // other miscellaneous settings
  91.         table.setRowHeight(kImageHeight);
  92.         table.setOpaque(false);
  93.         table.setShowGrid(false);
  94.         table.setAlignmentX(Component.CENTER_ALIGNMENT);
  95.         // Add a custom mouse listener that will handle player's clicks.
  96.         table.addMouseListener(myMouseListener);
  97.         // finally, add the table to the content pane
  98.         getContentPane().add(table);
  99.  
  100.         setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  101.     } // end layout GUI
  102.  
  103.     /* Setup the menubar and submenus */
  104.     private void layoutMenus()
  105.     {
  106.         menuBar = new javax.swing.JMenuBar();
  107.         JMenu mnuGame = new JMenu("Game");
  108.         menuBar.add(mnuGame);
  109.         JMenuItem mnuNew = new JMenuItem("New");
  110.         mnuNew.setMnemonic('N');
  111.         mnuNew.setAccelerator(
  112.                 KeyStroke.getKeyStroke('N', ActionEvent.ALT_MASK));
  113.         mnuNew.addActionListener(new ActionListener()
  114.         {
  115.         // Anonymous inner classes are used here for brevity, but should be
  116.         // named classes in production code.
  117.             public void actionPerformed(ActionEvent e)
  118.             {
  119.                 newGame();
  120.                 myStatus.setText("" + clickCount);
  121.                 repaint();                
  122.             }
  123.         });
  124.         mnuGame.add(mnuNew);
  125.        
  126.         JMenuItem mnuQuit = new JMenuItem("Quit");
  127.         mnuQuit.setMnemonic('Q');
  128.         mnuQuit.setAccelerator(
  129.                 KeyStroke.getKeyStroke('Q', ActionEvent.ALT_MASK));
  130.         mnuQuit.addActionListener(new ActionListener()
  131.         {
  132.             public void actionPerformed(ActionEvent e)
  133.             {
  134.                 dispose();
  135.             }
  136.         });
  137.         mnuGame.add(mnuQuit);
  138.         setJMenuBar(menuBar);        
  139.     } // end layout Menus
  140.  
  141.     /* Listener to respond to mouse clicks on the table */
  142.     private MouseAdapter myMouseListener = new MouseAdapter()
  143.     {
  144.         public void mouseReleased(MouseEvent ev)
  145.         {
  146.             // obtain the selected cell coordinates
  147.             int col = table.getSelectedColumn();
  148.             int row = table.getSelectedRow();
  149.             // Is it a right mouse click?
  150.             if (SwingUtilities.isRightMouseButton(ev))
  151.             {
  152.                 row = (int) (ev.getPoint().getY()/kImageHeight);
  153.                 col = (int) (ev.getPoint().getX()/kImageWidth);
  154.                 // Show special image
  155.                 myBoard[row][col] = lilly;
  156.             }
  157.             // left mouse click
  158.             else
  159.             {
  160.                 // Randomly decide to show grapes or nothing
  161.                 if (2 < (Math.random()*10))
  162.                 {
  163.                     myBoard[row][col] = null;
  164.                 }
  165.                 else
  166.                 {
  167.                     myBoard[row][col] = grapes;
  168.                 }
  169.                 clickCount++;
  170.                 myStatus.setText("" + clickCount);
  171.             }
  172.             repaint();
  173.         }
  174.     };  // end mouse listener
  175.  
  176.    
  177.     /* Load the images to be displayed */
  178.     private void loadImages()
  179.     {
  180.         // Only for the demo we load images from the internet, but it's
  181.         // really slow ... your app must load images from the Jar in
  182.         // which it's distributed, something like this:
  183.         // Toolkit.getDefaultToolkit().getImage(this.getClass()
  184.         //        .getResource("images/" + "bkgd.jpg")));
  185.         final String kSite = "http://i.imgur.com//";
  186.         try
  187.         {
  188.             Image one = ImageIO.read(new URL(kSite + "F4VnDdf.jpg"));
  189.             Image two = ImageIO.read(new URL(kSite + "vqHZWUZ.jpg"));
  190.             Image three = ImageIO.read(new URL(kSite + "nWpm4KG.jpg"));
  191.             Image four = ImageIO.read(new URL(kSite + "nORa16t.jpg"));
  192.             rose = new ImageIcon(one);
  193.             grapes = new ImageIcon(two);
  194.             lilly = new ImageIcon(three);
  195.             background = new ImageIcon(four);
  196.         }
  197.         catch (IOException ex)
  198.         {
  199.             System.out.println("Couldn't read images. No network connection?");
  200.         }
  201.     }
  202.  
  203.     /* Start a new game by putting new values in the board */
  204.     private void newGame()
  205.     {
  206.         Integer cellvalue = new Integer((int)(Math.random()*10));
  207.         // Initialize every row
  208.         for (int row = 0; row < 10; row++)
  209.         {
  210.             // Initialize every column
  211.             for (int col = 0; col < 10; col++)
  212.             {
  213.                 myBoard[row][col] = rose; //cellvalue;
  214.             }
  215.         }
  216.         clickCount = 0;
  217.  
  218.     }
  219.    
  220.     /** Our custom JTable has special features for displaying images and
  221.      *  a background.
  222.      */
  223.     private class ImageJTable extends JTable
  224.     {
  225.         public ImageJTable(Object[][] rowData, Object[] columnNames)
  226.         {
  227.             super(rowData, columnNames);
  228.         }
  229.         //  Tell JTable it should expect each column to contain IconImages,
  230.         //  and should select the corresponding renderer for displaying it.
  231.         public Class getColumnClass(int column)
  232.         {
  233.             return ImageIcon.class;
  234.         }
  235.         //  Allow the background to be displayed
  236.         public Component prepareRenderer(TableCellRenderer renderer, int row,
  237.                 int column)
  238.         {
  239.             Component component = super.prepareRenderer(renderer, row, column);
  240.             // We want renderer component to be
  241.             // transparent so background image is visible
  242.             if (component instanceof JComponent)
  243.             {
  244.                 ((JComponent) component).setOpaque(false);
  245.             }
  246.             return component;
  247.         }
  248.  
  249.         // Override paint so as to show the table background
  250.         public void paint(Graphics gfx)
  251.         {
  252.             // paint an image in the table background
  253.             if (background != null)
  254.             {
  255.                 gfx.drawImage(background.getImage(), 0, 0, null, null);
  256.             }
  257.             // Now let the paint do its usual work
  258.             super.paint(gfx);
  259.         }
  260.        
  261.     } // end ImageJTable
  262.  
  263.     /** Local main to launch the GUI.
  264.      * @param args command line arguments (none expected)
  265.      */
  266.     public static void main(String[] args)
  267.     {
  268.         // Create the GUI
  269.         GUIDemo frame = new GUIDemo();
  270.         frame.layoutGUI();   // do the layout of widgets
  271.                
  272.         // Make the GUI visible and available for user interaction
  273.         frame.pack();
  274.         frame.setVisible(true);
  275.     }
  276.    
  277. }  // end GUIDemo
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement