java中的 jpanel.updateUI() 和 jpanel.repaint() 和 toolkit.getDefultToolkit().sync() 有什么区别? [英] what is the difference between jpanel.updateUI() and jpanel.repaint() and toolkit.getDefultToolkit().sync() in java?

查看:38
本文介绍了java中的 jpanel.updateUI() 和 jpanel.repaint() 和 toolkit.getDefultToolkit().sync() 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的应用程序,并通过练习与 FPS 相关的方法如何在 Java 中工作以制作具有高刷新率的应用程序来学习,但是,我不知道我应该使用上述哪种方法.我的应用程序有一个按钮和一个文本字段以及一个我制作的简单布局管理器,它应该根据原始框架大小(使用比率)更改组件的位置.每次组件的位置更改时,布局管理器都应该能够更新面板(或我真的不知道的框架).此外,当用户更改框架尺寸时,组件应平滑移动且不会滞后.我怎样才能完成所有这些?现在我的问题如下所示,似乎 panel.updateUI() 没有做任何事情.

如您所见,当您缓慢更改帧大小时,会出现一条黑线,并且不会消失.速度快的时候会变大,看得很清楚,但是又消失了,而FPS 60以上应该看不到这样的东西.

这就是我目前的做法:

<预><代码>导入 java.awt.Color;导入 java.awt.Dimension;导入 java.awt.EventQueue;导入 java.awt.Font;导入 java.awt.Toolkit;导入 java.awt.event.ActionEvent;导入 java.awt.event.ActionListener;导入 java.util.List;导入 javax.swing.JButton;导入 javax.swing.JFrame;导入 javax.swing.JPanel;导入 javax.swing.JTextField;导入 javax.swing.SwingWorker;公共类测试{私人 JFrame 框架;private SwingWorkersw;私人 JTextField txtGi;受保护的 volatile 静态布尔值 b = false;私人双 FPS = 0;受保护的静态 volatile JButton btnStart;公共静态无效主(字符串 [] args){EventQueue.invokeLater(new Runnable() {公共无效运行(){尝试 {测试窗口 = new Test();window.frame.setVisible(true);} 捕获(异常 e){e.printStackTrace();}}});}公共测试(){初始化();}私有无效初始化(){框架 = 新 JFrame();frame.setBounds(100, 100, 230, 230);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setMinimumSize(new Dimension(230, 230));JPanel 面板 = new JPanel();panel.setBounds(0, 0, 216, 193);panel.setBackground(Color.PINK);frame.getContentPane().add(panel);panel.setLayout(null);btnStart = new JButton("Start");btnStart.setName("btnStart");btnStart.setFont(new Font(Segoe Print", Font.BOLD | Font.ITALIC, 17));btnStart.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {System.out.println(frame.getMinimumSize());System.out.println("#sw.isDone(): "+ sw.isDone() + "sw.isCancelled(): "+ sw.isCancelled() + "乙:"+ b);}});btnStart.setBounds(50, 120, 101, 33);panel.add(btnStart);System.out.println("1:" + Thread.currentThread().getName());frame.validate();panel.validate();sw = new SwingWorker() {@覆盖受保护的 Void doInBackground() 抛出异常 {b = 真;System.out.println(Thread.currentThread().getName() + 将要休眠 250 毫秒.");System.out.println(frame.isShowing());而 (frame.isShowing() == false) {System.out.println(初始化框架.");线程睡眠(320);}System.out.println(frame.isShowing());int cc = 0;int FC = 0;而(frame.isShowing()){线程睡眠(1);panel.updateUI();long s = System.currentTimeMillis();System.out.println("2:" + Thread.currentThread().getName());cc++;Graphical_AI.setComponentLocationWithButton(btnStart);System.out.println("3:" + Thread.currentThread().getName());如果(Graphical_AI.thread1.isAlive()){System.out.println();System.out.println("等待" + Graphical_AI.thread1.getName() + "完成!");System.out.println();Graphical_AI.thread1.join();线程睡眠(1);panel.updateUI();}Graphical_AI.setComponentLocationWithButton(txtGi);如果(Graphical_AI.thread1.isAlive()){System.out.println();System.out.println("等待" + Graphical_AI.thread1.getName() + "完成!");System.out.println();Graphical_AI.thread1.join();线程睡眠(1);panel.updateUI();}long e = System.currentTimeMillis();FPS = 1.0/((e - s)/1000.0);FC++;如果(FC == 60){txtGi.setText(String.valueOf("FPS:" + (int) FPS));FC = 0;}System.out.println("FPS:" + (int) FPS);如果 (cc == 1000) {线程睡眠(5);cc = 0;System.gc();System.out.println(内存优化");}}返回空;}@覆盖protected void process(List chunks) {超级进程(块);}@覆盖受保护的无效完成(){System.out.println("sw.isDone():"+sw.isDone()+"b:"+b);super.done();}};sw.execute();txtGi = 新 JTextField();txtGi.setName("txtGi");txtGi.setFont(new Font(Segoe Script", Font.BOLD | Font.ITALIC, 21));txtGi.setBounds(50, 40, 134, 70);panel.add(txtGi);txtGi.setColumns(10);}}

布局管理器:

import java.awt.Container;导入 java.util.ArrayList;导入 javax.swing.JComponent;导入 javax.swing.JFrame;公共类 Graphical_AI {受保护的静态易失性 int 计数 = 0;受保护的静态易失性 int C_X;受保护的静态易失性 int C_Y;受保护的静态双 x_C_To_E_ratio;受保护的静态双 y_C_To_E_ratio;受保护的静态 int C_WIDTH;受保护的静态 int C_HEIGHT;protected static int Con_WIDTH;protected static int Con_HEIGHT;受保护的静态易失性整数 N_C_X;受保护的静态易失性整数 N_C_Y;受保护的静态容器骗局;受保护的 volatile 静态布尔布尔 = 假;受保护的静态 volatile ArrayListal = new ArrayList();受保护的静态 volatile ArrayListal_for_O_names = new ArrayList();受保护的静态 volatile 字符串 C_Name;受保护的静态 volatile 字符串 C_O_Name;受保护的 volatile 静态布尔布尔 2 = 假;受保护的静态易失性线程 thread1;protected static void analysisJComponentSize(JComponent comp) 抛出 InterruptedException {System.out.println("W:" + comp.getWidth() + " H:" + comp.getHeight());线程睡眠(30);}protected static void analyzeJFrameSize(JFrame frame) 抛出 InterruptedException {System.out.println("W:"+frame.getWidth()+"H:"+frame.getHeight());线程睡眠(30);}protected static void setComponentLocationWithButton(JComponent comp) 抛出 InterruptedException {thread1 = Thread.currentThread();线程 1 = 新线程(新可运行(){@覆盖公共无效运行(){System.out.println("计数:"+计数);C_Name = comp.getName();System.out.println("C_Name:" + C_Name);如果(计数== 0){C_O_Name = comp.getName();System.out.println("C_O_Name:" + C_O_Name);con = comp.getParent();Con_WIDTH = con.getWidth();Con_HEIGHT = con.getHeight();System.out.println("** (double) Con_WIDTH: " + (double) Con_WIDTH);System.out.println("** (double) Con_HEIGHT: " + (double) Con_HEIGHT);x_C_To_E_ratio = (double) con.getWidth()/(double) comp.getX();y_C_To_E_ratio = (double) con.getHeight()/(double) comp.getY();如果(布尔2 == 假){al.add(x_C_To_E_ratio);al.add(y_C_To_E_ratio);al_for_O_names.add(comp.getName());bool2 = 真;}System.out.println("** x_C_To_E_ratio: " + x_C_To_E_ratio);System.out.println("** y_C_To_E_ratio: " + y_C_To_E_ratio);System.out.println("** (double) con.getWidth()/(double) comp.getX(): "+ (double) con.getWidth()/(double) comp.getX());C_X = comp.getX();C_Y = comp.getY();C_WIDTH = comp.getWidth();C_HEIGHT = comp.getHeight();System.out.println("** C_WIDTH: " + C_WIDTH + ", " + C_HEIGHT);System.out.println("** (double) con.getWidth()/(double) C_X): "+ (double) con.getWidth() + "/"+ (双) C_X);计数++;}如果 (C_Name != al_for_O_names.get(0)) {计数 = 0;System.out.println("%% C_Name:" + C_Name);System.out.println("%% C_O_Name:" + C_O_Name);System.out.println("%% al_for_O_names.get(0): "+ al_for_O_names.get(0));System.out.println("%% count 变为:" + count);al_for_O_names.remove(0);al_for_O_names.add(comp.getName());} 别的 {System.out.println("*ELSE STATEMENT*");计数 = 1;}如果(计数== 0){C_Name = comp.getName();System.out.println("$$ C_Name: " + C_Name);con = comp.getParent();Con_WIDTH = con.getWidth();Con_HEIGHT = con.getHeight();System.out.println("$$ (double) Con_WIDTH: " + (double) Con_WIDTH);System.out.println("$$ (double) Con_HEIGHT: " + (double) Con_HEIGHT);x_C_To_E_ratio = (double) con.getWidth()/(double) comp.getX();y_C_To_E_ratio = (double) con.getHeight()/(double) comp.getY();如果(布尔2 == 假){al.add(x_C_To_E_ratio);al.add(y_C_To_E_ratio);bool2 = 真;}System.out.println("$$ x_C_To_E_ratio: " + x_C_To_E_ratio);System.out.println("$$ y_C_To_E_ratio: " + y_C_To_E_ratio);System.out.println("$$ (double) con.getWidth()/(double) comp.getX(): "+ (double) con.getWidth()/(double) comp.getX());C_X = comp.getX();C_Y = comp.getY();C_WIDTH = comp.getWidth();C_HEIGHT = comp.getHeight();System.out.println("$$ C_WIDTH: " + C_WIDTH + ", " + C_HEIGHT);System.out.println("$$ (double) con.getWidth()/(double) C_X): "+ (double) con.getWidth() + "/"+ (双) C_X);计数++;}尝试 {System.out.println("## after if count block ## comp W: " + comp.getWidth() + " comp H: "+ comp.getHeight() + "\ncomp.getLocation(): "+ comp.getLocation()+ "comp.getLocationOnScreen(): "+ comp.getLocationOnScreen());System.out.println("con W:" + con.getWidth() +", con H:" + con.getHeight());if (x_C_To_E_ratio != al.get(0) || y_C_To_E_ratio != al.get(1)) {x_C_To_E_ratio = al.get(0);y_C_To_E_ratio = al.get(1);线程睡眠(2);}如果(((双)con.getWidth()/(双)C_X)> x_C_To_E_ratio + 0.025){线程睡眠(2);System.out.println(((((double) con.getWidth()/(double) C_X)) + ",,, " + x_C_To_E_ratio);而(((双)con.getWidth()/(双)C_X)> x_C_To_E_ratio + 0.025){C_X += 1;N_C_X = C_X;如果(((双)con.getWidth()/(双)C_X) x_C_To_E_ratio - 0.025){休息;}System.out.println("C_X:"+C_X+",N_C_X"+N_C_X);System.out.println("(double) con.getWidth()/(double) C_X): "+(双)con.getWidth()+ "/"+ (双) C_X);System.out.println("((double) con.getWidth()/(double) C_X): "+ ((double) con.getWidth()/(double) C_X) + ", x_C_To_E_ratio:"+ x_C_To_E_ratio+ ", ((double) con.getWidth()/(double) C_X) == x_C_To_E_ratio: "+ (((double) con.getWidth()/(double) C_X) == x_C_To_E_ratio));if (((double) con.getWidth()/(double) C_X) == x_C_To_E_ratio||((double) con.getWidth()/(double) C_X) - x_C_To_E_ratio >-0.002) {布尔 = 真;System.out.println("GA.bool:"+bool);System.out.println("W:" + comp.getWidth() + " H:" + comp.getHeight()+ "\ncomp.getLocation(): "+ comp.getLocation()+ "comp.getLocationOnScreen(): "+ comp.getLocationOnScreen() + "Con_WIDTH:"+ Con_WIDTH + "Con_HEIGHT:"+ Con_HEIGHT + "con.getWidth(): "+ con.getWidth() + "con.getHeight(): "+ con.getHeight());System.out.println("$GA.bool:"+bool+"$T.b:"+Test.b);休息;}comp.setBounds(N_C_X, comp.getY(), C_WIDTH, C_HEIGHT);}}} catch (InterruptedException e) {e.printStackTrace();}}});thread1.start();}}

** 现在,当您移动组件时,它们似乎不会滞后,如果您有更好的解决方案,我将不胜感激.

** 我不想使用 pack() 方法或任何预先构建的布局管理器.

** 我已经阅读了很多类似的问题,但我没有找到答案.

** 我正在使用 eclipse windowbuilder.

解决方案

自从你提出问题以来,我就没有想过这么多,

<块引用>

我不想使用 pack() 方法或任何预构建的布局管理器.

此评论立即取消了我认为您的问题的资格.有了这个限制,我无法回答这个问题.

这是我能想到的最简单的 Swing FPS 测试示例 GUI.

我使用 pack 方法.我使用 Swing 布局管理器.如果这是一个问题,请继续自己努力.

正如我在评论中所说,Oracle 有一个教程,Creating a GUI使用 JFC/Swing,这将引导您完成创建 Swing GUI 的步骤.跳过 Netbeans 部分.

我做的第一件事是调用 SwingUtilities invokeLater 方法来启动 Swing 应用程序.此方法确保在 事件调度线程上创建和执行 Swing 组件.

接下来我做的是构造一个JFrame.JFrame 方法必须按特定顺序调用.这是我在大多数 Swing 应用程序中使用的顺序.

我构造了一个按钮 JPanel 和一个绘图 JPanel.按钮 JPanel 包含开始 JButton.绘图 JPanel 每秒绘制帧数.

我使用 Swing Timer 来捕获当前时间和帧数.您可以通过调整 Timer 构造函数中的 int 值来调整 Timer 的速度.我不推荐低于 5 的值.

这是完整的可运行代码.

import java.awt.BorderLayout;导入 java.awt.Color;导入 java.awt.Dimension;导入 java.awt.FlowLayout;导入 java.awt.FontMetrics;导入 java.awt.Graphics;导入 java.awt.Graphics2D;导入 java.awt.event.ActionEvent;导入 java.awt.event.ActionListener;导入 java.awt.geom.Rectangle2D;导入 javax.swing.BorderFactory;导入 javax.swing.JButton;导入 javax.swing.JFrame;导入 javax.swing.JPanel;导入 javax.swing.SwingUtilities;导入 javax.swing.Timer;公共类 FPSTestExample 实现 Runnable {公共静态无效主(字符串 [] args){SwingUtilities.invokeLater(new FPSTestExample());}私人长开始时间,结束时间,计数间隔;私人最终 DrawingPanel 绘图面板;公共 FPSTestExample() {this.drawingPanel = new DrawingPanel();}@覆盖公共无效运行(){JFrame frame = new JFrame(FPS 测试示例");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.add(drawingPanel, BorderLayout.CENTER);frame.add(createButtonPanel(), BorderLayout.AFTER_LAST_LINE);框架.pack();frame.setLocationByPlatform(true);frame.setVisible(true);}私人 JPanel createButtonPanel() {JPanel 面板 = new JPanel(new FlowLayout());panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));JButton 按钮 = new JButton(开始");面板添加(按钮);button.addActionListener(new ActionListener() {私人定时器定时器;@覆盖公共无效 actionPerformed(ActionEvent 事件){如果(定时器 == 空){FPSTestExample.this.startTime = System.currentTimeMillis();timer = new Timer(15, new FPSListener());定时器开始();}}});返回面板;}公共类 DrawingPanel 扩展 JPanel {private static final long serialVersionUID = 1L;公共绘图面板(){this.setPreferredSize(new Dimension(300, 200));}@覆盖受保护的无效paintComponent(图形g){super.paintComponent(g);如果(FPSTestExample.this.endTime > 0L){long elapsedTime = FPSTestExample.this.endTime -FPSTestExample.this.startTime;int fps = (int) (FPSTestExample.this.countInterval * 1000L/elapsedTime);String fpsString = "FPS: ";+ 帧率;Graphics2D g2d = (Graphics2D) g;g2d.setColor(Color.BLUE);g2d.setFont(getFont().deriveFont(48f));FontMetrics fm = g2d.getFontMetrics();Rectangle2D r2d = fm.getStringBounds(fpsString, g2d);int width = (int) Math.round(r2d.getWidth());int height = (int) Math.round(r2d.getHeight());int x = (getWidth() - 宽度)/2;int y = (getHeight() - 高度 + fm.getAscent())/2;g2d.drawString(fpsString, x, y);}}}公共类 FPSListener 实现 ActionListener {@覆盖公共无效 actionPerformed(ActionEvent 事件){FPSTestExample.this.endTime = System.currentTimeMillis();FPSTestExample.this.countInterval++;FPSTestExample.this.drawingPanel.repaint();}}}

I'm making a simple app and learning with practicing how FPS-related methods work in java to make an app with a high fresh rate but, I don't know which one of the methods above should I use. my app have a button and a text field and a simple layout manager that I made which is supposed to change the location of the components according to the primal frame size (using ratio). the layout manager should be able to update the panel (or my frame I don't know really) every time that a component's location changed. also while the user is changing the frame size the components should move smoothly and without being laggy. how can I accomplish all these? right now my problem is shown below which seems that the panel.updateUI() doesn't do anything.

as you see there is a black line that will appear when you change the frame size slowly, and it doesn't disappear. when you do it fast it becomes bigger and you see it clearly but it disappears, while in FPS above 60 you shouldn't be able to see such a thing.

this is how I'm doing this currently:


import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;

public class Test {

    private JFrame frame;
    private SwingWorker<Void, Void> sw;
    private JTextField txtGi;
    protected volatile static boolean b = false;
    private double FPS = 0;
    protected static volatile JButton btnStart;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        Test window = new Test();
                        window.frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
    }

    public Test() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 230, 230);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setMinimumSize(new Dimension(230, 230));

        JPanel panel = new JPanel();
        panel.setBounds(0, 0, 216, 193);
        panel.setBackground(Color.PINK);
        frame.getContentPane().add(panel);
        panel.setLayout(null);

        btnStart = new JButton("Start");
        btnStart.setName("btnStart");
        btnStart.setFont(new Font("Segoe Print", Font.BOLD | Font.ITALIC, 17));
        btnStart.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println(frame.getMinimumSize());

                    System.out.println(
                        "#sw.isDone(): " + sw.isDone() + " sw.isCancelled(): " + sw.isCancelled() + " b: " + b);

                }
            });
        btnStart.setBounds(50, 120, 101, 33);
        panel.add(btnStart);
        System.out.println("1: " + Thread.currentThread().getName());
        frame.validate();
        panel.validate();
        sw = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {

                b = true;
                System.out.println(Thread.currentThread().getName() + " is going to sleep for 250 millis.");
                System.out.println(frame.isShowing());
                while (frame.isShowing() == false) {
                    System.out.println("initializing the frame.");
                    Thread.sleep(320);
                }

                System.out.println(frame.isShowing());
                int cc = 0;
                int FC = 0;

                while (frame.isShowing()) {
                    Thread.sleep(1);
                    panel.updateUI();
                    long s = System.currentTimeMillis();
                    System.out.println("2: " + Thread.currentThread().getName());
                    cc++;

                    Graphical_AI.setComponentLocationWithButton(btnStart);

                    System.out.println("3: " + Thread.currentThread().getName());
                    if (Graphical_AI.thread1.isAlive()) {
                        System.out.println();
                        System.out.println("waiting for " + Graphical_AI.thread1.getName() + " to finish!");
                        System.out.println();
                        Graphical_AI.thread1.join();
                        Thread.sleep(1);
                        panel.updateUI();

                    }

                    Graphical_AI.setComponentLocationWithButton(txtGi);

                    if (Graphical_AI.thread1.isAlive()) {
                        System.out.println();
                        System.out.println("waiting for " + Graphical_AI.thread1.getName() + " to finish!");
                        System.out.println();
                        Graphical_AI.thread1.join();
                        Thread.sleep(1);
                        panel.updateUI();

                    }

                    long e = System.currentTimeMillis();
                    FPS = 1.0 / ((e - s) / 1000.0);

                    FC++;
                    if (FC == 60) {
                        txtGi.setText(String.valueOf("FPS: " + (int) FPS));
                        FC = 0;
                    }

                    System.out.println("FPS: " + (int) FPS);

                    if (cc == 1000) {
                        Thread.sleep(5);
                        cc = 0;
                        System.gc();
                        System.out.println("memory optimized.");

                    }

                }
                return null;
            }

            @Override
            protected void process(List<Void> chunks) {
                super.process(chunks);
            }

            @Override
            protected void done() {
                System.out.println("sw.isDone(): " + sw.isDone() + " b: " + b);
                super.done();
            }

        };
        sw.execute();

        txtGi = new JTextField();
        txtGi.setName("txtGi");
        txtGi.setFont(new Font("Segoe Script", Font.BOLD | Font.ITALIC, 21));
        txtGi.setBounds(50, 40, 134, 70);
        panel.add(txtGi);
        txtGi.setColumns(10);
    }
}

the layout manager:

import java.awt.Container;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class Graphical_AI {

    protected static volatile int count = 0;
    protected static volatile int C_X;
    protected static volatile int C_Y;
    protected static double x_C_To_E_ratio;
    protected static double y_C_To_E_ratio;
    protected static int C_WIDTH;
    protected static int C_HEIGHT;
    protected static int Con_WIDTH;
    protected static int Con_HEIGHT;
    protected static volatile int N_C_X;
    protected static volatile int N_C_Y;
    protected static Container con;
    protected volatile static boolean bool = false;
    protected static volatile ArrayList<Double> al = new ArrayList<Double>();
    protected static volatile ArrayList<String> al_for_O_names = new ArrayList<String>();
    protected static volatile String C_Name;
    protected static volatile String C_O_Name;
    protected volatile static boolean bool2 = false;
    protected static volatile Thread thread1;

    protected static void analyzeJComponentSize(JComponent comp) throws InterruptedException {
        System.out.println("W: " + comp.getWidth() + " H: " + comp.getHeight());
        Thread.sleep(30);
    }

    protected static void analyzeJFrameSize(JFrame frame) throws InterruptedException {
        System.out.println("W: " + frame.getWidth() + " H: " + frame.getHeight());
        Thread.sleep(30);
    }

    protected static void setComponentLocationWithButton(JComponent comp) throws InterruptedException {

        thread1 = Thread.currentThread();
        thread1 = new Thread(new Runnable() {

                @Override
                public void run() {

                    System.out.println("count: " + count);
                    C_Name = comp.getName();
                    System.out.println("C_Name: " + C_Name);

                    if (count == 0) {
                        C_O_Name = comp.getName();
                        System.out.println("C_O_Name: " + C_O_Name);

                        con = comp.getParent();

                        Con_WIDTH = con.getWidth();
                        Con_HEIGHT = con.getHeight();

                        System.out.println("** (double) Con_WIDTH: " + (double) Con_WIDTH);
                        System.out.println("** (double) Con_HEIGHT: " + (double) Con_HEIGHT);

                        x_C_To_E_ratio = (double) con.getWidth() / (double) comp.getX();
                        y_C_To_E_ratio = (double) con.getHeight() / (double) comp.getY();

                        if (bool2 == false) {
                            al.add(x_C_To_E_ratio);
                            al.add(y_C_To_E_ratio);
                            al_for_O_names.add(comp.getName());
                            bool2 = true;
                        }

                        System.out.println("** x_C_To_E_ratio: " + x_C_To_E_ratio);
                        System.out.println("** y_C_To_E_ratio: " + y_C_To_E_ratio);

                        System.out.println("** (double) con.getWidth() / (double) comp.getX(): "
                            + (double) con.getWidth() / (double) comp.getX());

                        C_X = comp.getX();
                        C_Y = comp.getY();
                        C_WIDTH = comp.getWidth();
                        C_HEIGHT = comp.getHeight();

                        System.out.println("** C_WIDTH: " + C_WIDTH + ", " + C_HEIGHT);

                        System.out.println("** (double) con.getWidth() / (double) C_X): " + (double) con.getWidth() + " / "
                            + (double) C_X);

                        count++;
                    }

                    if (C_Name != al_for_O_names.get(0)) {
                        count = 0;
                        System.out.println("%% C_Name: " + C_Name);
                        System.out.println("%% C_O_Name: " + C_O_Name);
                        System.out.println("%% al_for_O_names.get(0): " + al_for_O_names.get(0));
                        System.out.println("%% count became to:" + count);
                        al_for_O_names.remove(0);
                        al_for_O_names.add(comp.getName());
                    } else {
                        System.out.println("*ELSE STATEMENT*");
                        count = 1;
                    }

                    if (count == 0) {
                        C_Name = comp.getName();
                        System.out.println("$$ C_Name: " + C_Name);

                        con = comp.getParent();

                        Con_WIDTH = con.getWidth();
                        Con_HEIGHT = con.getHeight();

                        System.out.println("$$ (double) Con_WIDTH: " + (double) Con_WIDTH);
                        System.out.println("$$ (double) Con_HEIGHT: " + (double) Con_HEIGHT);

                        x_C_To_E_ratio = (double) con.getWidth() / (double) comp.getX();
                        y_C_To_E_ratio = (double) con.getHeight() / (double) comp.getY();

                        if (bool2 == false) {
                            al.add(x_C_To_E_ratio);
                            al.add(y_C_To_E_ratio);
                            bool2 = true;
                        }

                        System.out.println("$$ x_C_To_E_ratio: " + x_C_To_E_ratio);
                        System.out.println("$$ y_C_To_E_ratio: " + y_C_To_E_ratio);

                        System.out.println("$$ (double) con.getWidth() / (double) comp.getX(): "
                            + (double) con.getWidth() / (double) comp.getX());

                        C_X = comp.getX();
                        C_Y = comp.getY();
                        C_WIDTH = comp.getWidth();
                        C_HEIGHT = comp.getHeight();

                        System.out.println("$$ C_WIDTH: " + C_WIDTH + ", " + C_HEIGHT);

                        System.out.println("$$ (double) con.getWidth() / (double) C_X): " + (double) con.getWidth() + " / "
                            + (double) C_X);

                        count++;
                    }

                    try {
                        System.out.println("## after if count block ## comp W: " + comp.getWidth() + " comp H: "
                            + comp.getHeight() + "\ncomp.getLocation(): " + comp.getLocation()
                            + " comp.getLocationOnScreen(): " + comp.getLocationOnScreen());
                        System.out.println("con W: " + con.getWidth() + ", con H: " + con.getHeight());

                        if (x_C_To_E_ratio != al.get(0) || y_C_To_E_ratio != al.get(1)) {
                            x_C_To_E_ratio = al.get(0);
                            y_C_To_E_ratio = al.get(1);
                            Thread.sleep(2);
                        }

                        if (((double) con.getWidth() / (double) C_X) > x_C_To_E_ratio + 0.025) {
                            Thread.sleep(2);
                            System.out.println((((double) con.getWidth() / (double) C_X)) + " ,,, " + x_C_To_E_ratio);
                            while (((double) con.getWidth() / (double) C_X) > x_C_To_E_ratio + 0.025) {

                                C_X += 1;
                                N_C_X = C_X;
                                if (((double) con.getWidth() / (double) C_X) < x_C_To_E_ratio + 0.025) {
                                    System.out.println("## in if bigger ## ");
                                    break;
                                }

                                System.out.println("## in if bigger ## C_X: " + C_X + ", N_C_X " + N_C_X);

                                System.out.println("## in if bigger ## (double) con.getWidth() / (double) C_X: "
                                    + (double) con.getWidth() + " / " + (double) C_X);
                                System.out.println("## in if bigger ## ((double) con.getWidth() / (double) C_X): "
                                    + ((double) con.getWidth() / (double) C_X) + ", x_C_To_E_ratio:" + x_C_To_E_ratio
                                    + ", ((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio: "
                                    + (((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio));

                                if (((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio
                                || ((double) con.getWidth() / (double) C_X) - x_C_To_E_ratio < 0.002) {
                                    bool = true;
                                    System.out.println("## in if bigger ## GI.bool: " + bool);
                                    System.out.println("## in if bigger ## W: " + comp.getWidth() + " H: "
                                        + comp.getHeight() + "\ncomp.getLocation(): " + comp.getLocation()
                                        + " comp.getLocationOnScreen(): " + comp.getLocationOnScreen() + " Con_WIDTH: "
                                        + Con_WIDTH + " Con_HEIGHT: " + Con_HEIGHT + " con.getWidth(): "
                                        + con.getWidth() + " con.getHeight(): " + con.getHeight());
                                    System.out.println("## in if bigger ## $GI.bool: " + bool + " $Test.b: " + Test.b);
                                    break;
                                }

                                comp.setBounds(N_C_X, comp.getY(), C_WIDTH, C_HEIGHT);
                            }
                        }

                        else if (((double) con.getWidth() / (double) C_X) < x_C_To_E_ratio - 0.025) {

                            Thread.sleep(2);
                            System.out.println((((double) con.getWidth() / (double) C_X)) + " *** " + x_C_To_E_ratio);
                            while (((double) con.getWidth() / (double) C_X) < x_C_To_E_ratio - 0.025) {

                                C_X -= 1;
                                N_C_X = C_X;

                                if (((double) con.getWidth() / (double) C_X) > x_C_To_E_ratio - 0.025) {
                                    break;
                                }

                                System.out.println("C_X: " + C_X + ", N_C_X " + N_C_X);

                                System.out.println("(double) con.getWidth() / (double) C_X): " + (double) con.getWidth()
                                    + " / " + (double) C_X);
                                System.out.println("((double) con.getWidth() / (double) C_X): "
                                    + ((double) con.getWidth() / (double) C_X) + ", x_C_To_E_ratio:" + x_C_To_E_ratio
                                    + ", ((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio: "
                                    + (((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio));

                                if (((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio
                                || ((double) con.getWidth() / (double) C_X) - x_C_To_E_ratio > -0.002) {
                                    bool = true;
                                    System.out.println("GA.bool: " + bool);
                                    System.out.println("W: " + comp.getWidth() + " H: " + comp.getHeight()
                                        + "\ncomp.getLocation(): " + comp.getLocation()
                                        + " comp.getLocationOnScreen(): " + comp.getLocationOnScreen() + " Con_WIDTH: "
                                        + Con_WIDTH + " Con_HEIGHT: " + Con_HEIGHT + " con.getWidth(): "
                                        + con.getWidth() + " con.getHeight(): " + con.getHeight());
                                    System.out.println("$GA.bool: " + bool + " $T.b: " + Test.b);
                                    break;
                                }

                                comp.setBounds(N_C_X, comp.getY(), C_WIDTH, C_HEIGHT);

                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        thread1.start();
    }
}

** Now the components don't seem to be laggy when you moving them while I appreciate it if you have any better solution.

** I don't want to use the pack() method or any prebuilt layout manager.

** I've already read a lot of similar questions but I didn't find my answer.

** I'm using eclipse windowbuilder.

解决方案

I hadn't given this much thought since you said in your question,

I don't want to use the pack() method or any prebuilt layout manager.

This comment immediately disqualified your question in my mind. There was no way I could answer this question with this restriction.

Here's the simplest Swing FPS Test Example GUI I could come up with.

I use the pack method. I use Swing layout managers. If this is a problem, keep struggling on your own.

As I said in my comment, Oracle has a tutorial, Creating a GUI With JFC/Swing, that will take you through the steps of creating a Swing GUI. Skip the Netbeans section.

The first thing I did was call the SwingUtilities invokeLater method to start the Swing application. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.

The next thing I did was construct a JFrame. The JFrame methods must be called in a specific order. This is the order I use for most of my Swing applications.

I constructed a button JPanel and a drawing JPanel. The button JPanel holds the Start JButton. The drawing JPanel draws the frames per second rate.

I used a Swing Timer to capture the current time and frame count. You can adjust the speed of the Timer by adjusting the int value in the Timer constructor. I don't recommend a value lower than 5.

Here's the complete runnable code.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class FPSTestExample implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new FPSTestExample());
    }
    
    private long startTime, endTime, countInterval;
    
    private final DrawingPanel drawingPanel;
    
    public FPSTestExample() {
        this.drawingPanel = new DrawingPanel();
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("FPS Test Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.add(drawingPanel, BorderLayout.CENTER);
        frame.add(createButtonPanel(), BorderLayout.AFTER_LAST_LINE);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JButton button = new JButton("Start");
        panel.add(button);
        
        button.addActionListener(new ActionListener() {
            private Timer timer;
            
            @Override
            public void actionPerformed(ActionEvent event) {
                if (timer == null) {
                    FPSTestExample.this.startTime = System.currentTimeMillis();
                    timer = new Timer(15, new FPSListener());
                    timer.start();
                } 
            }
        });
        
        return panel;
    }
    
    public class DrawingPanel extends JPanel {

        private static final long serialVersionUID = 1L;
        
        public DrawingPanel() {
            this.setPreferredSize(new Dimension(300, 200));
        }
        
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            
            if (FPSTestExample.this.endTime > 0L) {
                long elapsedTime = FPSTestExample.this.endTime - 
                        FPSTestExample.this.startTime;
                int fps = (int) (FPSTestExample.this.countInterval * 1000L / 
                        elapsedTime);
                String fpsString = "FPS: " + fps;
                
                Graphics2D g2d = (Graphics2D) g;
                g2d.setColor(Color.BLUE);
                g2d.setFont(getFont().deriveFont(48f));
                FontMetrics fm = g2d.getFontMetrics();
                Rectangle2D r2d = fm.getStringBounds(fpsString, g2d);
                
                int width = (int) Math.round(r2d.getWidth());
                int height = (int) Math.round(r2d.getHeight());
                int x = (getWidth() - width) / 2;
                int y = (getHeight() - height + fm.getAscent()) / 2;
                
                g2d.drawString(fpsString, x, y);
            }
        }
        
    }
    
    public class FPSListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {
            FPSTestExample.this.endTime = System.currentTimeMillis();
            FPSTestExample.this.countInterval++;
            FPSTestExample.this.drawingPanel.repaint();
        }
        
    }

}

这篇关于java中的 jpanel.updateUI() 和 jpanel.repaint() 和 toolkit.getDefultToolkit().sync() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆