java做一个窗口怎么设置一个退出按钮

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class X10
{
public static void main(String[]args){
Win win=new Win();
win.setTitle("下拉框的事件");
}
}
class Win extends JFrame implements ItemListener,ActionListener
{
JComboBox choice;
JTextField text;
JTextArea area;
JButton add,del,exi;
Win(){
init();
setBounds(300,400,300,300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
void init(){
setLayout(new FlowLayout());
choice=new JComboBox();
text=new JTextField(8);
area=new JTextArea(6,25);
choice.addItem("音乐天地");
choice.addItem("武术天地");
choice.addItem("象棋乐园");
choice.addItem("交友聊天");
add=new JButton("添加");
del=new JButton("删除");
exi=new JButton("退出");
add.addActionListener(this);
del.addActionListener(this);
text.addActionListener(this);
choice.addItemListener(this);
exi.addActionListener(this);
add(choice);
add(add);
add(del);
add(text);
add(exi);
add(new JScrollPane(area));
}
//public void actionPerformed(ActionEvent e){

public void itemStateChanged(ItemEvent e){
String name=choice.getSelectedItem().toString();
int index=choice.getSelectedIndex();
area.setText("\n"+index+":"+name);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==add||e.getSource()==text){
String name=text.getText();
if(name.length()>0){
choice.addItem(name);
choice.setSelectedItem(name);
area.append("\n列表添加:"+name);
}
}
else if(e.getSource()==del){
area.append("\n列表删除:"+choice.getSelectedItem());
choice.removeItemAt(choice.getSelectedIndex());
}
}
}请看上面的代码,按钮exi该怎么添加监视器,能让点击“退出”关闭窗口

如果是点击上面的那个叉号退出的话就加上这样一句setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
如果是通过按钮退出就用监听器实现如:
class MyListener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
一般情况下这两种都有。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-09-23

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ExitFrame extends JFrame{

   private JButton button;

   public ExitFrame(){
       super("按钮退出");
       setSize(600, 400);
       setVisible(true);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       button = new JButton("关闭");
       button.addActionListener(new ActionListener() {
           @Override
           public void actionPerformed(ActionEvent e) {
               System.exit(0);
           }
       });

       getContentPane().add(button);
   }

   public static void main(String[] args) {
       new ExitFrame();
   }

}


第2个回答  推荐于2016-05-15
  在窗体内添加;
  if(JOptionPane.showConfirmDialog(this,"退出","提示",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
  {
  System.exit(0);
  }
第3个回答  2012-06-02
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
相似回答