Как изменить размер экрана java

I have a program that uses visual scripting (sikuli-script) to allow the users to create their own visual scripts. The program needs to work across multiple systems that could have different screen

Therefore is there a way that I can change the resolution settings in windows through java code?

1.yes is possible, why not

import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.image.BufferStrategy;

public class MultiBufferTest {

    private Frame mainFrame;
    private static Color[] COLORS = new Color[]{
        Color.red, Color.blue, Color.green, Color.white, Color.black,
        Color.yellow, Color.gray, Color.cyan, Color.pink, Color.lightGray,
        Color.magenta, Color.orange, Color.darkGray};
    private static DisplayMode[] BEST_DISPLAY_MODES = new DisplayMode[]{
        new DisplayMode(640, 480, 32, 0),
        new DisplayMode(640, 480, 16, 0),
        new DisplayMode(640, 480, 8, 0)};

    public MultiBufferTest(int numBuffers, GraphicsDevice device) {
        try {
            GraphicsConfiguration gc = device.getDefaultConfiguration();
            mainFrame = new Frame(gc);
            mainFrame.setUndecorated(true);
            mainFrame.setIgnoreRepaint(true);
            device.setFullScreenWindow(mainFrame);
            if (device.isDisplayChangeSupported()) {
                chooseBestDisplayMode(device);
            }
            Rectangle bounds = mainFrame.getBounds();
            mainFrame.createBufferStrategy(numBuffers);
            BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();
            for (float lag = 2000.0f; lag > 0.00000006f; lag = lag / 1.33f) {
                for (int i = 0; i < numBuffers; i++) {
                    Graphics g = bufferStrategy.getDrawGraphics();
                    if (!bufferStrategy.contentsLost()) {
                        g.setColor(COLORS[i]);
                        g.fillRect(0, 0, bounds.width, bounds.height);
                        bufferStrategy.show();
                        g.dispose();
                    }
                    try {
                        Thread.sleep((int) lag);
                    } catch (InterruptedException e) {
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            device.setFullScreenWindow(null);
        }
    }

    private static DisplayMode getBestDisplayMode(GraphicsDevice device) {
        for (int x = 0; x < BEST_DISPLAY_MODES.length; x++) {
            DisplayMode[] modes = device.getDisplayModes();
            for (int i = 0; i < modes.length; i++) {
                if (modes[i].getWidth() == BEST_DISPLAY_MODES[x].getWidth()
                        && modes[i].getHeight() == BEST_DISPLAY_MODES[x].getHeight()
                        && modes[i].getBitDepth() == BEST_DISPLAY_MODES[x].getBitDepth()) {
                    return BEST_DISPLAY_MODES[x];
                }
            }
        }
        return null;
    }

    public static void chooseBestDisplayMode(GraphicsDevice device) {
        DisplayMode best = getBestDisplayMode(device);
        if (best != null) {
            device.setDisplayMode(best);
        }
    }

    public static void main(String[] args) {
        try {
            int numBuffers = 2;
            if (args != null && args.length > 0) {
                numBuffers = Integer.parseInt(args[0]);
                if (numBuffers < 2 || numBuffers > COLORS.length) {
                    System.err.println("Must specify between 2 and " + COLORS.length + " buffers");
                    System.exit(1);
                }
            }
            GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice device = env.getDefaultScreenDevice();
            MultiBufferTest test = new MultiBufferTest(numBuffers, device);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}

2.don’t do that, could annoying users, and on code lack can to change resolution in Native OS (my coworker has more than 100shortcuts on three screen, any change for resolution to change shotcuts size and location, result is simple mess)

3.use JLabel for Icons(layed with proper LayoutManager into container), or put Icons to the JList or JTable, then you never / don’t care about something

4.use only LayoutManager rather than possitioning or change for screen resolution, you can set for smaller Size (for JFrame) on the screen for Apps start_up, let’s user decide about final Dimmension on her/his screen

As mentioned in the comments, the best approach here is to fix the underlying code to not mandate a 1024 x 768 display. This is usually a very distinct code smell of front-end Java code. Proper use of Layout Managers can almost always get your display to function in a more flexible manner.

However, in industry, sometimes refactoring to get legacy components functioning properly is not a feasible effort. In such a case, I would propose that you treat the inflexible GUI you can’t refactor as a component of a larger GUI that you can control.

Consider the following example code:

public static void main(String[] args) {
  // Initialize the frame
  JFrame myApp = new JFrame("App");
  myApp.setSize(1400, 1050);

  // Create container for the GUI
  JPanel container = new JPanel(new BorderLayout());
  container.setPreferredSize(new Dimension(1024, 768));

  // Load the GUI into the container
  JComponent myGui = new JPanel(); // Replace this with actual GUI.
  myGui.setBackground(Color.RED); // Remove this once using actual GUI.
  container.add(myGui, BorderLayout.CENTER);

  // Create the frame's content pane
  JPanel content = new JPanel(new FlowLayout(FlowLayout.CENTER));
  content.setBackground(Color.BLUE); // Also remove this in production.

  // Add GUI to content pane
  content.add(container);

  // Add content pane to frame, show frame
  myApp.setContentPane(content);
  myApp.setVisible(true);
}

This works because we’ve added the GUI to the CENTER of a BorderLayout panel (which will stretch the GUI to occupy the entire size of the panel in the absence of any components on the NORTH/SOUTH/EAST/WEST). We set the preferred size of that BorderLayout panel to be 1024 x 768 (IE: the size that the GUI is specified to work for), and then feed that panel into a FlowLayout panel (which will preserve the preferred size).

The result is that our 1400 x 1050 application contains a 1024 x 768 rendering of our GUI component (you can easily change this to 1024 x 1050 by modifying the preferred size of the panel containing the BorderLayout).

As an exercise to the user, you’ll notice that the GUI code isn’t centered vertically if you run this. This can be tackled by modifying the layout of the content panel.

As mentioned in the comments, the best approach here is to fix the underlying code to not mandate a 1024 x 768 display. This is usually a very distinct code smell of front-end Java code. Proper use of Layout Managers can almost always get your display to function in a more flexible manner.

However, in industry, sometimes refactoring to get legacy components functioning properly is not a feasible effort. In such a case, I would propose that you treat the inflexible GUI you can’t refactor as a component of a larger GUI that you can control.

Consider the following example code:

public static void main(String[] args) {
  // Initialize the frame
  JFrame myApp = new JFrame("App");
  myApp.setSize(1400, 1050);

  // Create container for the GUI
  JPanel container = new JPanel(new BorderLayout());
  container.setPreferredSize(new Dimension(1024, 768));

  // Load the GUI into the container
  JComponent myGui = new JPanel(); // Replace this with actual GUI.
  myGui.setBackground(Color.RED); // Remove this once using actual GUI.
  container.add(myGui, BorderLayout.CENTER);

  // Create the frame's content pane
  JPanel content = new JPanel(new FlowLayout(FlowLayout.CENTER));
  content.setBackground(Color.BLUE); // Also remove this in production.

  // Add GUI to content pane
  content.add(container);

  // Add content pane to frame, show frame
  myApp.setContentPane(content);
  myApp.setVisible(true);
}

This works because we’ve added the GUI to the CENTER of a BorderLayout panel (which will stretch the GUI to occupy the entire size of the panel in the absence of any components on the NORTH/SOUTH/EAST/WEST). We set the preferred size of that BorderLayout panel to be 1024 x 768 (IE: the size that the GUI is specified to work for), and then feed that panel into a FlowLayout panel (which will preserve the preferred size).

The result is that our 1400 x 1050 application contains a 1024 x 768 rendering of our GUI component (you can easily change this to 1024 x 1050 by modifying the preferred size of the panel containing the BorderLayout).

As an exercise to the user, you’ll notice that the GUI code isn’t centered vertically if you run this. This can be tackled by modifying the layout of the content panel.

Наверняка многие сталкивались с проблемой, когда Java-игра ни в какую не хочет растягиваться на весь экран мобильного телефона. Играть, конечно, можно, но удовольствие резко падает, вы нервничаете, обижаетесь на производителя и разработчика, а затем в сердцах удаляете игрушку. И совершенно зря, потому что есть способы справиться с этой неприятностью!

Итак, способ первый, самый простой. Весь процесс требует установки на ваш компьютер бесплатного стороннего приложения JarResize. Это шаг первый. Шаг второй – после завершения установки вышеназванного приложения скачайте на компьютер Java-игру, разрешение которой вы намерены изменить. Для осуществления следующего шага вам необходимо знать исходное разрешение игры и разрешение дисплея вашего мобильного телефона. Когда такая информация получена, смело открывайте приложение JarResize и выбирайте исходное разрешение игры, а затем – желаемое (то, которого требует ваш телефон).

Как изменить разрешение Java-игры

После этого кликаете на кнопке Select & Resize («Выбрать и Изменить размер») и выделяете jar-файл игры, которую вы уже предварительно загрузили. Шаг последний — закройте приложение и установите игру на свой мобильный телефон.

Если вы не нашли приложение JarResize или считаете его использование трудоемким (что довольно странно), тогда вам подойдет второй способ – изменение разрешения Java-игры вручную. Итак, сначала скачайте Java-игру на рабочий стол и распакуйте jar-файл, другими словами, откройте ее с помощью архиватора – WinRar или WinZip. В папке, которую вы открыли, есть несколько подпапок, среди них найдите папку с названием META-INF, откройте ее и найдите файл MANIFEST.MF.

Как изменить разрешение Java-игры

Перетащите MANIFEST.MF на рабочий стол и откройте его с помощью Блокнота. Далее – самое главное. В самом конце файла нужно добавить вручную две строки:

Как изменить разрешение Java-игры

Первая строка: Nokia-MIDlet-Original-Display-Size: XXX, YYY (XXX, YYY – здесь указываем оригинальное разрешение Java-игры)
Вторая строка: Nokia-MIDlet-Target-Display-Size: ZZZ, WWW (ZZZ, WWW – здесь указываем требуемое разрешение игры в соответствии с разрешением вашего мобильного телефона)

Например, разрешение Java-игры – 176 х 208, а дисплей вашего телефона требует разрешения 240 х 320, тогда строчки будут выглядеть так:
Nokia-MIDlet-Original-Display-Size:176,208
Nokia-MIDlet-Target-Display-Size: 240,320

Естественно, разрешение может варьироваться в зависимости от игры и модели вашего мобильного телефона, поэтому будьте внимательны. После этого следует сохранить файл MANIFEST.MF и перетащить его обратно в папку  META-INF. После этого останется только заново упаковать jar-файл (.jar file), используя WinRar или WinZip. Разрешение изменено, а значит, можно устанавливать игрушку на телефон и наслаждаться игрой в полном объеме.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.GeneralPath;
import java.awt.Graphics2D;
import javax.swing.JPanel;
 
public class Frame {
    
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        DrawPanel panel = new DrawPanel();
        frame.add(panel);
        
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }
}
public class Plane implements DrawableObject {
    private int xpoint[] = {530,465,465,200,200,465,465,315,365,490,
                       570,695,745,595,595,860,860,595,595};
    private int ypoint[] = {50,140,290,490,560,520,560,670,740,
                       675,675,740,670,560,520,560,490,290,140};
 
    @Override
    public void draw(Graphics2D g2d){
        Point2D start = new Point2D.Float(0, 0);
        Point2D end = new Point2D.Float(800, 800);
        float[] dist = {0.2f, 1.0f};
        Color[] colors = {Color.BLUE, Color.GREEN};
        LinearGradientPaint bluetogreen = new LinearGradientPaint(start, end, dist, colors);
        g2d.setPaint(bluetogreen);
        g2d.fillPolygon(xpoint,ypoint,19);
    }
}
public interface DrawableObject {
    void draw(Graphics2D g2d);
}
public class DrawPanel extends JPanel {
 
    @Override
    public void paint(Graphics gr) {
        Graphics2D g2d = (Graphics2D) gr;
        Plane plane = new Plane();
        plane.draw(g2d);
        Star star = new Star(230, 490);
        Star star2 = new Star(790, 490);
        star.draw(g2d);
        star2.draw(g2d);
        gr.setColor(Color.BLACK);
        gr.setFont(new Font("Calibri", Font.BOLD,70));
        gr.drawString("И-16",465,500);
 
    }
}
public class Star implements DrawableObject {
    private int x, y;
 
    public Star(int x, int y) {
        this.x = x;
        this.y = y;
    }
    @Override
    public void draw(Graphics2D g2d) {
        int xPoints[]= {18, 30, 0, 36, 6};
        int yPoints[]= {0, 36, 12, 12, 36};
        GeneralPath star = new GeneralPath();
 
        star.moveTo(xPoints[0]+ x, yPoints[0]+ y);
        for (int i = 1; i < xPoints.length; i++) {
            star.lineTo(xPoints[i]+ x, yPoints[i]+ y);
        }
        star.closePath();
 
        g2d.setColor(Color.RED);
        g2d.fill(star);
    }
}

We have developed a huge application using Java Swings, this is well exceuting and running on all systems, but the problem is the resolution , if the resolution is 1260/768 it works well means all the components including the scrollbar will be visible, even application will fit to the width and height of the screen, but when its below 1280/768 its not fitting the screen, what i do is manually change the system resolution to 1280/768 and also wrote program which will change the resolution, but the problem is most systems does not support more than 1024/768,on old systems its max VGA Cards-1024/768.

What is the way to resolve this?Which layout manager to change?

Update
Our application will be going live in next 5 days, so need something much quicker, tried with FlowLayout but it will not be good UI.

Or how to resize components when maximized or minimized? how is it implememted?

Tim Bender's user avatar

Tim Bender

19.9k2 gold badges48 silver badges58 bronze badges

asked Mar 27, 2013 at 8:54

user2214771's user avatar

8

The answer basically depends on how your GUI is designed.

In some cases, a FlowLayout will allow components to wrap around.

JScrollPane wrappers can be added around sections to make them independently scrollable. Along this line of thought, the entire current GUI could be placed in a JScrollPane and set never to be less than 1280×768 such that scrollbars will appear on smaller displays.

JTabbedPanel could also be used to stack sections of the GUI which are not commonly used in unison.

answered Mar 27, 2013 at 8:58

Tim Bender's user avatar

Tim BenderTim Bender

19.9k2 gold badges48 silver badges58 bronze badges

2

The smaller resolution could use a smaller and especially a more narrow font. It is a huge task to substitute hard coordinates with scaled ones; something like Scale.x(80). But it is a «dumb» dependable solution. If you still can use a smaller font (Arial Narrow?).

Mind, smaller resolution is often displayed on the same physical size monitor. Or with today’s tablets tininess is acceptable.

answered Mar 27, 2013 at 10:31

Joop Eggen's user avatar

Joop EggenJoop Eggen

106k7 gold badges83 silver badges135 bronze badges

We have developed a huge application using Java Swings, this is well exceuting and running on all systems, but the problem is the resolution , if the resolution is 1260/768 it works well means all the components including the scrollbar will be visible, even application will fit to the width and height of the screen, but when its below 1280/768 its not fitting the screen, what i do is manually change the system resolution to 1280/768 and also wrote program which will change the resolution, but the problem is most systems does not support more than 1024/768,on old systems its max VGA Cards-1024/768.

What is the way to resolve this?Which layout manager to change?

Update
Our application will be going live in next 5 days, so need something much quicker, tried with FlowLayout but it will not be good UI.

Or how to resize components when maximized or minimized? how is it implememted?

Tim Bender's user avatar

Tim Bender

19.9k2 gold badges48 silver badges58 bronze badges

asked Mar 27, 2013 at 8:54

user2214771's user avatar

8

The answer basically depends on how your GUI is designed.

In some cases, a FlowLayout will allow components to wrap around.

JScrollPane wrappers can be added around sections to make them independently scrollable. Along this line of thought, the entire current GUI could be placed in a JScrollPane and set never to be less than 1280×768 such that scrollbars will appear on smaller displays.

JTabbedPanel could also be used to stack sections of the GUI which are not commonly used in unison.

answered Mar 27, 2013 at 8:58

Tim Bender's user avatar

Tim BenderTim Bender

19.9k2 gold badges48 silver badges58 bronze badges

2

The smaller resolution could use a smaller and especially a more narrow font. It is a huge task to substitute hard coordinates with scaled ones; something like Scale.x(80). But it is a «dumb» dependable solution. If you still can use a smaller font (Arial Narrow?).

Mind, smaller resolution is often displayed on the same physical size monitor. Or with today’s tablets tininess is acceptable.

answered Mar 27, 2013 at 10:31

Joop Eggen's user avatar

Joop EggenJoop Eggen

106k7 gold badges83 silver badges135 bronze badges

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить размер шубы
  • Как изменить размер штриховки архикад
  • Как изменить размер штрих кода на принтере
  • Как изменить размер шторки уведомлений
  • Как изменить размер шторки на андроид

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии