这个我i知道,我在窗体上放了一些复选框,让它隐藏是想记住复选框选中的状态,点击返回显示窗体,复选状态仍存在,但用visible 不能保存状态,应该怎样实现?谢谢
追答我测试了可以保存状态,没问题。这是我的部分代码。
panel = new JPanel();
chk = new JCheckBox("test");
chk.setSelected(true);
btn = new JButton("set visible");
btn.addActionListener(new ActionListener() {
private int count=0;
@Override
public void actionPerformed(ActionEvent arg0) {
try {
count++;
if(count==1)
chk.setVisible(false);
else
chk.setVisible(true);
} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
我是在不同的窗体上啊,窗体1上放的复选框和隐藏按钮,窗体2上放显示按钮,点击隐藏跳转到窗体2,点击显示调到窗体1,而复选框保持被选状态。这样要怎样实现呢?谢谢
追答第二个窗体的构造方法,需要把第一个窗体作为参数传进去。比如,
frame是第一个窗体的实例化变量,那么第二个窗体应该写成,
CopyOfMainGUI frame2 = new CopyOfMainGUI(frame);
不可以。。。。
追答为什么不可以?要求不可以传递参数?
追问你能不能具体给我写写这两个窗体之间的跳转代码?我的代码很长,我也不知道哪不行。。。谢谢哦
追答好的。
这是第一个窗体。
public class MainGUI extends JFrame {
private static JPanel panel;
private static JButton btn2;
private static JCheckBox chk;
private static MainGUI frame;
public static void main(String[] args) {
createGUI();
}
public static void createGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
frame = new MainGUI();
frame.setTitle("window1");
frame.setSize(100,200);
panel = new JPanel();
chk = new JCheckBox("test");
chk.setSelected(true);
btn2 = new JButton("set invisible");
btn2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
CopyOfMainGUI frame2 = new CopyOfMainGUI(frame);
frame2.createGUI();
}
});
FlowLayout layout = new FlowLayout();
layout.setAlignment(0);
panel.setLayout(layout);
panel.add(chk);
frame.add(panel, BorderLayout.CENTER);
frame.add(btn2, BorderLayout.NORTH);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是第二个窗体。
public class CopyOfMainGUI extends JFrame {
private static JButton btn;
private CopyOfMainGUI frame2;
private MainGUI frame1;
public CopyOfMainGUI(MainGUI frame){
frame1 = frame;
}
public void createGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
frame2 = new CopyOfMainGUI(frame1);
frame2.setTitle("window2");
frame2.setSize(200, 200);
btn = new JButton("set visible");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {frame1.setVisible(true);frame2.setVisible(false);
} catch (HeadlessException e) { e.printStackTrace(); }}});
FlowLayout layout = new FlowLayout(); layout.setAlignment(0);
frame2.add(btn, BorderLayout.SOUTH); frame2.setVisible(true);} catch (Exception e) {e.printStackTrace();}}}