问题
I have two JFrame.
public class Main extends JFramepublic class ColourOption extends JPanel implements ActionListenerwhich is then set up in a 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?
回答1:
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..
and this is not good practice
so personally i would recommend you to switch over to better alternatives like JTABBEDPANES or CARDLAYOUT
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);
}
}
and the second class:
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 :)
回答2:
Since they are from 2 different classes, you just have to define/instantiate an object of the other class... and if within that 2nd class (ColourOption) it already contains setVisible(true) then there must be no problem loading the window.
//this will be placed on your constructor
yourButton.addActionListener(new ButtonListener());
//listener class
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == yourButton){
new ColourOption();
}
}
}
来源:https://stackoverflow.com/questions/9900466/jframe-not-opening-when-a-button-is-clicked