Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import javax.swing.table.*;
- import java.awt.*;
- import java.awt.event.*;
- import java.io.*;
- import java.net.*;
- import javax.imageio.ImageIO;
- /** Skeleton GUI for grid-based games.
- * GUI has a status area, and a 2d playing area.
- * The GUI will display the game and handle mouse clicks, dispatching
- * them to the appropriate button or cell of the board.
- * The game displays a 10x10 grid of rose images.
- * Clicking on a cell removes the rose and allows the background image
- * to show through.
- * The move counter on the status bar increases with each click.
- * @author jdalbey
- * @version 2015.10.8b
- */
- public final class JTableDemo extends JFrame
- {
- /* Main components of the GUI */
- private JTable table; // DO NOT CHANGE THIS LINE
- private JLabel status; // DO NOT CHANGE THIS LINE
- // The underlying data model - AbstractTableModel would be better
- private Object[][] myBoard;
- private String[] columns = {"", "", "", "", "", "", "", "", "", "", };
- private int clickCount; // Counter for mouse clicks
- // The images to be displayed
- private ImageIcon background;
- private Piece rose;
- /* Image dimensions, in pixels */
- public final static int kImageWidth = 65;
- public final static int kImageHeight = 43;
- public final static int kGridSize = 10;
- /** Create the demo.
- */
- public JTableDemo()
- {
- super();
- myBoard = new Piece[kGridSize][kGridSize];
- }
- /** Place all the Swing widgets in the frame of this GUI.
- */
- public void layoutGUI()
- {
- setTitle("Swing JTable Demo");
- loadImages();
- newGame();
- table = new ImageJTable(myBoard, columns);
- // Define the layout manager that will control order of components
- getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
- // Create a panel for the status information
- JPanel statusPane = new JPanel();
- status = new JLabel("###");
- status.setName("status"); // DO NOT CHANGE THIS LINE
- statusPane.add(status);
- statusPane.setAlignmentX(Component.CENTER_ALIGNMENT);
- getContentPane().add(statusPane);
- /* Define the characteristics of the table that shows the game board */
- // Set the dimensions for each column in the board to match the image
- for (int col = 0; col < kGridSize; col++)
- {
- TableColumn column = table.getColumnModel().getColumn(col);
- column.setMaxWidth(kImageWidth);
- column.setMinWidth(kImageWidth);
- }
- // remove editor makes table not editable
- table.setDefaultEditor(Object.class, null);
- // define how cell selection works
- table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- table.setCellSelectionEnabled(false);
- // other miscellaneous settings
- table.setName("table"); // DO NOT CHANGE THIS LINE
- // Read "How to use Tables" in Java Swing Tutorial
- table.setDefaultRenderer(Renderable.class, new PieceRenderer());
- table.setRowHeight(kImageHeight);
- table.setOpaque(false);
- table.setShowGrid(false);
- table.setAlignmentX(Component.CENTER_ALIGNMENT);
- // Add a custom mouse listener that will handle player's clicks.
- table.addMouseListener(myMouseListener);
- // finally, add the table to the content pane
- getContentPane().add(table);
- pack();
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- } // end layout GUI
- /* Listener to respond to mouse clicks on the table */
- private MouseAdapter myMouseListener = new MouseAdapter()
- {
- public void mouseReleased(MouseEvent ev)
- {
- // obtain the selected cell coordinates
- int col = table.getSelectedColumn();
- int row = table.getSelectedRow();
- // left mouse click
- myBoard[row][col] = null;
- clickCount++;
- // update the status bar
- status.setText("" + clickCount);
- repaint();
- }
- }; // end mouse listener
- /* Load the images to be displayed */
- private void loadImages()
- {
- // Only for the demo we load images from the internet, but it's
- // really s l o w ... your app must load images from the Jar in
- // which it's distributed, something like this:
- // Toolkit.getDefaultToolkit().getImage(this.getClass()
- // .getResource("images/" + "bkgd.jpg")));
- final String kSite = "http://i.imgur.com//";
- try
- {
- Image roseimg = ImageIO.read(new URL(kSite + "F4VnDdf.jpg"));
- Image back = ImageIO.read(new URL(kSite + "nORa16t.jpg"));
- // Create a piece, assigning it the symbol "O"
- rose = new Piece("O", new ImageIcon(roseimg));
- background = new ImageIcon(back);
- }
- catch (IOException ex)
- {
- System.out.println("Couldn't read images. No network connection?");
- }
- }
- /* Start a new game by putting new values in the board */
- private final void newGame()
- {
- // Initialize every row
- for (int row = 0; row < kGridSize; row++)
- {
- // Initialize every column
- for (int col = 0; col < kGridSize; col++)
- {
- myBoard[row][col] = rose; //cellvalue;
- }
- }
- clickCount = 0;
- }
- /** Our custom JTable has special features for displaying images and
- * a background.
- */
- private class ImageJTable extends JTable
- {
- public ImageJTable(Object[][] rowData, Object[] columnNames)
- {
- super(rowData, columnNames);
- }
- // Tell JTable it should expect each column to contain Renderable things,
- // and should select the corresponding renderer for displaying it.
- public Class getColumnClass(int column)
- {
- return Renderable.class;
- }
- // Allow the background to be displayed
- public Component prepareRenderer(TableCellRenderer renderer, int row,
- int column)
- {
- Component component = super.prepareRenderer(renderer, row, column);
- // We want renderer component to be
- // transparent so background image is visible
- if (component instanceof JComponent)
- {
- ((JComponent) component).setOpaque(false);
- }
- return component;
- }
- // Override paint so as to show the table background
- public void paint(Graphics gfx)
- {
- // paint an image in the table background
- if (background != null)
- {
- gfx.drawImage(background.getImage(), 0, 0, null, null);
- }
- // Now let the paint do its usual work
- super.paint(gfx);
- }
- } // end ImageJTable
- /** Local main to launch the GUI.
- * @param args command line arguments (none expected)
- */
- public static void main(String[] args)
- {
- // Create the GUI
- JTableDemo frame = new JTableDemo();
- frame.layoutGUI(); // do the layout of widgets
- // Make the GUI visible and available for user interaction
- frame.pack();
- frame.setVisible(true);
- }
- } // end JTableDemo
- /** A piece occupying a cell in the table. */
- final class Piece implements Renderable
- {
- // It's a bad idea to keep the image in the piece
- private ImageIcon piece; // the image for this piece
- private String symbol; // the symbol for ths piece
- public Piece(String symbol, ImageIcon img)
- {
- this.symbol = symbol;
- this.piece = img;
- }
- @Override
- public String getText() { return symbol; }
- @Override
- public String toString() { return symbol; }
- /** Return the icon for this piece */
- // Yuck, find a better way to associate the image with the piece
- ImageIcon getIcon() { return piece; }
- }
- /** A cell renderer for the cells on the game board.
- * Read "How to use Tables" in the Java Swing Tutorial.
- */
- final class PieceRenderer extends DefaultTableCellRenderer
- {
- /** Construct a CellRenderer that will use the images specified. */
- public PieceRenderer() { super(); }
- /** Set the value to be displayed in the JTable for the given cell.
- * @param cell a Piece instance
- * @throws ClassCastException If cell is not an instance of Piece.
- */
- @Override
- public void setValue(Object cell)
- {
- setHorizontalAlignment(CENTER);
- setIcon(null);
- setText(null); // default case
- // Error check for null cells
- if (cell != null)
- {
- Piece piece = (Piece) cell;
- // Yuck, this is ugly, shouldn't store the icon in the piece
- // Should get the icon some other way
- setIcon(piece.getIcon());
- }
- } // end setValue
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement