0

I Want To work All Menu Items Functionality for All Opened Documents.In My Application It's working for Recently Opened Document only.For Example: I Open Two Files/Documents(say Document1 and Document2).My Application is work for Document2(Recent) only.If I Go with Document1 and try to Apply the Menu Items Functionality,It's not working for that.Because it is older one.In My Application I Add two Menu Items.One Open-->To open a file and another is ViewSpace-->for check the whether the functionality is working for all opened Documents or not.Please Check My Application and Help me.Thank You.

My Code: Main Class:

public class TabbedPaneFocus extends javax.swing.JFrame {

JTextArea tx;
int i=0;
JTabbedPane tabbedPane;

public TabbedPaneFocus() {
    initComponents();
    viewSpace.setSelected(false);
    tabbedPane=new CloseButtonTabbedPane();
    add(tabbedPane);
    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();
    open = new javax.swing.JMenuItem();
    viewSpace = new javax.swing.JCheckBoxMenuItem();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jMenu1.setText("File");

    open.setText("Open");
    open.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            openActionPerformed(evt);
        }
    });
    jMenu1.add(open);

    viewSpace.setSelected(true);
    viewSpace.setText("ViewSpace");
    viewSpace.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            viewSpaceActionPerformed(evt);
        }
    });
    jMenu1.add(viewSpace);

    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 openActionPerformed(java.awt.event.ActionEvent evt) {                                     
    final JFileChooser jc = new JFileChooser();
    int returnVal=  jc.showOpenDialog(TabbedPaneFocus.this);
    String title;
    File file=null;
    if(returnVal == JFileChooser.APPROVE_OPTION)
        file = jc.getSelectedFile();
    JTextArea text = new JTextArea();
    if (jc.getSelectedFile()!= null) {
        tx = new JTextArea();
        BufferedReader br = null;
        StringBuffer str = new StringBuffer("");
        try {
            br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                str.append(line + "\n");
            }
        }
        catch (IOException ex) {
            Logger.getLogger(tabbedpaneDemo.class.getName()).log(Level.SEVERE, null, ex);
        }
        String t = str.toString();
        title=file.getName();
        tx.setFont(new java.awt.Font("Miriam Fixed", 0, 13));

        JScrollPane  scrollpane=new JScrollPane(tx);
        tabbedPane.addTab(title, scrollpane);
        i++;
        tabbedPane.setSelectedIndex(i-1);
        tx.setText(t);
        tx.setCaretPosition(0);      
    }
}                                    

private void viewSpaceActionPerformed(java.awt.event.ActionEvent evt) {                                          
    AbstractButton button = (AbstractButton) evt.getSource();
    String previous=tx.getText();
    if(button.isSelected()){
        previous=previous.replaceAll(" ",".");
        tx.setText(previous);
        tx.setCaretPosition(0);
    }
    else{
        String str=tx.getText();
        str=str.replaceAll("\\."," ");
        tx.setText(str); 
        tx.setCaretPosition(0);
    }
}                                         

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(TabbedPaneFocus.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(TabbedPaneFocus.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(TabbedPaneFocus.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(TabbedPaneFocus.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            new TabbedPaneFocus().setVisible(true);
        }
    });
}                     
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JCheckBoxMenuItem viewSpace;                 
}

CloseButtonTabbedPane.java

public class CloseButtonTabbedPane extends JTabbedPane {
public CloseButtonTabbedPane() {
}
@Override
public void addTab(String title, Icon icon, Component component, String tip) {
    super.addTab(title, icon, component, tip);
    int count = this.getTabCount() - 1;
    setTabComponentAt(count, new CloseButtonTab(component, title, icon));
}
@Override
public void addTab(String title, Icon icon, Component component) {
    addTab(title, icon, component, null);
}
@Override
public void addTab(String title, Component component) {
    addTab(title, null, component);
}
public class CloseButtonTab extends JPanel {
    private Component tab;
    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);

        JLabel jLabel = new JLabel(title);
        jLabel.setIcon(icon);
        add(jLabel);
        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() {
            public void mouseClicked(MouseEvent e) {
                JTabbedPane tabbedPane = (JTabbedPane) getParent().getParent();
                tabbedPane.remove(tab);
            }
            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.DARK_GRAY, 1));
            }
            public void mouseExited(MouseEvent e) {
                JButton button = (JButton) e.getSource();
                button.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
            }
        });
        add(button);
    }
 }
}
  • 1
    You may want to consider revising your design to use `Action`, illustrated [here](http://stackoverflow.com/a/4039359/230513). – trashgod Nov 22 '14 at 12:55

2 Answers2

0

.In My Application It's working for Recently Opened Document only.

That is because your "tx" variable always references the most recently created JTextArea.

For your menu items you should be using an Action and you would create your Action by extending TextAction. The TextAction has a method that allows you to access the text component that last had focus. Then you do you processing on this component:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

public class TextFieldSelectAll
{
    private static void createAndShowGUI()
    {
        JPanel north = new JPanel();
        north.add( new JTextField("one", 10) );
        north.add( new JTextField("two", 10) );
        north.add( new JTextField("three", 10) );

        JButton selectAll = new JButton( new SelectAll() );

        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(north, BorderLayout.NORTH);
        frame.add(selectAll, BorderLayout.SOUTH);
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    static class SelectAll extends TextAction
    {
        public SelectAll()
        {
            super("Select All");
        }

        public void actionPerformed(ActionEvent e)
        {
            JTextComponent component = getFocusedComponent();
            component.selectAll();
            component.requestFocusInWindow();
        }
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}
camickr
  • 321,443
  • 19
  • 166
  • 288
0

As already explained by camickr, your "tx" field always references the most recently created text area. Also, when you switch tabs, you want to make sure that the selected text area displays according to the current "view spaces" setting.

I think both problems can be fixed by making the following changes:

  1. adding a list of text areas to keep track of them;
  2. add a change listener to the tabbedPane component to handle tab switches;
  3. add new text areas to this list as they are created;
  4. modify the viewSpaceActionPerformed method to determine the selected tab and rename it to setDocumentContents.

In code:

// Change 1 (before the constructor).
private final List<JTextArea> textAreas = new ArrayList<>();

// Change 2 (after assigning the tabbedPane field in the constructor).
tabbedPane.addChangeListener(new ChangeListener() {
    @Override
    public void stateChanged(final ChangeEvent changeEvent) {
        setDocumentContents();
    }
});

// Change 3 (after creating a text area in the openActionPerformed method).
textAreas.add(tx);

// Change 4 (replacing the viewSpaceActionPerformed method).
private void setDocumentContents() {
    final JTextArea textArea = textAreas.get(tabbedPane.getSelectedIndex());
    String previous = textArea.getText();
    if (viewSpace.isSelected()) {
        previous = previous.replaceAll(" ", ".");
    } else {
        previous = previous.replaceAll("\\.", " ");
    }
    textArea.setText(previous);
    textArea.setCaretPosition(0);
}
Community
  • 1
  • 1
Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28
  • Thank you for Giving reply,I Change My code with The Above Suggestions.But,It gives IndexOutOfBoundsException().This is not my Complete Application.I have show in Simple way of my problem.My Application Have Another Menu Items like Cut,Copy,Find,Replace like that.How can I call all these from Constructor And when I select the ViewSpace/cut/copy/find Menu Item Then only It process The according Action not through Constructor.Please Check My Application once and run it. – user3792689 Nov 24 '14 at 05:57
  • Can you apply the changes to the code in your question or post your complete application? Otherwise it's too difficult to reproduce the `IndexOutOfBoundsException` you encountered. – Freek de Bruijn Nov 24 '14 at 09:30