In this code I have created a JFrame to display the x and y points of the spot the users have clicked. As you can see in the example the y point is a really high number because it is taking the title bar height into consideration. How can i get it so the top left corner that is clickable is 0,0?
Right now (0,0) is out of reach and i'm not to sure how to incorporate the JPanel in order to be able to reach that point.
I can further explain my code or clarify if needed
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Proj07Runner {
Proj07Runner() {
System.out.println(
"Terminal");
new GUI();
}
}
class MyFrame extends Frame {
int clickX;
int clickY;
public void paint(Graphics g) {
g.drawString(" " clickX ", " clickY, clickX, clickY);
}
}
class GUI {
public GUI(){ // constructor - set up frame
MyFrame frame = new MyFrame();
frame.setSize(300,100);
frame.setTitle("xxx");
frame.setVisible(true);
// window listent to allow users to close frame
frame.addWindowListener(new Close());
// mouse listener so we can print points for mouse clicks
frame.addMouseListener(new MouseProc(frame));
// JPanel
JPanel panel = new JPanel();
frame.add(panel);
}
}
// monitors closing window
class Close extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
// Monitor mouse clicks and gather x and y points
class MouseProc extends MouseAdapter {
MyFrame reference;
MouseProc(MyFrame winIn) {
reference = winIn;
}
@Override
public void mousePressed(MouseEvent e) {
reference.clickX = e.getX();
reference.clickY = e.getY();
reference.repaint();
}
}
CodePudding user response:
How can i get it so the top left corner that is clickable is 0,0?
Add the MouseListener to the panel (not the frame). The mouse points are relative to the component you add the listener to.
Any custom painting should then be done by:
- extend your JPanel
- overriding the
paintComponent(...)
method, not paint(...).
Read the Swing tutorial on Custom Painting for more information and working example, including an example that uses a MouseListener.
CodePudding user response:
By nature, a jpanel has no particular size, and will just float around in the jframe without doing anything in particular. What you want it to do is expand to take up the whole frame. By default frames use BorderLayout, so you need to use border layout centre, which means "take up as much space as possible"
frame.add(panel, BorderLayout.CENTER)
You should become very very familiar with how to use BorderLayout if you want to be a good Swing programmer.