java 按钮复选框监听事件及恢复保存状态

葫芦的运维日志

下一篇 搜索 上一篇

2013/04/24 18:29


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Panel1
{
public static void main(String[] args)
{
Panel1 gui=new Panel1();
gui.go();

}
JPanel panel,panel2,panel3;
JTextArea text;
JScrollPane scroller;
JCheckBox check;
public void go(){
JFrame frame=new JFrame();
panel=new JPanel();
panel3=new JPanel();

panel.setBackground(Color.red);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
JButton button=new JButton("green");
panel.add(button);
button.addActionListener(new ButtonListener());

JButton button2=new JButton("red");
JButton button3=new JButton("save");
JButton button4=new JButton("load");
button3.addActionListener(new Button3Listener());

button2.addActionListener(new Button2Listener());
panel.add(button2);
panel3.add(button3);
panel3.add(button4);
button4.addActionListener(new Button4Listener());

panel2=new JPanel();
text=new JTextArea(5,25);
text.setLineWrap(true);
check=new JCheckBox("blue or black");
check.addItemListener(new CheckListen());
panel2.setLayout(new BoxLayout(panel2,BoxLayout.Y_AXIS));
panel2.add(check);
check.setSelected(true);
scroller=new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel2.add(scroller);

frame.getContentPane().add(BorderLayout.EAST,panel);
frame.getContentPane().add(BorderLayout.WEST,panel2);
frame.getContentPane().add(BorderLayout.SOUTH,panel3);

frame.setSize(400,300);
frame.setVisible(true);
}

class CheckListen implements ItemListener
{
public void itemStateChanged(ItemEvent envent){
if(check.isSelected()){
panel.setBackground(Color.blue);
text.append("blue \n");
}else{
panel.setBackground(Color.black);
text.append("black \n");
}
}
}
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event){
panel.setBackground(Color.green);
text.append("green \n");}
}
class Button2Listener implements ActionListener
{
public void actionPerformed(ActionEvent event){
panel.setBackground(Color.red);
text.append("red \n");}

}
class Button3Listener implements ActionListener
{
public void actionPerformed(ActionEvent event){
try{ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("save.ser"));
os.writeObject(text);
os.close();
}catch(IOException ex){
ex.printStackTrace();}

}
}
class Button4Listener implements ActionListener
{
public void actionPerformed(ActionEvent event){
try{ObjectInputStream is=new ObjectInputStream(new FileInputStream("save.ser"));
JTextArea test=(JTextArea) is.readObject();
text.setText(test.getText());
}catch(Exception ex){
ex.printStackTrace();}

}
}
}
 

 

葫芦的运维日志

上一篇 搜索 下一篇
© 冰糖葫芦甜(bthlt.com) 2019 王梓 赞助联系方式 陕ICP备17005322号