I am trying to make a simple game that will have squares of random size and color appear at a random location on the screen and you have to click on them. The more you click the higher your score.
I have everything working except, I have no idea how to make it so that when you click on a square it disappears.
Here is my rectangle code
g.fillRect(Cube.cubePosX, Cube.cubePosY, Cube.cubeSize, Cube.cubeSize);
The position, size, and color are already predetermined and randomly selected in another class file.
Suggestions:
Don't hard code the Rectangles that you're drawing.
Instead create a collection of Rectangles such as an ArrayList<Rectangle> that are drawn in a for loop in the paintComponent(...) method of your drawing JPanel.
Then you remove them from the ArrayList when the user clicks on them.
This would be done in a MouseListener and again uses a for loop,
but a key being that this loop iterates backwards. The reason for this is that the Rectangles on "top" of all the others are the last ones drawn. They should be the first ones removed if clicked on.
You would call repaint() on the drawing JPanel (or JComponent) after removing a Rectangle.
I am trying to make a simple game that will have squares of random size and color appear at a random location on the screen and you have to click on them
You can also use Swing components for this. See Playing With Shapes for more ideas. You would add a MouseListener to each component and you can just remove the component from the panel when it is clicked.
Even if you don't want to use components, you should still consider using a Shape so your game can have more shapes than just rectangles. In this case Howevercraft's suggestions would all apply.
You need to keep some kind of cache which tells you where these rectangles are.
You should use this cache to not only detect when they are clicked, but also to paint them.
Take a look at How to create a Mouse Listener for more details.
You make also find Rectangle of some use
Related
I create buttons using jlabels, so I can make a image into sort of a button. The only problem is, is that jlabels are square, therfore if i click somewhere within the square where the picture is not contained, it still runs the jlabel.MouseClickEvent. Is there any fix for this, or another component that i could use?
Ex. If i click this on the corner where the circle is not showing, but the square is still there, then the event fires.
Any fixes/different components to use? Thanks!
If you are just using simple Shapes for the images then you might be able to use the Shape Component found in Playing With Shapes.
The ShapeComponent will only respond to mouse events within the bounds of the Shape.
Otherwise the solution is to override the contains(...) method of your JLabel to check if the mouse point is in the bounds of your image, or in your case if the pixel at that location is not transparent.
I am working on a very simple mind mapping application, and I use a JPanel to draw the structure of the mind map on. The nodes of the mind map are circles, and if you write in a node, the structure expands in that direction. I put my JPanel in a JScrollPane, but my problem is, that I can only expand it downwards, or to the right, but it should be expandable to the left and upwards as well. When my JScrollPane should expand in "negative directions" so upwards or to the left, I tried calculating how many coordinates I shift, and than redrawing the whole graphic, changing the x and y coordinates of everything respectively. But it still did not work, it drew the part that is visible correctly, but then when I scrolled down, the rest of my drawing disappeared.
I hope there is a solution for this, because I've searched for hours and found nothing useful, and because I can't think of any other way to solve this. Thank you for your help! :)
When my JScrollPane should expand in "negative directions" so upwards or to the left
You can't have negative coordinates, so you need to translate all the indexes to positive values.
and if not, I resize the JPanel.
This is the key. You need to override the getPreferredSize(...) method of your custom panel to return the appropriate size of the panel after all nodes have been translated to positive values.
Then you invoke:
revalidate();
repaint();
on the panel to make sure the layout manager is invoked and the nodes are repainted.
I try to find the best way to make an image clickable with different action depending on the area you click. For now, my window display an EFTPOS (image found on google image) using :
getContentPane().add(new JPanelBackground("./img/background.png", "./img/eftposAboveBackground.png", this.getWidth(), this.getHeight()));
Now, I would like to click on every EFTPOS's buttons. I was thinking of create some transparent buttons at the buttons's positions but :
First, I don't want to use an absolute layer
Second, the Swing GUI design editor (Netbeans) doesn't display my background image since I used the code above.
I'm pretty sure there is another way than setting my eftpos on the background, maybe using the ImageIcon class..
Any help would be greatly appreciated!
You can to create an ArrayList of Rectangles (or Shapes) to represent the area of each button on the image.
You need to add a MouseListener to the image.
In the mousePressed() event you need to iterate through all the Rectangle in the ArrayList using the Rectangle.contains(mouse point) method to see if the user clicked in a Rectangle.
When you find the Rectangle that was clicked you execute your custom code.
I'm working on a project where I am displaying a square and a circle.
The circle moves on its own, but the user moves the square via the arrow keys. Whenever the circle touches the square, it rebounds.
Square and circle are different classes (2 different panels). I want to add those two to a frame, one on top of the other such that both are visible.
Can someone tell me how to do so?
JFrame n = new JFrame();
n.setTitle("Background Color for JFrame");
n.setSize(1000,600);
n.setLocationRelativeTo(null);
n.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
n.setResizable(false);
n.add(new Ball());
n.add(new Team());
n.setVisible(true);
User interface components at the same level in a hierarchy are assumed to be non-overlapping by default. You can explicitly work around this by making your components transparent with setOpaque(false), assuming you are taking care to only draw whats needed in the components, e.g. in case of a JPanel ensure that its background is not drawn. Its still somewhat random (implementation dependent) which component has precendence over another when doing this.
There is a component explicitly designed for that: JLayeredPane (https://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html), which manages "layers" in which components can be put, giving you full control which overlays which.
Games often implement this by themselves, since the full features of JComponent are not needed to represent a simple graphical element. In that case a single component is used as a "canvas" to paint self-defined objects onto making use of an override of paintComponent (See: https://docs.oracle.com/javase/tutorial/uiswing/painting/)
If you want to do this in swing, as it sounds, I would really recommend making a new class that extends JPanel, and override it's paintComponent method. In this method you use the Graphics in the argument to paint to the canvas. Then you can add this custom panel instead of two separate components to your JFrame, and handle the rendering in there. This render panel can then keep track of all objects that needs to be rendered, preferable implementing some interface (Drawable?) with a draw(Graphics g) method. That way you can make your classes that needs to be rendered implement your Drawable interface, keep then as a list in your render panel and just iterate through them in your paintComponent method and call draw on your Drawables.
I have a JPanel that contains a bunch of Swing JComponents, including some JSeparators that may be only one or two pixels wide. I want to let my users drag the items around, but it can be rather difficult to hit a one or two pixel wide line. Is there a way that I can give those JSeparators a wider "target" region for mouse clicks? The only thing I've been able to think of is to have my mouse handler listen for clicks on the JPanel, and if it gets any, run through the list of JSeparators, looking to see if any of them are within a couple of pixels of the mouse click.
Should that work? Is there a better way?
Add a fat EmptyBorder to the component.
If it already has a border, you can set a compound border using the current border then the empty border, or simpler, add the empty border (and listener) to a panel that contains the component. The latter will work better for components such as JButton, which have borders that change according to state and focus.