我想关闭所有已创建文档的所有操作。我的应用程序有Create和CloseAll菜单项。当我创建单个文档并在其上编写一些代码时,我单击CloseAll,它会询问构造对话框“是否要保存”。
这个案子对我来说很好。但是当我创建多个文档(超过五个)并且一些文档为空时,一些文档会有文本。然后我点击CloseAll菜单项,它应该询问具有文本的所有文档的conformation对话框。但是我的代码在这种情况下不起作用。我怎样才能做到这一点?
我的工作代码:
public class CloseAllAction extends javax.swing.JFrame implements ChangeListener {
JTextArea textArea;
JScrollPane scrollpane;
int tabCount=0,doc_count=0;
int i=0;
CloseButtonTabbedPane tabbedPane;
HashSet<String> docSet=new HashSet<>();
boolean update =false;
ArrayList<String> InternalClosing;
private final List<JTextArea> textAreas = new ArrayList<>();
private final List<JScrollPane> scrollPanes = new ArrayList<>();
public CloseAllAction() {
initComponents();
tabbedPane=new CloseButtonTabbedPane();
InternalClosing=new ArrayList<>();
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
create = new javax.swing.JMenuItem();
closeAll = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
create.setText("Create");
create.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createActionPerformed(evt);
}
});
jMenu1.add(create);
closeAll.setText("Close All");
closeAll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeAllActionPerformed(evt);
}
});
jMenu1.add(closeAll);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 512, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 366, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void createActionPerformed(java.awt.event.ActionEvent evt) {
textArea=new JTextArea();
textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
scrollpane=new JScrollPane(textArea);
tabCount++;
doc_count++;
String Doc_name="Document "+tabCount;
boolean value=docSet.add(Doc_name);
if(value==true)
tabbedPane.addTab("Document "+tabCount, null, scrollpane, "Document "+tabCount);
else{
tabbedPane.addTab("Document "+doc_count, null, scrollpane, "Document "+doc_count);
docSet.add("Document "+doc_count);
}
tabbedPane.addChangeListener(this);
textAreas.add(textArea);
scrollPanes.add(scrollpane);
try {
tabbedPane.setSelectedIndex(tabCount-1);
}
catch(IndexOutOfBoundsException i){
}
textArea.requestFocus();
textArea.setCaretPosition(0);
tabbedPane.addChangeListener(this);
Document doc=textArea.getDocument();
doc.addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
int index=tabbedPane.getSelectedIndex();
String sts=tabbedPane.getToolTipTextAt(index);
if(!InternalClosing.contains(sts)) {
InternalClosing.add(sts);
update =true;
}
update =true;
}
@Override
public void removeUpdate(DocumentEvent e) {
int index=tabbedPane.getSelectedIndex();
String sts=tabbedPane.getToolTipTextAt(index);
if(!InternalClosing.contains(sts)) {
InternalClosing.add(sts);
update =true;
}
}
@Override
public void changedUpdate(DocumentEvent e) {
int index=tabbedPane.getSelectedIndex();
String sts=tabbedPane.getToolTipTextAt(index);
if(!InternalClosing.contains(sts)) {
InternalClosing.add(sts);
update =true;
}
}
});
}
private void closeAllActionPerformed(java.awt.event.ActionEvent evt) {
if( update==false) {
tabbedPane.removeAll();
tabCount=0;
textAreas.clear();
scrollPanes.clear();
tabbedPane.tabs.clear();
}
else if(update==true){
int index=tabbedPane.getSelectedIndex();
String docName=InternalClosing.get(index);
int totalTabcount=tabbedPane.getTabCount();
tabbedPane.setSelectedIndex(totalTabcount-1);
int loop=1;
while(loop<=totalTabcount) {
if(!InternalClosing.contains(tabbedPane.getToolTipTextAt(index)))
{
totalTabcount--;
tabbedPane.setSelectedIndex(totalTabcount-1);
}
loop++;
}
if(InternalClosing.contains(docName))
{
update=false;
int reply = JOptionPane.showConfirmDialog(null,
"Save Changes to this Document", "Quit", JOptionPane.YES_NO_CANCEL_OPTION);
int chooserStatus;
if (reply == JOptionPane.YES_OPTION){
boolean success;
String editorString;
FileWriter fwriter;
PrintWriter outputFile;
try{
for(int i=0;i<=InternalClosing.size();i++) {
index=tabbedPane.getSelectedIndex();
InternalClosing.remove(docName);
if(tabbedPane.getToolTipTextAt(index).startsWith("Document ")) {
Save();
}
else{
String file1=tabbedPane.getToolTipTextAt(tabbedPane.getSelectedIndex());
DataOutputStream d = new DataOutputStream(new FileOutputStream(file1));
String line = textAreas.get(tabbedPane.getSelectedIndex()).getText();
BufferedReader br = new BufferedReader(new StringReader(line));
while((line = br.readLine())!=null){
d.writeBytes(line + "\r\n");
}
}
tabbedPane.remove(index);
try {
textAreas.remove(index);
scrollPanes.remove(index);
tabCount--;
}
catch(IndexOutOfBoundsException p){ }
}
}
catch (IOException e7){
success = false;
}
success = true;
tabbedPane.removeAll();
}
else if(reply==JOptionPane.NO_OPTION) {
//I Will Write this
}
else if(reply==JOptionPane.CANCEL_OPTION){
//I Will Write this
}
}
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CloseAllAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CloseAllAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CloseAllAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CloseAllAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new CloseAllAction().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem closeAll;
private javax.swing.JMenuItem create;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
// End of variables declaration
@Override
public void stateChanged(ChangeEvent e) {
JTabbedPane sourceTabbedPane = (JTabbedPane) e.getSource();
int index = sourceTabbedPane.getSelectedIndex();
try {
textArea=textAreas.get(index);
scrollpane=scrollPanes.get(index);
} catch (IndexOutOfBoundsException e1) {
}
}
public class CloseButtonTabbedPane extends JTabbedPane
{
public CloseButtonTabbedPane()
{
}
ArrayList<CloseButtonTab> tabs = new ArrayList<CloseButtonTab>();
public void addTab(String title, Icon icon, Component component,
String tip)
{
super.addTab(title, icon, component, tip);
int count = this.getTabCount() - 1;
CloseButtonTab tab = new CloseButtonTab(component, title, icon);
setTabComponentAt(count, tab);
tabs.add(tab); // Add the new tab to later modify the title
}
public void addTab(String title, Icon icon, Component component)
{
addTab(title, icon, component, null);
}
public void addTab(String title, Component component)
{
addTab(title, null, component);
}
public class CloseButtonTab extends JPanel
{
private Component tab;
JLabel tabTitle; // Saves the title, modify this label to set a new title
public CloseButtonTab(final Component tab, String title, Icon icon)
{
this.tab = tab;
setOpaque(false);
FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 3, 3);
setLayout(flowLayout);
setVisible(true);
tabTitle = new JLabel(title); // Set the tab title
tabTitle.setIcon(icon);
add(tabTitle);
JButton button = new JButton(MetalIconFactory.getInternalFrameCloseIcon(16));
button.setMargin(new Insets(0, 0, 0, 0));
button.setBorder(BorderFactory.createLineBorder( Color.LIGHT_GRAY, 1));
button.addMouseListener(new MouseListener()
{
int index;
public void mouseClicked(MouseEvent e)
{
index=tabbedPane.getSelectedIndex();
tabbedPane.remove(tabbedPane.getSelectedIndex());
i--;
tabs.remove(index);
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
JButton button = (JButton) e.getSource();
button.setBorder(BorderFactory.createLineBorder(Color.RED, 1));
}
public void mouseExited(MouseEvent e)
{
JButton button = (JButton) e.getSource();
button.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
}
});
add(button);
}
}
}
private void Save() {
int chooserStatus;
String filename=null;
int index=tabbedPane.getSelectedIndex();
String name=tabbedPane.getTitleAt(index);
if(name.isEmpty() || name.startsWith("Document ")){
JFileChooser chooser = new JFileChooser();
chooser.setPreferredSize( new Dimension(450, 400) );
chooserStatus = chooser.showSaveDialog(this);
if (chooserStatus == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
if (!selectedFile.getName().endsWith(".txt")) {
selectedFile = new File(selectedFile.getAbsolutePath() + ".txt");
}
filename = selectedFile.getPath();
tabbedPane.tabs.get(index).tabTitle.setText(selectedFile.getName());
tabbedPane.setToolTipTextAt(tabbedPane.getSelectedIndex(), filename);
}
else{
return;
}
}
boolean success;
String editorString;
FileWriter fwriter;
PrintWriter outputFile;
try {
DataOutputStream d = new DataOutputStream(new FileOutputStream(filename));
String line = textAreas.get(tabbedPane.getSelectedIndex()).getText();
BufferedReader br = new BufferedReader(new StringReader(line));
while((line = br.readLine())!=null) {
d.writeBytes(line + "\r\n");
}
InternalClosing.remove(filename);
}
catch (IOException e) {
success = false;
}
success = true;
}
}