单击按钮时JFrame不会打开 [英] JFrame not opening when a button is clicked

查看:163
本文介绍了单击按钮时JFrame不会打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 JFrame


  1. 公共类Main扩展JFrame

  2. 公共类ColourOption扩展了JPanel实现的ActionListener ,然后在JFrame中设置。

  1. public class Main extends JFrame
  2. public class ColourOption extends JPanel implements ActionListener which is then set up in a JFrame.

当我点击第一个JFrame的按钮时,我想打开第二个JFrame

.setVisible()无效。我还试过 revalidate(),以及 invalidate() validate()在第二个JFrame中。

I wanted to open the second JFrame when i click on button of first JFrame
.setVisible() is not working. I also tried revalidate(), as well as invalidate() , validate() in the second JFrame.

这可能是什么原因导致它失效?

What could be the reason for it to not work?

推荐答案

你将必须实例化具有第二帧(显示)的第二类..然后如果你调用setVisible(true)..然后它必须显示..你在做什么..你能提供你的按钮的事件吗?处理程序..

You will have to instantiate the 2nd class which has the 2nd Frame(to be shown)..and then if you call the setVisible(true) .. then it must show .. what you doing .. could you provide your button's event handler..

这不是一个好习惯

所以我个人建议你切换转到更好的替代品,如JTABBEDPANES或CARDLAYOUT

并考虑评论..好评论家伙:) ..特别是在这个背景下使用JDialog :)

and consider the comments as well .. good comments guys :) .. especially using JDialog for this context :)

如果您仍想在上下文中寻求帮助:样本:

well if you still want help in your context: a sample:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JFrame1 extends JFrame
{
    public JFrame1()
    {
        setLayout(new FlowLayout());
        JButton b=new JButton("Click");
        add(b);
        b.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                JFrame jf = new JFrame2();
                jf.setVisible(true);
                jf.setSize(200, 200);
                jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        }
        );
}
    public static void main(String args[])
    {
        JFrame jf = new JFrame1();
        jf.setVisible(true);
        jf.setSize(200, 200);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

和第二类:

import javax.swing.*;
import java.awt.*;
class JFrame2 extends JFrame
{
    public JFrame2()
    {
        setLayout(new FlowLayout());
        add(new JLabel("2nd Frame"));
    }
}    

但我仍然建议切换到其他方法正如我之前提到的:tabbedpanes,cardlayout等..
希望我帮助:))

But again i would still recommend to switch to other methods as i mentioned earlier: tabbedpanes, cardlayout etc.. Hope i helped :)

这篇关于单击按钮时JFrame不会打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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