Page 2 of 3 FirstFirst 123 LastLast
Results 21 to 40 of 46
Like Tree1Likes

Thread: Is it possible to get the covered area of an object?

  1. #21
    jiffi is offline Member
    Join Date
    Oct 2011
    Posts
    79
    Rep Power
    0

    Default Re: Is it possible to get the covered area of an object?

    well here is the full code that i have right now. Please don't pay attention to how the code is written or anything, this is just like a very rough draft of what i'm trying to do.

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    
    public class GUI extends JFrame implements ActionListener
    {
    
        
        public static final int FRAME_WIDTH = 700;
        public static final int FRAME_HEIGHT = 500;
        public static final int buttonW = 30;
        public static final int buttonH = 30;
    
        public static final int maxSquare = 10;
    
        public Container contentPane;
    
        public JLabel background;
        public JLayeredPane [] shipBackground = new JLayeredPane[2];
    
        public JButton [][] squareButton = new JButton [maxSquare][maxSquare]; 
        public JLabel [][] squareLabel = new JLabel [maxSquare][maxSquare]; 
    
        public Border lineD;
        public Border lineL;
        public Border lineDL;
        int x = 0;
        public GUI()
        {
            setSize(FRAME_WIDTH,FRAME_HEIGHT);
            setLocationRelativeTo(null);
            setResizable(false);
            setVisible(true);
            setTitle("Battleship");
    
            contentPane = getContentPane();
            contentPane.setBackground(Color.white);
            contentPane.setLayout(null);
    
            lineD = BorderFactory.createMatteBorder(1,0,1,0,Color.black);//used to make the borders of the squareLabels
            lineL = BorderFactory.createMatteBorder(0,1,0,1,Color.black);
            lineDL = BorderFactory.createCompoundBorder(lineD,lineL);
    
            background = new JLabel();//background of the frame
            background.setBounds(2, 2, FRAME_WIDTH, FRAME_HEIGHT);
            background.setVisible(true);
            contentPane.add(background);
    
            shipBackground[0] = new JLayeredPane();//holds the boats and labels for the user's boats
            shipBackground[0].setBounds(25,75,302,302);
            shipBackground[0].setBorder(lineDL);
            background.add(shipBackground[0]);
    
                for (int c = 0; c<squareButton.length;c++)//create and place the buttons & labels 
                {
                    for (int l = 0; l<squareButton[c].length;l++)
                    {
                        squareButton[c][l] = new JButton();
                        squareButton[c][l].setBounds(2+l*30,2+c*30, buttonW-2, buttonH-2);
                        squareButton[c][l].addActionListener(this);
    
                        squareLabel[c][l] = new JLabel();
                        squareLabel[c][l].setBounds(1 + l*30, 1 + c*30, buttonW, buttonH);
                        shipBackground[0].add(squareLabel[c][l]);
                        shipBackground[0].add(squareButton[c][l]);
    
                        squareLabel[c][l].setBorder(lineDL);
                    }
                }
            }
        
    
        public void actionPerformed(ActionEvent event)
        {
            JButton source;
            source = (JButton)event.getSource();
            
            if (x == 0)
            {
                JLabel image = new JLabel ();//JLabel that will hold the boats
                image.setBounds(source.getX(),source.getY(), source.getWidth() *4, source.getHeight());//place it at the 
                image.setIcon(new ImageIcon("size4.png"));                                                //location of the pressed button
                shipBackground[0].add(image);
                shipBackground[0].moveToFront(image);//move the image to the front
                x = 1;
    
            }
            if (shipBackground[0].getComponentAt(source.getX(),source.getY()) == image)
            {//test the method getComponentAt with the origins of the source button.
             //should return true if the button used to put the image above is pressed again later, but doesn't. 
                System.out.println("found");
            }
        }
    
        public static void main (String [] args)
        {
            GUI gui = new GUI();
        }
    }
    Last edited by jiffi; 01-14-2012 at 12:49 AM.

  2. #22
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Is it possible to get the covered area of an object?

    Can you describe what each part of the code is supposed to do and what your overall goal with this bit of code is? Also we have no access yet to any images that you're using.

  3. #23
    jiffi is offline Member
    Join Date
    Oct 2011
    Posts
    79
    Rep Power
    0

    Default Re: Is it possible to get the covered area of an object?

    I added a few comments. This is just a TEST, I am trying out solutions for my program that will be a battleship. There are no specific goals for this class right now.

    for the images, anything will do it doesn't matter, it is not part of the problem (mine is a totally random image).

    Sorry never mind, I just solved the problem it was something really stupid.

    The JLabel was declared inside the actionperformed and a new one was declared everytime, with different bounds. Sorry for all this
    Last edited by jiffi; 01-14-2012 at 01:32 AM. Reason: solution found

  4. #24
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Is it possible to get the covered area of an object?

    Hm, I'll try to look at the code in a bit.

    I'm posting an unfinished program that demonstrates use of JLabels held in a JPanel that uses GridLayout. If you download the file, called BattleGrid.zip, change the extension to jar so that the new name is BattleGrid.jar, and then run it. If your system is set up correctly, a jar file can run simply by double clicking it. To see what it does, click on a cell, then with the mouse still down, drag the cursor to another cell that is either in the same row as the original cell or the same column, and release the mouse. Try this a couple of times, and then click on one of the images (no dragging this time) to change the icon. Let me know if any of these ideas are what you're looking for.

    The running program looks like this: Is it possible to get the covered area of an object?-battle-grid.jpg

    I'm not going to post the source code (not now anyway) as I don't want to dissuade you from creating your own source.
    Attached Files Attached Files

  5. #25
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Is it possible to get the covered area of an object?

    Quote Originally Posted by jiffi View Post
    Sorry never mind, I just solved the problem it was something really stupid.

    The JLabel was declared inside the actionperformed and a new one was declared everytime, with different bounds. Sorry for all this
    Oops, well, it wasn't a waste of time for me since I learned a bit myself. Glad you've got it sorted, and best of luck.

  6. #26
    jiffi is offline Member
    Join Date
    Oct 2011
    Posts
    79
    Rep Power
    0

    Default Re: Is it possible to get the covered area of an object?

    I am still interested in learning how you managed to do yours, mostly because it looks much simpler than mine.
    I can't run your program though, I have a mac and it decompresses the file automatically so it ends up in a folder, and renaming that folder with .jar doesn't do anything. is there any other way you can send the file?

  7. #27
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Is it possible to get the covered area of an object?

    Yeah, here's the jar file inside of a zip file.
    Attached Files Attached Files

  8. #28
    jiffi is offline Member
    Join Date
    Oct 2011
    Posts
    79
    Rep Power
    0

    Default Re: Is it possible to get the covered area of an object?

    this is what I have so far. Don't pay attention to the source code too much it is really badly organized. Only the right frame works for now, so you can just place and destroy your own boats.
    the delete button also doesn't work yet.
    Attached Files Attached Files

  9. #29
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Is it possible to get the covered area of an object?

    I've gone through a little of your code. I think you'll want to have less inheritance since most of it is unnecessary and actually somewhat confusing. By the way, is this for a homework assignment? Oh, and nice background images by the way.

  10. #30
    jiffi is offline Member
    Join Date
    Oct 2011
    Posts
    79
    Rep Power
    0

    Default Re: Is it possible to get the covered area of an object?

    The inheritance is mostly for me, when my code is done I usually put the stuff back together. I can more easily know where the mistake comes from, and it is much easier going through 100 or 200 lines then 700-800.

    This is not for homework, my computer classes ended in december for this year. I write the programs to challenge myself, and to learn (the logic mostly, not the language) as I might want to pursue something similar as a career.
    (This is actually more of a way for me to learn how to make the AI, my teacher challenged me to make a tic tac toe and I thought making the AI for a battleship first would help me understand the logic behind it before making the AI in the tic tac toe which is more complex).

    Image creds go to Google Images and preview for mac.

    Did you try the game though? how is it?

  11. #31
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Is it possible to get the covered area of an object?

    I sort of tried it. I ran the GUI class, but couldn't really get it to work other than to show the grids and background images.

  12. #32
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Is it possible to get the covered area of an object?

    Quote Originally Posted by jiffi View Post
    The inheritance is mostly for me, when my code is done I usually put the stuff back together. I can more easily know where the mistake comes from, and it is much easier going through 100 or 200 lines then 700-800.
    That's solved by subdividing logical entities into separate classes (encapsulation), not by inheritance.

  13. #33
    jiffi is offline Member
    Join Date
    Oct 2011
    Posts
    79
    Rep Power
    0

    Default Re: Is it possible to get the covered area of an object?

    Quote Originally Posted by Fubarable View Post
    I sort of tried it. I ran the GUI class, but couldn't really get it to work other than to show the grids and background images.
    That's odd. It works perfectly fine for me. What are you doing exactly?

    Quote Originally Posted by Fubarable View Post
    That's solved by subdividing logical entities into separate classes (encapsulation), not by inheritance.
    I just learned something new. Thanks i'll try that.

  14. #34
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Is it possible to get the covered area of an object?

    Quote Originally Posted by jiffi View Post
    That's odd. It works perfectly fine for me. What are you doing exactly?
    First of all, was your file original a jar file that was changed into a zip? I tried to convert it into a jar and run it, but it would not run. I then copied the .java files and the images into Eclipse, made some changes to the .java files to declare their current directory, and made changes to the GUI.java class so that it would obtain its images as resources with proper resource paths. I then ran the GUI class.

  15. #35
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Is it possible to get the covered area of an object?

    Going through more code...

    Consider changing this:

    Java Code:
            for (int c = 0; c<squareButton.length;c++)
            {
                String letter = "";
                switch(c)
                {
                    case 0: letter = "A"; break;
                    case 1: letter = "B"; break;
                    case 2: letter = "C"; break;
                    case 3: letter = "D"; break;
                    case 4: letter = "E"; break;
                    case 5: letter = "F"; break;
                    case 6: letter = "G"; break;
                    case 7: letter = "H"; break;
                    case 8: letter = "I"; break;
                    case 9: letter = "J"; break;
    
                }
    to something a "little" more compact:

    Java Code:
          for (int c = 0; c < squareButton.length; c++) {
             String letter = String.valueOf((char)('A' + c));

  16. #36
    jiffi is offline Member
    Join Date
    Oct 2011
    Posts
    79
    Rep Power
    0

    Default Re: Is it possible to get the covered area of an object?

    it is not a .jar file, the images don't appear when I put it into a jar file so I didn't use jar. Download bluej then you just double click on the file name package.bluej once you unzip the file that should work. (or tell me how to include images in when you export it into jar files).

  17. #37
    jiffi is offline Member
    Join Date
    Oct 2011
    Posts
    79
    Rep Power
    0

    Default Re: Is it possible to get the covered area of an object?

    Quote Originally Posted by Fubarable View Post
    Going through more code...

    Consider changing this:

    Java Code:
            for (int c = 0; c<squareButton.length;c++)
            {
                String letter = "";
                switch(c)
                {
                    case 0: letter = "A"; break;
                    case 1: letter = "B"; break;
                    case 2: letter = "C"; break;
                    case 3: letter = "D"; break;
                    case 4: letter = "E"; break;
                    case 5: letter = "F"; break;
                    case 6: letter = "G"; break;
                    case 7: letter = "H"; break;
                    case 8: letter = "I"; break;
                    case 9: letter = "J"; break;
    
                }
    to something a "little" more compact:

    Java Code:
          for (int c = 0; c < squareButton.length; c++) {
             String letter = String.valueOf((char)('A' + c));
    I did not know you could do that. Thanks

  18. #38
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Is it possible to get the covered area of an object?

    Some more suggestions:

    • Again, don't do inheritance like you're doing, and in fact squash your current inheritance hierarchy.
    • Rather than having an array of two JLayeredPanes, two JLabel arrays, two JButton grids, create a class Just for the grid-panel, and in your main GUI, have and display two of these grid panel objects.
    • Get all images as program resources, not as files; otherwise your images will be unretrievable when you try to jar this program (which is one reason that I've had a great deal of difficulty getting parts of your code to run for me).
    • Consider having a HashMap<String, ImageIcon> hold your image icons. Then you can get the desired icon by using a simple String.
    • I wouldn't put any JButtons on the grid, but instead use a MouseListener to listen for mouse presses on the grid.

  19. #39
    jiffi is offline Member
    Join Date
    Oct 2011
    Posts
    79
    Rep Power
    0

    Default Re: Is it possible to get the covered area of an object?

    Quote Originally Posted by Fubarable View Post
    Some more suggestions:

    • Again, don't do inheritance like you're doing, and in fact squash your current inheritance hierarchy.
    I will try to change that.
    Quote Originally Posted by Fubarable View Post
    • Rather than having an array of two JLayeredPanes, two JLabel arrays, two JButton grids, create a class Just for the grid-panel, and in your main GUI, have and display two of these grid panel objects.
    So how would that work? Through parameter passing?
    Quote Originally Posted by Fubarable View Post
    • Get all images as program resources, not as files; otherwise your images will be unretrievable when you try to jar this program (which is one reason that I've had a great deal of difficulty getting parts of your code to run for me).
    • Consider having a HashMap<String, ImageIcon> hold your image icons. Then you can get the desired icon by using a simple String.
    I have literally no idea how to do neither of those. I'll try to look it up later (although I already tried to understand HashMap and wasn't successful ).
    Quote Originally Posted by Fubarable View Post
    • I wouldn't put any JButtons on the grid, but instead use a MouseListener to listen for mouse presses on the grid.
    It seems a little more complicated to me than using a JButton. I would add a mouse listener to every JLabel right?

  20. #40
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Is it possible to get the covered area of an object?

    Latest iteration....

    Class BattleShipGridPanel.java
    Java Code:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.GridLayout;
    import java.awt.Image;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class BattleShipGridPanel extends JPanel {
       public static final String MOUSE_PRESSED = "Mouse Pressed";
       // public static final String MOUSE_DRAGGED = "Mouse Dragged";
       private static final int ROW_COUNT = 11;
       private static final int COL_COUNT = 11;
       private Image img = null;
       private String selectedCellName = "";
       private JLabel selectedLabel = null;
       private Map<String, JLabel> labelMap = new HashMap<String, JLabel>();
    
       public BattleShipGridPanel(Image img, int cellSideLength) {
          this.img = img;
          setLayout(new GridLayout(11, 11));
          setBorder(BorderFactory.createLineBorder(Color.black));
          
          MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
          addMouseListener(myMouseAdapter);
    
          for (int row = 0; row < ROW_COUNT; row++) {
             for (int col = 0; col < COL_COUNT; col++) {
                String rowStr = String.valueOf((char) ('A' + row - 1));
                String colStr = String.valueOf(col);
                String name = ""; // name for component
                String text = ""; // text to display
    
                // create JLabel to add to grid
                JLabel label = new JLabel("", SwingConstants.CENTER);
    
                // text to display if label is a row header at col 0
                if (col == 0 && row != 0) {
                   text = "" + rowStr;
                } else
    
                // text to display if label is a col header at row 0
                if (row == 0 && col != 0) {
                   text = "" + colStr;
                } else
    
                // name to give to label if label is on the grid and not a
                // row or col header
                if (row != 0 && col != 0) {
                   name = rowStr + " " + colStr;
                   labelMap.put(name, label);
                }
                label.setText(text);
                label.setName(name);
                label.setPreferredSize(new Dimension(cellSideLength, cellSideLength));
                label.setBorder(BorderFactory.createLineBorder(Color.black));
                add(label);
             }
          }
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          if (img != null) {
             int w0 = getWidth();
             int h0 = getHeight();
             int x = w0 / 11;
             int y = h0 / 11;
    
             int iW = img.getWidth(null);
             int iH = img.getHeight(null);
    
             g.drawImage(img, x, y, w0, h0, 0, 0, iW, iH, null);
          }
       }
    
       private class MyMouseAdapter extends MouseAdapter {
          @Override
          public void mousePressed(MouseEvent mEvt) {
             if (mEvt.getButton() == MouseEvent.BUTTON1) {
                Component comp = getComponentAt(mEvt.getPoint());
                if (comp instanceof JLabel) {
                   String name = comp.getName();
                   if (!name.trim().isEmpty()) {
                      String oldValue = selectedCellName;
                      String newValue = name;
                      selectedCellName = name;
                      selectedLabel = (JLabel) comp;
                      firePropertyChange(MOUSE_PRESSED, oldValue, newValue);
                   }
                }
             }
          }
       }
    
       public String getSelectedCellName() {
          return selectedCellName;
       }
    
       public JLabel getSelectedLabel() {
          return selectedLabel;
       }
    
       public void resetSelections() {
          selectedCellName = "";
          selectedLabel = null;
       }
    
       public JLabel getLabel(String key) {
          return labelMap.get(key);
       }
       
       public void resetAll() {
          resetSelections();
          for (String key : labelMap.keySet()) {
             labelMap.get(key).setIcon(null);
          }
       }
    
    }

    BattleShipMainPanel.java

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Font;
    import java.awt.image.BufferedImage;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    
    public class BattleShipMainPanel extends JPanel {
       private static final int TA_ROWS = 10;
       private static final int TA_COLS = 30;
       private static final int CELL_SIDE_LENGTH = 40;
       private BattleShipGridPanel playerGrid;
       private BattleShipGridPanel opponentGrid;
       private JTextArea textarea = new JTextArea(TA_ROWS, TA_COLS);
       
       public BattleShipMainPanel() throws IOException {
          String westImgString = "images/Wallpaper-Picture-Under-Water Crp.jpg";
          String eastImgString = "images/Maldives_Sml.jpg";
          BufferedImage westImg = ImageIO.read(getClass().getResource(westImgString));
          BufferedImage eastImg = ImageIO.read(getClass().getResource(eastImgString));      
          
          playerGrid = new BattleShipGridPanel(westImg, CELL_SIDE_LENGTH);
          opponentGrid = new BattleShipGridPanel(eastImg, CELL_SIDE_LENGTH);
               
          playerGrid.addPropertyChangeListener(new PropertyChangeListener() {
    
             @Override
             public void propertyChange(PropertyChangeEvent pChngEvt) {
                if (pChngEvt.getPropertyName().equals(
                      BattleShipGridPanel.MOUSE_PRESSED)) {
                   textarea.append("Player: " + pChngEvt.getNewValue() + "\n");
                   playerGrid.resetSelections();
                }
             }
          });
          
          opponentGrid.addPropertyChangeListener(new PropertyChangeListener() {
    
             @Override
             public void propertyChange(PropertyChangeEvent pChngEvt) {
                if (pChngEvt.getPropertyName().equals(
                      BattleShipGridPanel.MOUSE_PRESSED)) {
                   textarea.append("Opponent: " + pChngEvt.getNewValue() + "\n");
                   opponentGrid.resetSelections();
                }
             }
          });
          
          textarea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
          textarea.setEditable(false);
          textarea.setFocusable(false);
          
          JPanel centerPanel = new JPanel();
          centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
          JPanel centerTopPanel = new JPanel(new BorderLayout());
          centerTopPanel.add(new JLabel("GridCell Pressed", SwingConstants.LEFT), 
                BorderLayout.NORTH);
          centerTopPanel.add(new JScrollPane(textarea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
          centerPanel.add(centerTopPanel);
          centerPanel.add(Box.createVerticalGlue());
          
          JPanel playerPanel = new JPanel(new BorderLayout());
          playerPanel.add(new JLabel("Player", JLabel.LEFT), BorderLayout.PAGE_START);
          playerPanel.add(playerGrid, BorderLayout.CENTER);
          
          JPanel opponentPanel = new JPanel(new BorderLayout());
          opponentPanel.add(new JLabel("Opponent", JLabel.LEFT), BorderLayout.PAGE_START);
          opponentPanel.add(opponentGrid, BorderLayout.CENTER);
          
          int eb = 10;
          setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
          setLayout(new BorderLayout(eb, eb));
          add(playerPanel, BorderLayout.WEST);
          add(opponentPanel, BorderLayout.EAST);
          add(centerPanel, BorderLayout.CENTER);
    
       }
    }

    BattleShipMainProg.java

    Java Code:
    import java.io.IOException;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    
    public class BattleShipMainProg {
       private static void createAndShowGui() {
          BattleShipMainPanel mainPanel;
          try {
             mainPanel = new BattleShipMainPanel();
             JFrame frame = new JFrame("Battleship");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.getContentPane().add(mainPanel);
             frame.pack();
             frame.setLocationByPlatform(true);
             frame.setVisible(true);
          } catch (IOException e) {
             e.printStackTrace();
          }
    
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    
    }
    Attached Files Attached Files

Page 2 of 3 FirstFirst 123 LastLast

Similar Threads

  1. Text Area
    By pabloma2002 in forum CLDC and MIDP
    Replies: 1
    Last Post: 02-11-2011, 05:56 PM
  2. Area Add
    By Java Tip in forum java.awt
    Replies: 0
    Last Post: 06-23-2008, 12:07 AM
  3. Area Subtract
    By Java Tip in forum java.awt
    Replies: 0
    Last Post: 06-23-2008, 12:07 AM
  4. Area Intersect
    By Java Tip in forum java.awt
    Replies: 0
    Last Post: 06-23-2008, 12:07 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •