单击按钮时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 :)
相关文章