JFrame not opening when a button is clicked(单击按钮时JFrame未打开)
问题描述
我有两个 JFrame
.
公共类 Main 扩展 JFrame
public class ColourOption extends JPanel 实现 ActionListener
然后在 JFrame 中设置.
public class Main extends JFrame
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未打开


- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 获取数字的最后一位 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01