Domanda

I'm in the midst of my first independent Java project, and I have a limited knowledge of all the libraries at my disposal, but feel pretty comfortable with the language. This project requires a GUI interface with a JTextArea that displays instructions for user guidance on the left side, and a JPanel with some buttons on the right side. On my panel, I want to include a component with a simple drawing -- say, three rectangles of different sizes and different colors -- and add different actionListeners to each rectangle. How should I start implementing this? What kind of component can I add to my JPanel that will allow me to achieve this?

Any advice is greatly appreciated.

È stato utile?

Soluzione

You could display Shape objects such as Rectangle2D, among others, in the paintComponent(...) method of a JPanel, and then identify clicks to the Shapes by adding a MouseListener to the JPanel. If you're going to be sizing various shapes, I wouldn't use a JButton or something similar, but just a single MouseListener or MouseAdapter added to a single drawing JPanel. Shape has a contains(Point p) method that you can use to see if any of the Shapes have been clicked.

Specifically:

On my panel, I want to include a component with a simple drawing -- say, three rectangles of different sizes and different colors

Three Rectangle2D objects can fit this bill, declared in the class that extends JPanel and drawn in that JPanel's paintComponent(Graphics g) method. You will need to cast the Graphics object to Graphics2D, and then you can draw the Rectangle2D objects by calling draw(myRectangle) and fill them with different color by setting the Graphics color prior to drawing and then call fill(myRectangle)

and add different actionListeners to each rectangle.

Again, I'd use a single MouseListener added to the JPanel. You can find out which Rectangle2D was clicked by calling contains(Point p) with the Point given to you in the MouseListener mousePressed methods MouseEvent object.

For more on this, check out:

Altri suggerimenti

You could use JButtons as your rectangles. This makes action handling easy.

http://docs.oracle.com/javase/tutorial/uiswing/components/button.html

if you want to ad different actionListeners -> use JButtons. but you must to change it's view.

All methods, that you can use are here: http://docs.oracle.com/javase/7/docs/api/javax/swing/AbstractButton.html and here http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#setBackground(java.awt.Color)

What kind of component can I add to my JPanel that will allow me to achieve this?

The JDK doesn't have one, but you can check out Playing With Shapes and maybe use the ShapeComponent, then you can just add a MouseListener to each component.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top