How to Apply Insert key action for all opened Documents - java

I want to apply Insert key Action(Available in keyboard as "Insert" key) for all the opened Documents.By default It didn't work for any document.I write the code for Insert key.But,In my program Insert key Action has worked for only recent opened file only.I want add this feature to all opened files.Please check it once.
Main Class:
public class InsertDemo extends javax.swing.JFrame {
JScrollPane scrollPane;
JTextArea textArea;
public InsertDemo() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
tabbedPane = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
file = new javax.swing.JMenu();
newFile = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
file.setText("File");
newFile.setText("NewFile");
newFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newFileActionPerformed(evt);
}
});
file.add(newFile);
jMenuBar1.add(file);
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, 400, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void newFileActionPerformed(java.awt.event.ActionEvent evt) {
textArea=new CaretTextArea();
scrollPane=new JScrollPane(textArea);
tabbedPane.add(scrollPane);
}
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(InsertDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InsertDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InsertDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InsertDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new InsertDemo().setVisible(true);
}
});
}
private javax.swing.JMenu file;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem newFile;
private javax.swing.JTabbedPane tabbedPane;
}
Insert Action class.I create the JtextArea reference through this class.This is extended class of JTextArea.
public class CaretTextArea extends JTextArea {
private boolean isInsertMode=false;
Color oldCaretColor;
Color insertCaretColor=new Color(254, 254, 254);
public CaretTextArea() {
MyCaret c=new MyCaret();
c.setBlinkRate(getCaret().getBlinkRate());
setCaret(c);
oldCaretColor=getCaretColor();
addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e){
if (isInsertMode()) {
processCaretWidth();
}
}
});
Keymap kMap=this.getKeymap();
Action a=new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
setInsertMode(!isInsertMode());
}
};
kMap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT,0),a);
}
public boolean isInsertMode() {
return isInsertMode;
}
public void setInsertMode(boolean insertMode) {
isInsertMode = insertMode;
processMode();
}
private void processMode() {
if (isInsertMode()) {
processCaretWidth();
setCaretColor(insertCaretColor);
}
else {
setCaretColor(oldCaretColor);
putClientProperty("caretWidth", 1);
}
}
private void processCaretWidth() {
try {
int pos=getCaretPosition();
Rectangle rPos=modelToView(pos)!=null ? modelToView(pos).getBounds() :new Rectangle();
int caretX=rPos.x;
int caretEndX=rPos.x;
if (pos<getDocument().getLength()) {
Rectangle rNextPos=modelToView(pos+1)!=null ? modelToView(pos+1).getBounds(): new Rectangle();
if (rPos.y==rNextPos.y) {
caretEndX=rNextPos.x;
}
}
putClientProperty("caretWidth", Math.max(1, caretEndX-caretX+1));
} catch (BadLocationException e) {
// e.printStackTrace();
}
}
#Override
public void replaceSelection(String content) {
if (isEditable() && isInsertMode() && getSelectionStart()==getSelectionEnd()) {
int pos=getCaretPosition();
int lastPos=Math.min(getDocument().getLength(), pos+content.length());
select(pos, lastPos);
}
super.replaceSelection(content);
}
class MyCaret extends DefaultCaret {
public void paint(Graphics g) {
if (isInsertMode()) {
//we should shift to half width because of DefaultCaret rendering algorithm
AffineTransform old=((Graphics2D)g).getTransform();
int w=(Integer)getClientProperty("caretWidth");
g.setXORMode(Color.black);
g.translate(w/2,0);
super.paint(g);
((Graphics2D)g).setTransform(old);
}
else {
super.paint(g);
}
}
protected synchronized void damage(Rectangle r) {
if (isInsertMode()) {
if (r != null) {
int damageWidth = (Integer)getClientProperty("caretWidth");
x = r.x - 4 - (damageWidth/2 );
y = r.y;
width = 9 + 3*damageWidth/2;
height = r.height;
repaint();
}
}
else {
super.damage(r);
}
}
}
}

Related

How to implement Undo and Redo for JTextArea

I have Developed a Swing Based Application based on JTextArea.I Add Undo and Redo Options to My Application.I have Three Menu Items,Open,Rollback and Redo.My problem is when I open more than one Empty Documents and write some text on opened Documents.When I click on Rollback the contents of all opened Documents are removed/rollback not only focus Document.Please Check it.Thank you.
My Code:
public class UndoAndRedo extends javax.swing.JFrame {
int i = 0;
JTextArea textArea;
JScrollPane scrollPane;
int tabCount=0;
UndoManager undoManager = new UndoManager();
public UndoAndRedo() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
open = new javax.swing.JMenuItem();
rollback = new javax.swing.JMenuItem();
redo = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
fileMenu.setText("File");
open.setText("Open");
open.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openActionPerformed(evt);
}
});
fileMenu.add(open);
rollback.setText("Rollback");
rollback.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rollbackActionPerformed(evt);
}
});
fileMenu.add(rollback);
redo.setText("Redo");
redo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
redoActionPerformed(evt);
}
});
fileMenu.add(redo);
jMenuBar1.add(fileMenu);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}
private void openActionPerformed(java.awt.event.ActionEvent evt) {
textArea=new JTextArea();
textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
textArea.setDocument(new CustomUndoPlainDocument());
scrollPane=new JScrollPane(textArea);
tabCount++;
tp.addTab("Document "+tabCount, null, scrollPane, "Document "+tabCount);
try {
tp.setSelectedIndex(tabCount-1);
}
catch(IndexOutOfBoundsException i) {
}
textArea.requestFocus();
textArea.setCaretPosition(0);
textArea.getDocument().addUndoableEditListener(undoManager);
}
private void rollbackActionPerformed(java.awt.event.ActionEvent evt) {
if (undoManager.canUndo()) {
undoManager.undo();
}
}
private void redoActionPerformed(java.awt.event.ActionEvent evt) {
if (undoManager.canRedo()) {
undoManager.redo();
}
}
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(UndoAndRedo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UndoAndRedo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UndoAndRedo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UndoAndRedo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UndoAndRedo().setVisible(true);
}
});
}
private javax.swing.JMenu fileMenu;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JMenuItem redo;
private javax.swing.JMenuItem rollback;
private javax.swing.JTabbedPane tp;
class CustomUndoPlainDocument extends PlainDocument {
private CompoundEdit compoundEdit;
#Override protected void fireUndoableEditUpdate(UndoableEditEvent e) {
if (compoundEdit == null) {
super.fireUndoableEditUpdate(e);
} else {
compoundEdit.addEdit(e.getEdit());
}
}
#Override public void replace(
int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
if (length == 0) {
super.replace(offset, length, text, attrs);
} else {
compoundEdit = new CompoundEdit();
super.fireUndoableEditUpdate(new UndoableEditEvent(this, compoundEdit));
super.replace(offset, length, text, attrs);
compoundEdit.end();
compoundEdit = null;
}
}
}
}

How To Work Menu Items For All Opened Documents in Java Swing

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);
}
}
}
.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();
}
});
}
}
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:
adding a list of text areas to keep track of them;
add a change listener to the tabbedPane component to handle tab switches;
add new text areas to this list as they are created;
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);
}

How To Write Close All Action For All Documents using Swing

I want to write close all action for all created documents. My application has Create and CloseAll menu items. When I create a single document and write some code on that then I click on CloseAll, it asks conformation dialog box "Whether do you want to save or not".
This case is working fine for me. But when I create multiple documents (more than five) and some documents are empty, some documents have text. Then I click on CloseAll menu item, it should ask conformation dialog box for all documents that have text. But my code is not working in this case. How can I achieve this?
My Working Code:
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;
}
}

How to add JLabel to existing JTextField

I want to add Capslock label to the status JtextField. Status has got line and column values. I want to add capslock with line and column. I have tried adding updateStatus() method, but it does not work as expected.
Sample code:
public class CapsLock extends javax.swing.JFrame {
JTextField status;
int i=0;
JTextArea textArea;
JLabel capsLock;
public CapsLock() {
initComponents();
status=new JTextField();
capsLock=new JLabel();
updateStatus(1,1);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tabbedPane = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
file = new javax.swing.JMenu();
newFile = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
file.setText("File");
newFile.setText("NewFile");
newFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newFileActionPerformed(evt);
}
});
file.add(newFile);
jMenuBar1.add(file);
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, 400, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void updateStatus(int linenumber, int columnnumber) {
status.setText("ln: " + linenumber + " Col: " + columnnumber);
}
private void newFileActionPerformed(java.awt.event.ActionEvent evt) {
final JInternalFrame internalFrame = new JInternalFrame("");
i++;
internalFrame.setName("Doc "+i);
internalFrame.setClosable(true);
internalFrame.setAutoscrolls(true);
textArea=new JTextArea();
textArea.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent ke) {
}
#Override
public void keyPressed(KeyEvent ke) {
if(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)){
capsLock.setText("ON");
}
else{
capsLock.setText("OFF");
status.setText(capsLock.getText());
}
}
#Override
public void keyReleased(KeyEvent ke) {
}
});
textArea.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
JTextArea editArea = (JTextArea)e.getSource();
int linenum = 1;
int columnnum = 1;
try {
int caretpos = editArea.getCaretPosition();
linenum = editArea.getLineOfOffset(caretpos);
columnnum = caretpos - editArea.getLineStartOffset(linenum);
linenum += 1;
}
catch(Exception ex) { }
updateStatus(linenum, columnnum);
}
});
status.setBackground(Color.LIGHT_GRAY);
status.setEditable(false);
internalFrame.add(textArea);
internalFrame.add(status,BorderLayout.SOUTH);
tabbedPane.add(internalFrame);
}
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(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CapsLock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CapsLock().setVisible(true);
}
});
}
private javax.swing.JMenu file;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem newFile;
private javax.swing.JTabbedPane tabbedPane;
}
I write StatusPanel class as shown below:
public class StatusPanel extends JPanel{
InternalFrame currentFrame;
private JLabel statusLabel;
JLabel capsLabel;
public StatusPanel(){
statusLabel=new JLabel();
capsLabel=new JLabel();
add(statusLabel);
add(capsLabel);
updateStatus(1,1);
}
public void setRowColumn(){
currentFrame.textPane.addCaretListener(new CaretListener() {
private KeyEvent KeyEvent;
#Override
public void caretUpdate(CaretEvent e) {
int linenum = 1;
int columnnum = 1;
try {
int caretpos = currentFrame.textPane.getCaretPosition();
linenum=currentFrame.getLineAtCaret()-1;
columnnum=currentFrame.getColumnAtCaret();
linenum += 1;
}
catch(Exception ex) { }
updateStatus(linenum, columnnum);
}
});
}
private void updateStatus(int linenumber, int columnnumber)
{
statusLabel.setText("Line: " + linenumber +" "+ " Column: " + columnnumber);
}
public void setCapslock(){
currentFrame.textPane.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent ke) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void keyPressed(KeyEvent ke) {
if(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)){
capsLabel.setText(" CAPS ON");
}
else{
capsLabel.setText(" CAPS OFF");
}
}
#Override
public void keyReleased(KeyEvent ke) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
}
}
In the "if" code you have a single statement. In the "else" statement you have 2 statements. Don't you think the code should be the same except for the text?
Also, you should NOT be using a text field to display the text. Instead you should be using a panel with multiple labels. One label for the row/column position. Another label for the Caps Lock status. Then you only update the text for the label that changes.
.Caps lock enable/disable not update the all the opened Documents.
Then you have a couple of solutions:
Your status bar should be common for the frame, not the Document. So the labels will be shared by all Documents. This means that whenever a Document gains focus you would need to update the caret position but the Caps Lock will still be correct from the last Document.
Or, you could create the Caps Lock field as a non-editable JTextField. Then you can share the Document of the text field with all text field. This mean when you update the text field it will be reflected on all documents.
So you would need to pass in the shared text field Document any time you create a new document for your application. Then to create the text field you would use:
JTextField textField = new JTextField( sharedDocument );
Edit:
When you create the component for the frame you would have code something like:
StatusPanel status = new StatusPanel();
frame.add(status, ...);
Then in this custom class you add the components to display the data you want displayed. You also need to add methods like setRowColumn(...) and setCapsLock(...) to display the text you want to see for those components.
Then you need to create another custom class MyInternalFrame that extend JInternalFrame. Then when you create this class you use:
MyInternalFrame internal = new MyInternalFrame(status);
So now your custom internal frame has access to the status bar and you can update the status bar from any Document that your create.
Another Edit:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class Status extends JPanel
{
public Status()
{
setLayout( new BorderLayout() );
StatusPanel status = new StatusPanel();
add(status, BorderLayout.SOUTH);
DocumentPanel document = new DocumentPanel( status );
add(document, BorderLayout.CENTER);
}
class StatusPanel extends JPanel
{
JLabel caretStatus = new JLabel("Caret Offset: 0");
public StatusPanel()
{
add( caretStatus );
}
public void updateCaretStatus(String status)
{
caretStatus.setText( status );
}
}
class DocumentPanel extends JPanel
{
private StatusPanel status;
private JTextArea textArea;
public DocumentPanel(StatusPanel statusPanel)
{
status = statusPanel;
textArea = new JTextArea(5, 30);
add( new JScrollPane( textArea ) );
textArea.addCaretListener( new CaretListener()
{
#Override
public void caretUpdate(CaretEvent e)
{
status.updateCaretStatus( "Caret Offset: " + textArea.getCaretPosition() );
}
});
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Status");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new Status() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

How to work functionality for all Documents in swing

I want work functionality for all opened Documents not current open Document only. I had created one swing application. I was open an Document. The cut, copy, paste and selectAll operations through menuItem work for currently opened documents; not working for the previous opened Documents. Please help me.
Here is my code:
public class OpenDemo extends javax.swing.JFrame implements ChangeListener{
JTextPane textPane;
JTextPane lnNum;
JScrollPane scrollPane;
int i=0;
JTextField status;
ArrayList<JTextPane> textPanes=new ArrayList<>();
public OpenDemo() {
initComponents();
viewLineNumbers.setSelected(false);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
open = new javax.swing.JMenuItem();
cut = new javax.swing.JMenuItem();
selectAll = new javax.swing.JMenuItem();
viewLineNumbers = 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);
cut.setText("Cut");
cut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cutActionPerformed(evt);
}
});
jMenu1.add(cut);
selectAll.setText("SelectAll");
selectAll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectAllActionPerformed(evt);
}
});
jMenu1.add(selectAll);
viewLineNumbers.setSelected(true);
viewLineNumbers.setText("ViewLineNumbers");
viewLineNumbers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewLineNumbersActionPerformed(evt);
}
});
jMenu1.add(viewLineNumbers);
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)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void updateStatus(int linenumber, int columnnumber) {
status.setText("Line: " + linenumber + " Column: " + columnnumber);
}
private void openActionPerformed(java.awt.event.ActionEvent evt) {
FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
fd.show();
String title;
String sts;
File f;
if (fd.getFile() != null) {
sts = fd.getDirectory() + fd.getFile();
title=fd.getFile();
System.out.println(sts);
title=fd.getFile();
BufferedReader br = null;
StringBuffer str = new StringBuffer("");
try {
br = new BufferedReader(new FileReader(sts));
String line;
try {
while ((line = br.readLine()) != null) {
str.append(line + "\n");
}
} catch (IOException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
String t = str.toString();
final JInternalFrame internalFrame = new JInternalFrame("",true,true);
textPane = new JTextPane();
textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
internalFrame.add(textPane);
i++;
internalFrame.setName("Doc "+i);
internalFrame.setTitle(title);
try {
internalFrame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
textPane.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
JTextPane editArea = (JTextPane)e.getSource();
int linenum = 1;
int columnnum = 1;
try {
int caretpos = editArea.getCaretPosition();
linenum=getLineAtCaret(editArea)-1;
columnnum=getColumnAtCaret(editArea);
linenum += 1;
}
catch(Exception ex) { }
updateStatus(linenum, columnnum);
}
});
status=new JTextField();
status.setBackground(Color.LIGHT_GRAY);
internalFrame.add(status,BorderLayout.SOUTH);
tp.add(internalFrame);
scrollPane=new JScrollPane(textPane);
tp.setSelectedIndex(i-1);
internalFrame.add(scrollPane);
internalFrame.setVisible(true);
textPane.setText(t);
tp.addChangeListener(this);
textPanes.add(textPane);
textPane.setCaretPosition(0);
}
}
private void cutActionPerformed(java.awt.event.ActionEvent evt) {
textPane.cut();
}
private void selectAllActionPerformed(java.awt.event.ActionEvent evt) {
textPane.selectAll();
}
private void viewLineNumbersActionPerformed(java.awt.event.ActionEvent evt) {
AbstractButton button = (AbstractButton) evt.getSource();
if(button.isSelected()){
lnNum = new JTextPane();
lnNum.setEditable(false);
lnNum.setSize(50,50);
lnNum.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
lnNum.setText(getText());
textPane.getDocument().addDocumentListener(new DocumentListener(){
#Override
public void changedUpdate(DocumentEvent de) {
lnNum.setText(getText());
}
#Override
public void insertUpdate(DocumentEvent de) {
lnNum.setText(getText());
}
#Override
public void removeUpdate(DocumentEvent de) {
lnNum.setText(getText());
}
});
scrollPane.getViewport().add(textPane);
scrollPane.setRowHeaderView(lnNum);
}
else{
scrollPane.setRowHeaderView(null);
}
}
public String getText(){
int caretPosition = textPane.getDocument().getLength();
javax.swing.text.Element root = textPane.getDocument().getDefaultRootElement();
String text = "1" + System.getProperty("line.separator");
for(int i = 2; i <= root.getElementIndex( caretPosition ) + 1; i++){
text += i + System.getProperty("line.separator");
}
return text;
}
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(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OpenDemo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem cut;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JMenuItem selectAll;
private javax.swing.JTabbedPane tp;
private javax.swing.JCheckBoxMenuItem viewLineNumbers;
// End of variables declaration
#Override
public void stateChanged(ChangeEvent ce) {
JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
int index = sourceTabbedPane.getSelectedIndex();
try
{
textPane =textPanes.get(index);
}
catch(IndexOutOfBoundsException e1){
}
}
public int getLineAtCaret(JTextComponent component)
{
int caretPosition = component.getCaretPosition();
Element root = component.getDocument().getDefaultRootElement();
return root.getElementIndex( caretPosition ) + 1;
}
public int getColumnAtCaret(JTextComponent component)
{
FontMetrics fm = component.getFontMetrics( component.getFont() );
int characterWidth = fm.stringWidth( "0" );
int column = 0;
try
{
Rectangle r = component.modelToView( component.getCaretPosition() );
int width = r.x - component.getInsets().left;
column = width / characterWidth;
}
catch(BadLocationException ble) {}
return column + 1;
}
}
I think, i managed to answer all your problems, but i needed to create another class which i called 'OInternalFrame', so i will give you both code for those class. Tell me if that's what you were trying to achieve :
OpenDemo :
import java.awt.FileDialog;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractButton;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
public class OpenDemo extends javax.swing.JFrame implements ChangeListener{
private ArrayList<OInternalFrame> frames = new ArrayList<OInternalFrame>();
private OInternalFrame currentFrame;
int i=0;
public OpenDemo() {
initComponents();
viewLineNumbers.setSelected(false);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
open = new javax.swing.JMenuItem();
cut = new javax.swing.JMenuItem();
selectAll = new javax.swing.JMenuItem();
viewLineNumbers = 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);
cut.setText("Cut");
cut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cutActionPerformed(evt);
}
});
jMenu1.add(cut);
selectAll.setText("SelectAll");
selectAll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectAllActionPerformed(evt);
}
});
jMenu1.add(selectAll);
viewLineNumbers.setSelected(true);
viewLineNumbers.setText("ViewLineNumbers");
viewLineNumbers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewLineNumbersActionPerformed(evt);
}
});
jMenu1.add(viewLineNumbers);
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)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void openActionPerformed(java.awt.event.ActionEvent evt) {
FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
fd.show();
String title;
String sts;
if (fd.getFile() != null) {
sts = fd.getDirectory() + fd.getFile();
title=fd.getFile();
System.out.println(sts);
title=fd.getFile();
BufferedReader br = null;
StringBuffer str = new StringBuffer("");
try {
br = new BufferedReader(new FileReader(sts));
String line;
try {
while ((line = br.readLine()) != null) {
str.append(line + "\n");
}
} catch (IOException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
String t = str.toString();
OInternalFrame internalFrame = new OInternalFrame("",true,true);
i++;
internalFrame.setName("Doc "+i);
internalFrame.setTitle(title);
try {
internalFrame.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e) {
i--;
frames.remove(currentFrame);
tp.remove(currentFrame);
for(OInternalFrame frame : frames)
{
int index=frames.indexOf(frame);
tp.setTitleAt(index, "Doc "+(index+1));
}
}
});
tp.add(internalFrame);
tp.setSelectedIndex(i-1);
tp.addChangeListener(this);
frames.add(internalFrame);
currentFrame=internalFrame;
currentFrame.setText(t);
currentFrame.setVisible(true);
currentFrame.setLineViewer(viewLineNumbers.isSelected());
}
}
private void cutActionPerformed(java.awt.event.ActionEvent evt) {
currentFrame.cut();
}
private void selectAllActionPerformed(java.awt.event.ActionEvent evt) {
currentFrame.selectAll();
}
private void viewLineNumbersActionPerformed(java.awt.event.ActionEvent evt) {
AbstractButton button = (AbstractButton) evt.getSource();
currentFrame.setLineViewer(viewLineNumbers.isSelected());
}
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(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OpenDemo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem cut;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JMenuItem selectAll;
private javax.swing.JTabbedPane tp;
private javax.swing.JCheckBoxMenuItem viewLineNumbers;
// End of variables declaration
#Override
public void stateChanged(ChangeEvent ce) {
JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
int index = sourceTabbedPane.getSelectedIndex();
try
{
currentFrame =frames.get(index);
currentFrame.setLineViewer(viewLineNumbers.isSelected());
}
catch(IndexOutOfBoundsException e1){
}
}
public int getLineAtCaret(JTextComponent component)
{
int caretPosition = component.getCaretPosition();
Element root = component.getDocument().getDefaultRootElement();
return root.getElementIndex( caretPosition ) + 1;
}
public int getColumnAtCaret(JTextComponent component)
{
FontMetrics fm = component.getFontMetrics( component.getFont() );
int characterWidth = fm.stringWidth( "0" );
int column = 0;
try
{
Rectangle r = component.modelToView( component.getCaretPosition() );
int width = r.x - component.getInsets().left;
column = width / characterWidth;
}
catch(BadLocationException ble) {}
return column + 1;
}
}
OInternalFrame :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
public class OInternalFrame extends JInternalFrame
{
private JTextArea textPane;
private JScrollPane scrollPane;
private JTextPane linePane;
private JTextField status;
private DocumentListener listen;
public OInternalFrame(String title,boolean resizable,boolean closable)
{
super(title,resizable,closable);
initComponents();
initListeners();
}
private void initComponents()
{
textPane = new JTextArea();
linePane = new JTextPane();
status = new JTextField();
scrollPane = new JScrollPane();
textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
status.setBackground(Color.LIGHT_GRAY);
linePane.setEditable(false);
linePane.setSize(50,50);
linePane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
status.setEditable(false);
// add(textPane);
add(scrollPane);
add(status,BorderLayout.SOUTH);
scrollPane.getViewport().add(textPane);
scrollPane.setRowHeaderView(linePane);
setVisible(true);
linePane.setVisible(false);
updateStatus(1,1);
scrollPane.setVisible(true);
}
private void initListeners()
{
textPane.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
int linenum = 1;
int columnnum = 1;
try {
int caretpos = textPane.getCaretPosition();
linenum=getLineAtCaret()-1;
columnnum=getColumnAtCaret();
linenum += 1;
}
catch(Exception ex) { }
updateStatus(linenum, columnnum);
}
});
listen = new DocumentListener(){
#Override
public void changedUpdate(DocumentEvent de) {
linePane.setText(getText());
}
#Override
public void insertUpdate(DocumentEvent de) {
linePane.setText(getText());
}
#Override
public void removeUpdate(DocumentEvent de) {
linePane.setText(getText());
}
};
}
public int getLineAtCaret()
{
int line = 0;
int caretPosition = textPane.getCaretPosition();
try {
line = textPane.getLineOfOffset(caretPosition);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return line+1;
}
public int getColumnAtCaret()
{
FontMetrics fm = textPane.getFontMetrics( textPane.getFont() );
int characterWidth = fm.stringWidth( "0" );
int column = 0;
try
{
Rectangle r = textPane.modelToView( textPane.getCaretPosition() );
int width = r.x - textPane.getInsets().left;
column = width / characterWidth;
}
catch(BadLocationException ble) {}
return column + 1;
}
private void updateStatus(int linenumber, int columnnumber)
{
status.setText("Line: " + linenumber + " Column: " + columnnumber);
}
public void setText(String t)
{
System.out.println(t);
textPane.setText(t);
textPane.setCaretPosition(0);
textPane.setVisible(true);
textPane.repaint();
}
public void setLineViewer(boolean enabled)
{
if(enabled)
{
linePane.setText(getText());
linePane.setCaretPosition(0);
linePane.revalidate();
linePane.repaint();
textPane.getDocument().addDocumentListener(listen);
}
else
{
linePane.setText("");
textPane.getDocument().removeDocumentListener(listen);
}
linePane.setVisible(enabled);
}
public void cut()
{
textPane.cut();
}
public void selectAll()
{
textPane.selectAll();
}
public String getText(){
int caretPosition = textPane.getLineCount();
String text = "1" + System.getProperty("line.separator");
for(int i = 2; i <= caretPosition-1; i++){
text += i + System.getProperty("line.separator");
}
return text;
}
}
Use the Actions provided by the DefaultEditorKit. For example:
JMenuItem cut = new DefaultEditorKit.CutAction();
For a "SelectAll" Action you will need to create your own by extending TextAction:
class SelectAll extends TextAction
{
public SelectAll()
{
super("Select All");
}
public void actionPerformed(ActionEvent e)
{
JTextComponent component = getFocusedComponent();
component.selectAll();
}
}
These Actions will work on the last text component that had focus.

Categories