第二个 JFrame 中的组件未显示

本文介绍了第二个 JFrame 中的组件未显示的处理方法,对大家解决问题具有一定的参考价值

问题描述

我想通过按下 JFrame 中的按钮来启动另一个 JFrame.但是,如果我按下按钮,它会显示 JFrame,但不会显示其中的按钮和滑块.

i want to start another JFrame from pressing a button in a JFrame. But if I press the Button it shows the JFrame but not the Buttons and Sliders in it.

public class MainMenu extends JFrame {


private JFrame klick;
private static final long serialVersionUID = 9002;


public static void main(String[] args) {

    new MainMenu();

}


public MainMenu() {
    buildGUI1();

}
public void buildGUI1() throws NullPointerException {
    setTitle("Hauptmenü");      
    setSize(800, 480);
    setLayout(new GridLayout());
    setAlwaysOnTop(false);
    setLocation((Toolkit.getDefaultToolkit().getScreenSize().width)/4, (Toolkit.getDefaultToolkit().getScreenSize().height)/4);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    setVisible(true);
    final JButton startclickbt = new JButton("Start Clicker");
    startclickbt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            dispose();
            if(klick == null ) {
                klick =new Clicker();
                add(klick);
            }


        }
    });

    add(startclickbt);


    }

}

第二个具有完全相同的 costructor.sliders 和按钮不是静态的.在按钮应该出现的地方,屏幕是黑色的.

The second has quite the same costructor.sliders and buttons are not static. At the places where Buttons should appear the screen is black.

希望你能帮助我:)

public class Clicker extends JFrame {

    private static final long serialVersionUID = 9001;
    protected JPanel panel;
    static Click j = null;
    protected JSlider jsl;
    protected JTextField tf;
    static final int CPS_MIN= 0;
    static final int CPS_MAX= 100;
    static final int CPS_INIT= 25;
    private int amount;
    private boolean visible;

    public int getDelay() {
        return Math.abs(jsl.getValue()-100);
    }
    public int getAmount() {
        return amount;
    }
    public boolean getVisible() {
        return visible;
    }
    public void setOpen(boolean visible) {
        this.visible=visible;
    }

    public Clicker(boolean visible) {

        buildGUI(visible);
        j = new Click(false).addPosition(new Point((Toolkit.getDefaultToolkit().getScreenSize().width)/2, (Toolkit.getDefaultToolkit().getScreenSize().height)/2)).addPosition(new Point(getLocation().x+1, getLocation().y+20));
        while(true) {

            j.runClicks(getDelay());
        }
    }

    public Clicker() {
        buildGUI(true);
        j = new Click(false).addPosition(new Point((Toolkit.getDefaultToolkit().getScreenSize().width)/2, (Toolkit.getDefaultToolkit().getScreenSize().height)/2)).addPosition(new Point(getLocation().x+1, getLocation().y+20));
        while(true) {

            j.runClicks(getDelay());
        }
    }
    public void buildGUI(boolean visible) {

        setTitle("Clicker");
        setSize(340, 200);
        setLayout(new GridLayout());
        setAlwaysOnTop(true);
        setLocation(0, 0);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(visible);

        final JButton bt1 = new JButton("Schließen");
        bt1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        final JButton bt2 = new JButton("Start  ");
        bt2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                j.setClick(true);
            }
        });
        final JButton bt3 = new JButton("Stop       ");
        bt3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                j.setClick(false);
                JOptionPane.showMessageDialog(null, "Klicken gestoppt. Klicks: " + j.getClickAmount());
                j.setClickAmout(0);
            }
        });
        final JButton bt4 = new JButton("StartAnzahl");
        bt4.addActionListener(new ActionListener() {
            private int amount;

            public void actionPerformed(ActionEvent e) {
                String wert = tf.getText();
                try {
                    amount = Integer.parseInt(wert);
                }catch(Exception ee) {
                    JOptionPane.showMessageDialog(null,"Das war keine Zahl oder mehr als ein Integer");
                }

                j.doClick(amount);


            }
        });
        tf = new JTextField("Anzahl gewünschte Clicks max "+ Integer.MAX_VALUE, 10);
        tf.setEditable(true);


        jsl = new JSlider(JSlider.HORIZONTAL,CPS_MIN,CPS_MAX,CPS_INIT);
        jsl.setMinorTickSpacing(5);
        jsl.setMajorTickSpacing(10);
        jsl.setPaintTicks(true);
        jsl.setPaintLabels(true);

        panel = new JPanel();
        panel.addMouseMotionListener(new MouseMotionListener() {

            @Override
            public void mouseDragged(MouseEvent event) {
                j.setClick(false);  
            }

            @Override
            public void mouseMoved(MouseEvent event) {
                j.setClick(false);          
            }
        });

        panel.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_F1) {
                    j.setClick(true);
                }
                if(e.getKeyCode() == KeyEvent.VK_F2) {
                    j.setClick(false);
                }
            }

        });


        add(panel);
        add(bt2);
        add(bt3);
        add(bt1);
        add(bt4);
        add(jsl);
        add(tf);

        pack();
    }

}

推荐答案

使 setVisible 成为你调用的最后一件事...

Make setVisible the last thing you call...

public void buildGUI1() throws NullPointerException {
    setTitle("Hauptmenü");
    setSize(800, 480);
    setLayout(new GridLayout());
    setAlwaysOnTop(false);
    setLocation((Toolkit.getDefaultToolkit().getScreenSize().width) / 4, (Toolkit.getDefaultToolkit().getScreenSize().height) / 4);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    final JButton startclickbt = new JButton("Start Clicker");
    startclickbt.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            dispose();
            if (klick == null) {
                klick = new Clicker();
                add(klick);
                // Add this when you need to add/remove components
                revalidate();
                repaint();
            }

        }
    });

    add(startclickbt);
    // Move to here
    setVisible(true);

}

另外,使用 revalidate()repaint() 来鼓励容器在添加新组件时更新其布局

Also, use revalidate() and repaint() to encourage the container to update it's layout when adding new components

建议:

  • 确保您的 UI 在 EDT 的上下文中启动,请参阅 初始线程了解更多详情
  • 避免直接从 JFrame 等顶级容器扩展,而是考虑使用 JPanel 作为基础容器.这个免费的用户界面可以让您使用更广泛的用例,并防止您陷入困境(因为您无法将框架添加到其他框架)
  • 使用多个 JFrame,好/坏做法?
  • Make sure your UI is started within the context of the EDT, see Initial Threads for more details
  • Avoid extending directly from top level containers like JFrame and instead consider using a JPanel as you base container. This free's up you UI to a wider range of use-cases and prevents you from getting locked in (as you can't add frames to other frames)
  • The Use of Multiple JFrames, Good/Bad Practice?

更新

你有两个直接的问题

  1. ClickerJFrame 扩展而来,但是您正试图将其添加到另一个容器中,这在 Swing 中是不可能的并且会导致异常,但是...
  2. 您正在使用 while (true) 循环阻塞事件调度线程,这意味着 Swing 无法处理任何新事件,包括 repaint 事件
  1. Clicker extends from a JFrame, but you are trying to add it to another container, this is not possible in Swing and will cause an exception, however...
  2. You are blocking the Event Dispatching Thread with your while (true) loop, meaning that Swing is unable to process any new events, including repaint events

例如...

public Clicker(boolean visible) {

    buildGUI(visible);
    j = new Click(false).addPosition(new Point((Toolkit.getDefaultToolkit().getScreenSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height) / 2)).addPosition(new Point(getLocation().x + 1, getLocation().y + 20));
    // This is bad
    while (true) {

        j.runClicks(getDelay());
    }
}

public Clicker() {
    buildGUI(true);
    j = new Click(false).addPosition(new Point((Toolkit.getDefaultToolkit().getScreenSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height) / 2)).addPosition(new Point(getLocation().x + 1, getLocation().y + 20));
    // This is bad
    while (true) {

        j.runClicks(getDelay());
    }
}

现在,Click 看起来像是 UI 组件,它带来了许多其他问题,但我们没有相应的代码,因此无法评论.

Now, Click looks like it's UI component which brings up a bunch of other problems, but we don't have the code for that so it's impossible to comment.

直接的解决方案可能是使用:

The immediate solutions might be to use a:

  • SwingWorker, see Worker Threads and SwingWorker for more details

Swing Timer,参见 如何使用摆动计时器了解更多详情

Swing Timer, see How to use Swing Timers for more details

要记住的事情

  • Swing(与大多数 UI 框架一样)是单线程的,任何阻塞该线程的事物(例如永无止境的循环)都会阻止它处理新事件,包括绘制事件,这会使您的应用看起来像是挂起",因为它有
  • Swing 不是线程安全的.与 UI 的所有交互都必须在事件调度线程的上下文中进行.SwingWorker 和 Swing Timer 都提供了安全更新 UI 的能力.
  • Swing (like most UI frameworks) is single threaded, anything which blocks this thread (like never ending loops), will prevent it from processing new events, including paint events, which will make your application look like it's "hung", because it has
  • Swing is NOT thread safe. All interactions with the UI MUST be made from within the context of the Event Dispatching Thread. Both SwingWorker and Swing Timer provide the capability to update the UI safely.

这篇关于第二个 JFrame 中的组件未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1172

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1071

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this->id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:808

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this->id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:900

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:930

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:877

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:865

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:834

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1733

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1309