Использование setLocation для перемещения JFrame по Windows, Java

Я пытаюсь перемещать JFrame в Windows с помощью 5 кнопок (север, восток, юг, запад и центр). На данный момент весь текущий код на месте, и он работает при использовании;

public void actionPerformed(ActionEvent e)
{
    if(e.getSource()==northButton)
    {
       setLocation(500,500);
    }

} //works

public void actionPerformed(ActionEvent e)
{
    if(e.getSource()== northButton)
    {
       setLocation(north);
    }

} //doesn't work

Однако в рамках задачи мне нужно использовать Java Toolkit для ширины и высоты getScreenSize и с помощью вычислений определить границы экрана и отправить «север» на setLocation() (как указано выше). Однако при использовании этого метода выдается ошибка "No suitable method found" Я не знаю, как это исправить. Код расчета ниже только для севера на данный момент.

int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;

int width = this.getWidth();
int height = this.getHeight();

int north = ((screenWidth - width)/2);

Любая помощь будет оценена. Спасибо!


person Tom C    schedule 20.02.2014    source источник


Ответы (2)


Здесь вы передаете два параметра, X и Y:

setLocation(500,500);

Вот вы проходите один, но какой? Х или Y? Если X, то где Y?:

int north = ((screenWidth - width)/2);
setLocation(north);

Компилятор сообщает вам, что у него нет метода setLocation(), принимающего один параметр. Ему нужно местоположение в 2D-пространстве: это X и Y. Возможно, вам нужно следующее:

setLocation(north, 0);
person martinez314    schedule 20.02.2014

Toolkit.getDefaultToolkit().getScreenSize() возвращает полный размер экрана по умолчанию, он не принимает во внимание такие вещи, как панели задач или другие элементы, которые могут занимать место на рабочем столе, окна которых не следует размещать под или над ними.

Лучшим решением было бы использовать Toolkit.getDefaultToolkit().getScreenInsets(GraphicsConfiguration) и GraphicsConfiguration#getBounds

public static Rectangle getScreenViewableBounds(Window window) {
    return getScreenViewableBounds((Component) window);
}

public static Rectangle getScreenViewableBounds(Component comp) {
    return getScreenViewableBounds(getGraphicsDevice(comp));
}

public static Rectangle getScreenViewableBounds(GraphicsDevice gd) {
    Rectangle bounds = new Rectangle(0, 0, 0, 0);
    if (gd == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gd = ge.getDefaultScreenDevice();
    }

    if (gd != null) {
        GraphicsConfiguration gc = gd.getDefaultConfiguration();
        bounds = gc.getBounds();

        Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
        bounds.x += insets.left;
        bounds.y += insets.top;
        bounds.width -= (insets.left + insets.right);
        bounds.height -= (insets.top + insets.bottom);
    }

    return bounds;
}

/**
 * Attempts to locate the graphics device that the component most likely is
 * on.
 *
 * This calculates the area that the window occupies on each screen deivce and
 * returns the one which it occupies the most.
 *
 * @param comp
 * @return
 */
public static GraphicsDevice getGraphicsDevice(Component comp) {

    GraphicsDevice device = null;

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice lstGDs[] = ge.getScreenDevices();

    ArrayList<GraphicsDevice> lstDevices = new ArrayList<GraphicsDevice>(lstGDs.length);

    if (comp != null && comp.isVisible()) {

        Rectangle parentBounds = comp.getBounds();

        /*
         * If the component is not a window, we need to find its location on the
         * screen...
         */
        if (!(comp instanceof Window)) {

            Point p = new Point(0, 0);

            SwingUtilities.convertPointToScreen(p, comp);
            parentBounds.setLocation(p);

        }

        for (GraphicsDevice gd : lstGDs) {

            GraphicsConfiguration gc = gd.getDefaultConfiguration();
            Rectangle screenBounds = gc.getBounds();

            if (screenBounds.intersects(parentBounds)) {

                lstDevices.add(gd);

            }

        }

        if (lstDevices.size() == 1) {

            device = lstDevices.get(0);

        } else {

            GraphicsDevice gdMost = null;
            float maxArea = 0;

            for (GraphicsDevice gd : lstDevices) {

                int width = 0;
                int height = 0;

                GraphicsConfiguration gc = gd.getDefaultConfiguration();
                Rectangle bounds = gc.getBounds();

                Rectangle2D intBounds = bounds.createIntersection(parentBounds);

                float perArea = (float) ((intBounds.getWidth() * intBounds.getHeight()) / (parentBounds.width * parentBounds.height));

                if (perArea > maxArea) {

                    maxArea = perArea;
                    gdMost = gd;

                }

            }

            if (gdMost != null) {

                device = gdMost;

            }

        }

    }

    return device;

}

Основная проблема, с которой вы столкнулись, заключается в том, что не существует такого метода, как setLocation(int)... что бы представляло собой значение int? х или у позиции?

Вам нужно передать позицию x и y в setLocation, чтобы она работала.

Rectangle bounds = getScreenViewableBounds(this); // where this is a reference to your window
int x = bounds.x + ((bounds.width - getWidth()) / 2;
int y = bounds.y;

setLocation(x, y);

Например...

person MadProgrammer    schedule 20.02.2014
comment
Я подумал, что это может быть полезно, но getGraphicsDevice(comp) не существует. - person Stan Towianski; 25.08.2017
comment
Нет, вам нужно написать метод - person MadProgrammer; 26.08.2017
comment
@StanTowianski Вот что вы получаете за копирование и вставку кода библиотеки: P - Обновлено - person MadProgrammer; 29.08.2017