JLabel Overlapping - java

I have created a label with overriding its paintComponent (to paint it in a different format with an arc) and located them on a panel. Everything worked fine, however the labels which are located in same location (by .setlocation) are creating problems.
Lets say I have 3 labels at the same location with different shapes. A-B-C
A is first created, then B is created and lastly c is created.
When I click on A, my function paints A and displays "youve clicked A"
But when I click on B or C, it acts like i have clicked on A.
(I'm adding labels in a panel stacked in scroll pane )
Here is the code where i make labels
for(int i=0;i<rowcount;i++){
arcstart = Rawazimuth(azimuth[i]);
//custom JLabel to paint it like an arc
MyLabel FLabel = new MyLabel(100, 50, (int)arcstart,cellid[i],lon[i],lat[i]);
FLabel.setOpaque(true);
Dimension LabelSize = new Dimension( 100,50);
FLabel.setSize(LabelSize);
//locate the JLabel to labels location. it might be same or not
FLabel.setLocation(lon[i], lat[i]);
MyPanel.add(FLabel);
}
this is my custom jlabel class
public MyLabel(int W, int H, int start,int outcellid,int lonn, int latt) {
addMouseListener(this);
arcsizeW = W;
arcsizeH = H;
arcstart = start;
cellid = outcellid;
clicked = false;
lon = lonn;
lat = latt;
}
#Override
public void paintComponent(Graphics g){
// true if button is clicked, so paint acordingly
if(clicked ==true){
g.setColor(dummyg.getColor());
}else{
g.setColor(Color.blue);
}
// draw the arc
g.fillArc(0, 0,arcsizeW , arcsizeH, arcstart, 60);
}
//if cell is clicked, change its color to red and print its cellid
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(cellid);
dummyg = this.getGraphics();
dummyg.setColor(Color.red);
this.paintComponent(dummyg);
clicked = true;
}// other listener stuff}
so how do i prevent this?
i think i can use jlayerpane, but i will need at least 4 layers ( dunno if its ok ).

Make sure you are calling super.paintComponent. This is important to ensure that the component is painting correcting.
Mouse events are like rain. They will hit the first component registered to receive mouse events and stop (like rain hitting an umbrella).
If you have components that overlap, where they overlap, the mouse events go to the first component registered to handle them (in this case A).
Here's a quick example to show what I mean...
As you hover over each circle, it will highlight, try hovering over the middle...
public class OverlappingMouseTest {
public static void main(String[] args) {
new OverlappingMouseTest();
}
public OverlappingMouseTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new BackgroundPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class BackgroundPane extends JLayeredPane {
private CirclePane redPane;
private CirclePane greenPane;
private CirclePane bluePane;
public BackgroundPane() {
redPane = new CirclePane(Color.RED);
greenPane = new CirclePane(Color.GREEN);
bluePane = new CirclePane(Color.BLUE);
add(redPane);
add(greenPane);
add(bluePane);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
public void doLayout() {
Dimension size = new Dimension(100, 100);
int width = getWidth() - 1;
int height = getHeight() - 1;
Point p = new Point();
p.x = (width / 2) - 50;
p.y = (height / 2) - 75;
redPane.setBounds(new Rectangle(p, size));
p.x = (width / 2) - 75;
p.y = (height / 2) - 25;
bluePane.setBounds(new Rectangle(p, size));
p.x = (width / 2) - 25;
p.y = (height / 2) - 25;
greenPane.setBounds(new Rectangle(p, size));
}
}
protected class CirclePane extends JPanel {
private boolean mouseHover = false;
public CirclePane(Color background) {
setOpaque(false);
setBackground(background);
addMouseListener(new MouseAdapter() {
#Override
public void mouseExited(MouseEvent me) {
mouseHover = false;
repaint();
}
#Override
public void mouseEntered(MouseEvent me) {
mouseHover = true;
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
#Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
Graphics2D g2d = (Graphics2D) grphcs.create();
if (!mouseHover) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
}
g2d.setColor(getBackground());
g2d.fill(new Ellipse2D.Float(0, 0, getWidth() - 1, getHeight() - 1));
g2d.dispose();
}
}
}

Everything worked fine, however the JLabel's which are located in same
location ( by .setlocation ) are creating problems.
Lets say i have 3 Jlabels at the same location with different shapes.
A-B-C A is first created, then B is created and lastly c is created.
there are tree ways, to use
JLayer (Java7), based on JXLayer (Java6)
OverlayLayout
JLayeredPane

I have solved my problem.
The real problem that i found was, Java is interpreting each component with their x,y location and width & height. So even if your label does not overlap ( graphically ) they can be interpreted as same component.
To solve my problem,
I found the angle between mouse click point and component center; then calculated the closest component and reached it.
Layers and such doesn't work in this situation, the only other way around is possibly overriding the contains method for the actualy shape.

Related

How is it possible to make an image follow the framesize in Java? [duplicate]

When a user clicks on the corner of a JFrame to resize and drags the mouse around, the JFrame redraws based on the current position of the mouse as the user drags. How can you listen to these events?
Below is the what I have currently tried:
public final class TestFrame extends JFrame {
public TestFrame() {
this.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
// This is only called when the user releases the mouse button.
System.out.println("componentResized");
}
});
}
// These methods do not appear to be called at all when a JFrame
// is being resized.
#Override
public void setSize(int width, int height) {
System.out.println("setSize");
}
#Override
public void setBounds(Rectangle r) {
System.out.println("setBounds A");
}
#Override
public void setBounds(int x, int y, int width, int height) {
System.out.println("setBounds B");
}
}
How can I determine and constrain how the user resizes a window (based on the current aspect ratio of the window) as they are dragging around the mouse around?
You can add a component listener and implement the componentResized function like that:
JFrame component = new JFrame("My Frame");
component.addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent evt) {
Component c = (Component)evt.getSource();
//........
}
});
EDIT: Apparently, for JFrame, the componentResized event is hooked to the mouseReleased event. That's why the method is invoked when the mouse button is released.
One way to achieve what you want, is to add a JPanel that will cover the whole area of your JFrame. Then add the componentListener to the JPanel (componentResized for JPanel is called even while your mouse is still dragging). When your frame is resized, your panel will also be resized too.
I know, this isn't the most elegant solution, but it works!
Another workaround (which is very similar to Alex's but a little more straightforward) is to listen to the events from the JFrame's root pane instead:
public final class TestFrame extends JFrame {
public TestFrame() {
this.getRootPane().addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
// This is only called when the user releases the mouse button.
System.out.println("componentResized");
}
});
}
}
Depending on other implementation details, it's possible that the root pane might be changed. If that's a possibility then you could override setRootPane() and deal with that. Since setRootPane() is protected and only called from the constructor though, it's unlikely you'll need to do that.
You probably need to override something like validate (don't forget to call the super). Of course, that still may not work if you are using a windowing system to configured to drag outlines.
public class MouseDrag extends Component implements MouseListener,
MouseMotionListener {
/** The Image we are to paint */
Image curImage;
/** Kludge for showStatus */
static Label status;
/** true if we are in drag */
boolean inDrag = false;
/** starting location of a drag */
int startX = -1, startY = -1;
/** current location of a drag */
int curX = -1, curY = -1;
// "main" method
public static void main(String[] av) {
JFrame f = new JFrame("Mouse Dragger");
Container cp = f.getContentPane();
if (av.length < 1) {
System.err.println("Usage: MouseDrag imagefile");
System.exit(1);
}
Image im = Toolkit.getDefaultToolkit().getImage(av[0]);
// create a MouseDrag object
MouseDrag j = new MouseDrag(im);
cp.setLayout(new BorderLayout());
cp.add(BorderLayout.NORTH, new Label(
"Hello, and welcome to the world of Java"));
cp.add(BorderLayout.CENTER, j);
cp.add(BorderLayout.SOUTH, status = new Label());
status.setSize(f.getSize().width, status.getSize().height);
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// "Constructor" - creates the object
public MouseDrag(Image i) {
super();
curImage = i;
setSize(300, 200);
addMouseListener(this);
addMouseMotionListener(this);
}
public void showStatus(String s) {
status.setText(s);
}
// Five methods from MouseListener:
/** Called when the mouse has been clicked on a component. */
public void mouseClicked(MouseEvent e) {
}
/** Called when the mouse enters a component. */
public void mouseEntered(MouseEvent e) {
}
/** Called when the mouse exits a component. */
public void mouseExited(MouseEvent e) {
}
// And two methods from MouseMotionListener:
public void mouseDragged(MouseEvent e) {
Point p = e.getPoint();
// System.err.println("mouse drag to " + p);
showStatus("mouse Dragged to " + p);
curX = p.x;
curY = p.y;
if (inDrag) {
repaint();
}
}
public void paint(Graphics g) {
int w = curX - startX, h = curY - startY;
Dimension d = getSize();
g.drawImage(curImage, 0, 0, d.width, d.height, this);
if (startX < 0 || startY < 0)
return;
System.err.println("paint:drawRect #[" + startX + "," + startY
+ "] size " + w + "x" + h);
g.setColor(Color.red);
g.fillRect(startX, startY, w, h);
}
}

Java how to move a paint componenet [duplicate]

I'm trying to move the boat on the x-axis (without the keyboard yet). How can I relate the movement/ animation to the boat.png and not to any other image?
public class Mama extends Applet implements Runnable {
int width, height;
int x = 200;
int y = 200;
int dx = 1;
Image img1, img2, img3, img4;
#Override
public void init(){
setSize(627, 373);
Thread t = new Thread(this);
img1 = getImage(getCodeBase(),"Background.png");
img2 = getImage(getCodeBase(), "boat.png");
img3 = getImage(getCodeBase(), "LeftPalm.png");
img4 = getImage(getCodeBase(), "RightPalm.png");
}
#Override
public void paint(Graphics g){
g.drawImage(img1, 0, 0, this);
g.drawImage(img2, 200, 200, this);
g.drawImage(img3, 40, 100, this);
g.drawImage(img4, 450, 130, this);
}
#Override
public void run() {
while(true){
x += dx;
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
System.out.println("Thread generates an error.");
}
}
}
}
There are a few things that stand out...
The "Problem"
As has already been stated, you need to supply variable arguments to the image drawing process. g.drawImage(img2, x, y, this);, this will allow you define where the image should be painted.
While you've implemented Runnable, you've actually not started any threads to call it. This means, nothing is actually changing the variables.
In you start method, you should be calling something like new Thread(this).start().
Recommendations
Although you've tagged the question as Swing, you're using AWT components. This isn't recommended (in fact applets are generally discouraged as they are troublesome - IMHO). The other problem, as you are bound to find out shortly, is they are not double buffered, this generally leads to flickering when performing animation, which isn't desirable.
As a side note, it is also discouraged to override the paint method of top level containers like Applet. Top level containers tend to contain a number additional components, by overriding the paint method like this, you destroy this setup. Also, top level containers don't tend to be double buffered either.
The example below uses a JFrame, but it wouldn't take much to convert it to use a JApplet (just drop the AnimationPanel on to it. This is another reason why extending from top level containers is generally discouraged ;)
public class AnimatedBoat {
public static void main(String[] args) {
new AnimatedBoat();
}
public AnimatedBoat() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new AnimationPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class AnimationPane extends JPanel {
private BufferedImage boat;
private int xPos = 0;
private int direction = 1;
public AnimationPane() {
try {
boat = ImageIO.read(new File("boat.png"));
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
xPos += direction;
if (xPos + boat.getWidth() > getWidth()) {
xPos = getWidth() - boat.getWidth();
direction *= -1;
} else if (xPos < 0) {
xPos = 0;
direction *= -1;
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return boat == null ? super.getPreferredSize() : new Dimension(boat.getWidth() * 4, boat.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int y = getHeight() - boat.getHeight();
g.drawImage(boat, xPos, y, this);
}
}
}
You need to replace g.drawImage(img2, 200, 200, this); with g.drawImage(img2, x, y, this);

Java hit-test behaving strangely

I was trying to extend the java ScrollDemo2 to report if a shape on the canvas had been clicked. I started with a simple rectangle believing that it should be no problem to simply loop over rectangle in the canvas checking if the click point was contained within them. But then something peculiar happened, the contains methods only seems to care if the point is in a rectangle anchored at (0,0), and doesn't seem to care that my component is at y=20. Therefore i get a hit if I click withing the Jpanel from x:[0,20] y:[0,20] when I should only get a hit if I click on x:[0,20] y[20,40]. Is this a bug, or am I doing something incorrectly?
public class CachedDrawableComponent extends JComponent
{
//this will do more later
CachedDrawableComponent(Rectangle bounds)
{
this.setBounds(bounds);
}
protected void paintComponent(Graphics g)
{
g.setColor(Color.magenta);
Rectangle r = this.getBounds();
g.fillRect(r.x, r.y, r.width, r.height);
}
}
public class ScrollDemo2 extends JPanel
implements MouseListener {
private Dimension area; //indicates area taken up by graphics
private Vector<Rectangle> circles; //coordinates used to draw graphics
private Vector<CachedDrawableComponent> otherDrawables;
private JPanel drawingPane;
private final Color colors[] = {
Color.red, Color.blue, Color.green, Color.orange,
Color.cyan, Color.magenta, Color.darkGray, Color.yellow};
private final int color_n = colors.length;
public ScrollDemo2() {
super(new BorderLayout());
area = new Dimension(0,0);
circles = new Vector<Rectangle>();
this.otherDrawables = new Vector<CachedDrawableComponent>();
//Set up the instructions.
JLabel instructionsLeft = new JLabel(
"Click left mouse button to place a circle.");
JLabel instructionsRight = new JLabel(
"Click right mouse button to clear drawing area.");
JPanel instructionPanel = new JPanel(new GridLayout(0,1));
instructionPanel.setFocusable(true);
instructionPanel.add(instructionsLeft);
instructionPanel.add(instructionsRight);
//Set up the drawing area.
drawingPane = new DrawingPane();
drawingPane.setBackground(Color.white);
drawingPane.addMouseListener(this);
TestRect t = new TestRect(new Rectangle(0,20,20,20));
this.otherDrawables.add(t);
//Put the drawing area in a scroll pane.
JScrollPane scroller = new JScrollPane(drawingPane);
scroller.setPreferredSize(new Dimension(200,200));
//Lay out this demo.
add(instructionPanel, BorderLayout.PAGE_START);
add(scroller, BorderLayout.CENTER);
}
/** The component inside the scroll pane. */
public class DrawingPane extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Rectangle rect;
for (int i = 0; i < circles.size(); i++) {
rect = circles.elementAt(i);
g.setColor(colors[(i % color_n)]);
g.fillOval(rect.x, rect.y, rect.width, rect.height);
}
for (int i = 0; i < otherDrawables.size(); i++) {
CachedDrawableComponent drawMe = otherDrawables.elementAt(i);;
g.setColor(colors[(i % color_n)]);
drawMe.paint(g);
}
}
}
//Handle mouse events.
public void mouseReleased(MouseEvent e) {
final int W = 100;
final int H = 100;
boolean changed = false;
if (SwingUtilities.isRightMouseButton(e)) {
//This will clear the graphic objects.
circles.removeAllElements();
area.width=0;
area.height=0;
changed = true;
} else {
int x = e.getX() - W/2;
int y = e.getY() - H/2;
if (x < 0) x = 0;
if (y < 0) y = 0;
Rectangle rect = new Rectangle(x, y, W, H);
circles.addElement(rect);
drawingPane.scrollRectToVisible(rect);
int this_width = (x + W + 2);
if (this_width > area.width) {
area.width = this_width; changed=true;
}
int this_height = (y + H + 2);
if (this_height > area.height) {
area.height = this_height; changed=true;
}
}
if (changed) {
//Update client's preferred size because
//the area taken up by the graphics has
//gotten larger or smaller (if cleared).
drawingPane.setPreferredSize(area);
//Let the scroll pane know to update itself
//and its scrollbars.
drawingPane.revalidate();
}
drawingPane.repaint();
}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e)
{
System.out.println("Did press:"+e.getPoint());
System.out.println(otherDrawables.get(0).getBounds());
if(otherDrawables.get(0).contains(e.getPoint()))
{
System.out.println("Did Hit");
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ScrollDemo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ScrollDemo2();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Output:
Did press:java.awt.Point[x=8,y=7]
java.awt.Rectangle[x=0,y=20,width=20,height=20]
Did Hit
Did press:java.awt.Point[x=14,y=89]
java.awt.Rectangle[x=0,y=20,width=20,height=20]
The face problem is that you are mixing coordinate systems:
the coordinates in the mouseListener are coordinates of the drawingPane
the coordinates expected in somecomponent.contains are coordinates of the component
From the api doc of contains:
Checks whether this component "contains" the specified point,
where x and y are defined to be
relative to the coordinate system of this component.
It's unusual (don't do without a reeeaal good reason :-) to have those components without actually adding them to the drawingPane.
Check out Playing With Shapes. It may give you some ideas for a slightly different approach.
For example by creating Shapes you don't need to keep track of Rectangle and others since all shapes will be treated the same.
You can also use the Shapes as components is you wish.

How to move an image (animation)?

I'm trying to move the boat on the x-axis (without the keyboard yet). How can I relate the movement/ animation to the boat.png and not to any other image?
public class Mama extends Applet implements Runnable {
int width, height;
int x = 200;
int y = 200;
int dx = 1;
Image img1, img2, img3, img4;
#Override
public void init(){
setSize(627, 373);
Thread t = new Thread(this);
img1 = getImage(getCodeBase(),"Background.png");
img2 = getImage(getCodeBase(), "boat.png");
img3 = getImage(getCodeBase(), "LeftPalm.png");
img4 = getImage(getCodeBase(), "RightPalm.png");
}
#Override
public void paint(Graphics g){
g.drawImage(img1, 0, 0, this);
g.drawImage(img2, 200, 200, this);
g.drawImage(img3, 40, 100, this);
g.drawImage(img4, 450, 130, this);
}
#Override
public void run() {
while(true){
x += dx;
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
System.out.println("Thread generates an error.");
}
}
}
}
There are a few things that stand out...
The "Problem"
As has already been stated, you need to supply variable arguments to the image drawing process. g.drawImage(img2, x, y, this);, this will allow you define where the image should be painted.
While you've implemented Runnable, you've actually not started any threads to call it. This means, nothing is actually changing the variables.
In you start method, you should be calling something like new Thread(this).start().
Recommendations
Although you've tagged the question as Swing, you're using AWT components. This isn't recommended (in fact applets are generally discouraged as they are troublesome - IMHO). The other problem, as you are bound to find out shortly, is they are not double buffered, this generally leads to flickering when performing animation, which isn't desirable.
As a side note, it is also discouraged to override the paint method of top level containers like Applet. Top level containers tend to contain a number additional components, by overriding the paint method like this, you destroy this setup. Also, top level containers don't tend to be double buffered either.
The example below uses a JFrame, but it wouldn't take much to convert it to use a JApplet (just drop the AnimationPanel on to it. This is another reason why extending from top level containers is generally discouraged ;)
public class AnimatedBoat {
public static void main(String[] args) {
new AnimatedBoat();
}
public AnimatedBoat() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new AnimationPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class AnimationPane extends JPanel {
private BufferedImage boat;
private int xPos = 0;
private int direction = 1;
public AnimationPane() {
try {
boat = ImageIO.read(new File("boat.png"));
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
xPos += direction;
if (xPos + boat.getWidth() > getWidth()) {
xPos = getWidth() - boat.getWidth();
direction *= -1;
} else if (xPos < 0) {
xPos = 0;
direction *= -1;
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return boat == null ? super.getPreferredSize() : new Dimension(boat.getWidth() * 4, boat.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int y = getHeight() - boat.getHeight();
g.drawImage(boat, xPos, y, this);
}
}
}
You need to replace g.drawImage(img2, 200, 200, this); with g.drawImage(img2, x, y, this);

Listen to JFrame resize events as the user drags their mouse?

When a user clicks on the corner of a JFrame to resize and drags the mouse around, the JFrame redraws based on the current position of the mouse as the user drags. How can you listen to these events?
Below is the what I have currently tried:
public final class TestFrame extends JFrame {
public TestFrame() {
this.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
// This is only called when the user releases the mouse button.
System.out.println("componentResized");
}
});
}
// These methods do not appear to be called at all when a JFrame
// is being resized.
#Override
public void setSize(int width, int height) {
System.out.println("setSize");
}
#Override
public void setBounds(Rectangle r) {
System.out.println("setBounds A");
}
#Override
public void setBounds(int x, int y, int width, int height) {
System.out.println("setBounds B");
}
}
How can I determine and constrain how the user resizes a window (based on the current aspect ratio of the window) as they are dragging around the mouse around?
You can add a component listener and implement the componentResized function like that:
JFrame component = new JFrame("My Frame");
component.addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent evt) {
Component c = (Component)evt.getSource();
//........
}
});
EDIT: Apparently, for JFrame, the componentResized event is hooked to the mouseReleased event. That's why the method is invoked when the mouse button is released.
One way to achieve what you want, is to add a JPanel that will cover the whole area of your JFrame. Then add the componentListener to the JPanel (componentResized for JPanel is called even while your mouse is still dragging). When your frame is resized, your panel will also be resized too.
I know, this isn't the most elegant solution, but it works!
Another workaround (which is very similar to Alex's but a little more straightforward) is to listen to the events from the JFrame's root pane instead:
public final class TestFrame extends JFrame {
public TestFrame() {
this.getRootPane().addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
// This is only called when the user releases the mouse button.
System.out.println("componentResized");
}
});
}
}
Depending on other implementation details, it's possible that the root pane might be changed. If that's a possibility then you could override setRootPane() and deal with that. Since setRootPane() is protected and only called from the constructor though, it's unlikely you'll need to do that.
You probably need to override something like validate (don't forget to call the super). Of course, that still may not work if you are using a windowing system to configured to drag outlines.
public class MouseDrag extends Component implements MouseListener,
MouseMotionListener {
/** The Image we are to paint */
Image curImage;
/** Kludge for showStatus */
static Label status;
/** true if we are in drag */
boolean inDrag = false;
/** starting location of a drag */
int startX = -1, startY = -1;
/** current location of a drag */
int curX = -1, curY = -1;
// "main" method
public static void main(String[] av) {
JFrame f = new JFrame("Mouse Dragger");
Container cp = f.getContentPane();
if (av.length < 1) {
System.err.println("Usage: MouseDrag imagefile");
System.exit(1);
}
Image im = Toolkit.getDefaultToolkit().getImage(av[0]);
// create a MouseDrag object
MouseDrag j = new MouseDrag(im);
cp.setLayout(new BorderLayout());
cp.add(BorderLayout.NORTH, new Label(
"Hello, and welcome to the world of Java"));
cp.add(BorderLayout.CENTER, j);
cp.add(BorderLayout.SOUTH, status = new Label());
status.setSize(f.getSize().width, status.getSize().height);
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// "Constructor" - creates the object
public MouseDrag(Image i) {
super();
curImage = i;
setSize(300, 200);
addMouseListener(this);
addMouseMotionListener(this);
}
public void showStatus(String s) {
status.setText(s);
}
// Five methods from MouseListener:
/** Called when the mouse has been clicked on a component. */
public void mouseClicked(MouseEvent e) {
}
/** Called when the mouse enters a component. */
public void mouseEntered(MouseEvent e) {
}
/** Called when the mouse exits a component. */
public void mouseExited(MouseEvent e) {
}
// And two methods from MouseMotionListener:
public void mouseDragged(MouseEvent e) {
Point p = e.getPoint();
// System.err.println("mouse drag to " + p);
showStatus("mouse Dragged to " + p);
curX = p.x;
curY = p.y;
if (inDrag) {
repaint();
}
}
public void paint(Graphics g) {
int w = curX - startX, h = curY - startY;
Dimension d = getSize();
g.drawImage(curImage, 0, 0, d.width, d.height, this);
if (startX < 0 || startY < 0)
return;
System.err.println("paint:drawRect #[" + startX + "," + startY
+ "] size " + w + "x" + h);
g.setColor(Color.red);
g.fillRect(startX, startY, w, h);
}
}

Categories