单击按钮时JFrame未打开

JFrame not opening when a button is clicked(单击按钮时JFrame未打开)

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

问题描述

我有两个 JFrame.

  1. 公共类 Main 扩展 JFrame
  2. public class ColourOption extends 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() 不工作.我还在第二个 JFrame 中尝试了 revalidate(),以及 invalidate()validate().

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?

推荐答案

您将必须实例化具有第 2 帧的第 2 类(要显示)..然后如果您调用 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"));
    }
}    

但我仍然建议切换到我之前提到的其他方法:标签窗格、卡片布局等.希望我有所帮助:)

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

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

本文标题为:单击按钮时JFrame未打开

基础教程推荐