我知道这已被问到数千次,但是我从未找到对我有用的答案。我将Java IDE用于Java开发人员(Eclipse Kepler)。
我需要拥有一个jbutton,通过单击它,它将关闭按钮打开的jframe,并打开一个在其他类中存在的新的。我有这个:
JButton button = new JButton("Click Me!");
add(button);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
}
});
}
我不知道在动作范围之后该放置什么。和frame.dispose();对我不起作用。
我在问,如何使用jbutton关闭Jframe,然后单击相同的按钮,它也打开了新类的Jframe?
这是一个可能会有所帮助的示例:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MyFrame extends JFrame {
public MyFrame() {
setLayout(new BorderLayout());
getContentPane().setPreferredSize(new Dimension(400, 250));
JButton btn = new JButton("Click Me");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
JFrame frame2 = new JFrame();
frame2.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame2.setLocation(300, 150);
frame2.add(new JLabel("This is frame2."));
frame2.setVisible(true);
frame2.setSize(200, 200);
}
} );
add(btn,BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MyFrame frame = new MyFrame();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.add(new JLabel("This is frame1."), BorderLayout.NORTH);
frame.setVisible(true);
}
});
}
}