Is there a possibility to move window by clicking on one of the panels in the window when that window is undecorated?
I have a main panel with matte border 40 pixels size, and few panels with controls inside, and I would like to move the window when clicking on that border. Is that possible?
You can place another panel over the panel with the border, leaving the border visible.Use the following code to move your window.
public class MotionPanel extends JPanel{
private Point initialClick;
private JFrame parent;
public MotionPanel(final JFrame parent){
this.parent = parent;
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
initialClick = e.getPoint();
getComponentAt(initialClick);
}
});
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
// get location of Window
int thisX = parent.getLocation().x;
int thisY = parent.getLocation().y;
// Determine how much the mouse moved since the initial click
int xMoved = e.getX() - initialClick.x;
int yMoved = e.getY() - initialClick.y;
// Move window to this position
int X = thisX + xMoved;
int Y = thisY + yMoved;
parent.setLocation(X, Y);
}
});
}
}
I've been working with this code for a while now to make a custom titlebar for undecorated windows.
P.S.:You can generalize this example by extending JComponent instead of JPanel.
I have a main panel with matte border 40 pixels size, and few panels with controls inside, and I would like to move the window when clicking on that border
I think that ComponetMover by #camickr is right class for you
Yes, it is very possible. You need a MouseListener to listen on mouse events. you start moving on mousedown and stop moving on mouseup. Then you simply translate the window position by the same amount the mouse translates during that phase (calculate the delta bewteen old mouse position and new mouse position and add that to the frames position). You should be able to do this with a mouse listener fairly easily.
I have a simple solution from my project. Here is my undecorated JDialog class.
public class TimerDialog extends JDialog {
// some fields here
private Point mouseClickPoint; // Will reference to the last pressing (not clicking) position
private TimerDialog() {
initComponents();
addEventsForDragging();
}
private void addEventsForDragging() {
// Here is the code does moving
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseClickPoint = e.getPoint(); // update the position
}
});
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
Point newPoint = event.getLocationOnScreen();
newPoint.translate(-mouseClickPoint.x, -mouseClickPoint.y); // Moves the point by given values from its location
setLocation(newPoint); // set the new location
}
});
}
private void initComponents() {
setLayout(new FlowLayout());
// adding components
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setAlwaysOnTop(true);
setUndecorated(true);
setResizable(false);
pack();
}
}
int xMoved = (thisX + e.getX()) - (thisX + initialClick.x);
thisX + -thisX = 0
int xMoved = e.getX()-initialClick.x;
What i'm using.
public class MouseLiestenerX implements MouseListener,MouseMotionListener{
private theFrame;
public MouseLiestenerX(Frame theFrame){
this.theFrame = theFrame;
}
private Point startClick;
public void mouseDragged(MouseEvent e) {
int deltaX = e.getX()-startClick.x;
int deltaY = e.getY()-startClick.y;
Core.getSp().setLocation(theFrame.getLocation().x+deltaX, theFrame.getLocation().y+deltaY);
}
public void mousePressed(MouseEvent e) {
startClick = e.getPoint();
}
public void mouseMoved(MouseEvent e){
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
}
}
and in your Frame constructor
MouseLiestenerX IMove = new MouseLiestenerX(this);
addMouseListener(IMove);
addMouseMotionListener(IMove);
Related
Trying to have an object follow the cursor using:
int mx =(int) MouseInfo.getPointerInfo().getLocation().getX()-50;
Player.setX(mx);
in my tick method. However, this returns cursor position on screen, how can I make it relative to the JFrame itself? Is there maybe a way to read the position of the top-left point in the canvas so i can add an offset ?
Create a mouse listener, and fetch the coordinates from there:
public class SimpleFrame extends JFrame {
public static void main(String[] args) {
SimpleFrame frame = new SimpleFrame();
frame.setSize(new Dimension(200, 300));
frame.setLocation(new Point(500, 600));
frame.setVisible(true);
frame.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
System.out.println(e.getX() + " / " + e.getY());
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
});
}
}
When you test this, you probably realize that you want to have the coordinates relative to something else, for example the main panel of your application. Then you create the mouselistener for that component:
SimpleFrame frame = new SimpleFrame();
JPanel mainPanel = new JPanel();
frame.add(mainPanel, ...);
mainPanel.addMouseListener(...
It is much better to do it this way, than to start substracting constants from the coordinates you get from the JFrame's mouseListener, since those "constants" will differ depending on OS etc.
And if you want to have event whenever the user moves the mouse, not only when he/she clicks it, use this:
frame.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent e) {
System.out.println(e.getX() + " / " + e.getY());
}
#Override
public void mouseDragged(MouseEvent e) {
});
I have made a custome JFrame called mainWindow that is undecorated. I have added a JLabel named dragBar at the top of it and gave it desired dimensions (as shown below). When I click on the label I make the window move according to my mouse by using two listeners; one MouseListener and one MouseMotionListener.
The problem is that whenever I click on the label the window does move according to my mouse's location but it spazzes all over my screen until I stop moving the mouse or let go of the click button.
Is my method wrong? What is causing this issue?
Here is my code:
//what i use to make the dragBar
private JLabel dragBar = new JLabel();
private Point initialClick; //the initial point where I click on the label
//my mainWindow JFrame
private JFrame mainWindow = new JFrame();
private Dimension mainWindowSize = new Dimension(680,410);
//the code I use to set up my mainWindow JFrame
mainWindow.setUndecorated(true);
mainWindow.setShape(new RoundRectangle2D.Double(0, 0, 670, 400, 5, 5));
mainWindow.setSize(mainWindowSize);
mainWindow.setMinimumSize(mainWindowSize);
mainWindow.setResizable(false);
mainWindow.setLocation((screen_size.width/2)- mainWindow.getWidth()/2, (screen_size.height/2)- mainWindow.getHeight()/2);
mainWindow.getContentPane().setBackground(new Color(46, 48, 50, 255));
//the code I use to set up my dragBar label
topContainer.add(dragBar,3); //a Jlayeredpane that contains the dragBar label and is added to the mainWindow
dragBar.setSize(topContainer.getSize());
dragBar.setLocation(0,0);
dragBar.addMouseListener(new MouseListener() {
#Override public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {
initialClick = e.getPoint();
}
#Override public void mouseReleased(MouseEvent e) {}
#Override public void mouseEntered(MouseEvent e) {}
#Override public void mouseExited(MouseEvent e) {}
});
dragBar.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
int changeX = e.getX()-initialClick.x;
int changeY = e.getY()-initialClick.y;
mainWindow.setLocation(mainWindow.getX()+changeX, mainWindow.getY()+changeY);
}
#Override public void mouseMoved(MouseEvent e) {}
});
a Jlayeredpane that contains the dragBar label
Don't think I would use a JLayeredPane for this. Just add a component to the BorderLayout.PAGE_START of the frame.
The basic logic for dragging a component is something like:
public class DragListener extends MouseInputAdapter
{
Point location;
MouseEvent pressed;
public void mousePressed(MouseEvent me)
{
pressed = me;
}
public void mouseDragged(MouseEvent me)
{
Component component = me.getComponent();
location = component.getLocation(location);
int x = location.x - pressed.getX() + me.getX();
int y = location.y - pressed.getY() + me.getY();
component.setLocation(x, y);
}
}
However in your case you don't want to drag the label, but instead drag the window, you your logic needs to forward the events to the window.
Check out Moving Windows for a more complex implementation of the above code that also adds additional features that easily allow you to move a window.
I've seen a number of posters argue that Swing components should not be extended, and that functionality should instead be added via composition. So say I want to reusably create a JPanel with absolute positioning (no layout manager) in which I can reposition components with the mouse:
public class MoveableComponentPanel
{
private final JPanel m_panel;
public MoveableComponentPanel()
{
m_panel = new JPanel(null);
}
public void add(Component c)
{
m_panel.add(c);
c.addMouseListener(m_mover);
c.setSize(c.getPreferredSize());
}
private final MouseListener m_mover = new MouseListener()
{
private int m_startX, m_startY;
#Override
public void mousePressed(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
m_startX = e.getX();
m_startY = e.getY();
}
}
#Override
public void mouseReleased(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
Component c = e.getComponent();
Point p = c.getLocation();
p.x += e.getX() - m_startX;
p.y += e.getY() - m_startY;
c.setLocation(p);
c.repaint();
}
}
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
};
}
Looks nice, but there's no way to add the panel to a container. Further headaches if I want to allow a calling class to interact with the panel, e.g. change size, background color, register event listeners, etc. Either I add a getPanel() accessor, which breaks encapsulation, or write pass-through methods for the JPanel methods/properties I want to expose (potentially many). Is there some other strategy I'm missing here? What is the accepted best practice?
in which I can reposition components with the mouse:
Then you just add the MouseListener/MouseMotionListener to the components that you want to drag. There is no need to extend any component to add that functionality.
Check out the Component Mover class for examples of ways to do basic dragging of a component as well as a more complex dragging solution.
I'm making a small java game for fun to practice with my GUI programming. I want to have the center of my content pane's borderLayout be an image, and I would like to put "invisible" buttons on top of the image in specific places (to be placed later, I just want to get one working for now). My issue is getting the button to actually be invisible, it seems to leave a white square where it is now. I looked around but the only things that seem to be suggested were the .setOpaque, .setContentAreaFilled, and .setBorderPainted. (game is space related, explains the names)
galaxyButton1 = new JButton();
galaxyButton1.setFont(starSystem);
galaxyButton1.setBorder(BorderFactory.createEmptyBorder(25,25,25,25) );
galaxyButton1.setOpaque(false);
galaxyButton1.setContentAreaFilled(false);
galaxyButton1.setBorderPainted(false);
Color invis = new Color(Color.TRANSLUCENT);
galaxyButton1.setForeground(invis);
galaxyButton1.setBackground(invis);
galaxyButton1.addActionListener( new ButtonHandler() );
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout());
JPanel buttons = new JPanel();
buttons.setLayout(new GridLayout( 1,0,5,5 ) );
buttons.setOpaque(false);
buttons.add(galaxyButton1);
centerPanel.add(buttons,BorderLayout.CENTER);
centerImg.setLayout(new GridBagLayout());
centerImg.add(centerPanel);
contentPane.add(centerImg, BorderLayout.CENTER);
Here is a code outline of how to make your own button. You will need to set up a the actual mouse in some other class.
public class InvisibleButton implements MouseListener{
private final Rectangle rectangle;
public InvisibleButton(int x, int y, int width, int height){
rectangle = new Rectangle(x,y,width,height);
}
#Override
public void mouseClicked(MouseEvent e) {
int x = 0; // Set this to Mouse X
int y = 0; // Set this to Mouse Y
if(rectangle.contains(x,y)){
//Set Something to True or do action here
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
I'm attempting to add mouse listening capabilities to a JFrame that displays an MBFImage and the mouse events do absolutely nothing. I'm not sure if the events are not firing or if they are and not being caught because I am doing something wrong...
The image shows up in the JFrame just fine, however moving the mouse around over the image, clicking, moving, dragging, etc. does not result in any activity.
NOTE 1 I've discovered that if I add the mouselistener to a JPanel and then (in this specific order) draw the image and then add the the JPanel to the JFrame, that the mouse listener catches the events, but ONLY listens outside of the image. It draws a minimum size window which I need to resize. Any mouse movement over the image does not seem to fire / catch any events.
NOTE 2 If I add the panel to the JFrame and then draw the image, the window size is just fine, however the mouse listener no longer work.
Can anyone shed any light?
Here is the relevant portion of my code:
private JFrame displayImage(final MyAppImage image, final MyAppImage.DetectLevel level, String title) {
MBFImage mbfImg = image.drawDetections(level); //draws face detection boxes
JFrame imgFrame = new JFrame(title);
DisplayUtilities.display(mbfImg, imgFrame);
imgFrame.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("here");
if (level == MyAppImage.DetectLevel.filtered) {
if (image.checkPoints(e.getX(), e.getY(), level) != null) {
System.out.println("YES");
}
else {
System.out.println("NO!");
}
}
else {
System.out.println("Huh?");
}
}
#Override
public void mouseExited(MouseEvent e) {
}
});
imgFrame.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
System.out.println("hello");
}
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("here");
if (level == MyAppImage.DetectLevel.filtered) {
if (image.checkPoints(e.getX(), e.getY(), level) != null) {
System.out.println("YES");
}
else {
System.out.println("NO!");
}
}
else {
System.out.println("Huh?");
}
}
});
return imgFrame;
}
Exactly what #MadProgrammer commented - when you call DisplayUtilities.display(mbfImg, imgFrame); it creates an ImageComponent inside your JFrame that is itself a MouseListener.
You should be able to add a MouseListener to the ImageComponent directly however.