How to work functionality for all Documents in swing - java

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.

Related

Is there any method i can add a scroll pane to a jlist that its added on a panel with null layout?

I'm doing a school project based on a medical store and I want to add a scroll pane to all my 3 lists that I'm using
package Interfata;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing. * ;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;
public class Home extends JFrame {
JPanel panelHome;
static String[] listaplante = new String[10];
static String[] listacantitati = new String[10];
static String[] listapreturi = new String[10];
static int kPlante = 0,
kCantitati = 0,
kPreturi = 0;
JButton butonCumpara,
butonAdauga;
JTextField denumireField,
pretField,
cantitateField,
cantitateDoritaField;
public JPanel createHomeContentPane() {
//Creez un panel pe care sa pun toate campurile.
panelHome = new JPanel();
panelHome.setLayout(null);
panelHome.setBackground(new java.awt.Color(204, 204, 255));
panelHome.setBorder(javax.swing.BorderFactory.createTitledBorder("Home"));
//Creez lista cu plante
DefaultListModel < String > listaPlante = new DefaultListModel < >();
JList < String > list = new JList < >(citirePlante());
list.setBounds(50, 75, 75, 100);
list.setSelectionBackground(Color.ORANGE);
panelHome.add(list);
//Creez lista cu cantitatile fiecarei plante
DefaultListModel < String > listaCantitati = new DefaultListModel < >();
JList < String > list2 = new JList < >(citireCantitati());
list2.setBounds(150, 75, 75, 100);
list2.setSelectionBackground(Color.YELLOW);
panelHome.add(list2);
//Creez lista cu preturile fiecarei plante
DefaultListModel < String > listaPreturi = new DefaultListModel < >();
JList < String > list3 = new JList < >(citirePreturi());
list3.setBounds(250, 75, 75, 100);
list3.setSelectionBackground(Color.GREEN);
panelHome.add(list3);
//Creez titlurile pt fiecare lista
JLabel denumireLabel = new JLabel("Denumire:");
denumireLabel.setBounds(50, 55, 70, 20);
panelHome.add(denumireLabel);
JLabel cantitatiLabel = new JLabel("Cantitati:");
cantitatiLabel.setBounds(150, 55, 70, 20);
panelHome.add(cantitatiLabel);
JLabel preturiLabel = new JLabel("Preturi:");
preturiLabel.setBounds(250, 55, 70, 20);
panelHome.add(preturiLabel);
//Creez un camp pt a adauga cantitatea dorita care urmeaza a fi cumparata
//cantitateDoritaField
cantitateDoritaField = new JTextField();
cantitateDoritaField.setBounds(80, 200, 100, 20);
cantitateDoritaField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt cantitateField
final String placeholderCantitateDorita = "Cantitatea dorita";
cantitateDoritaField.setText(placeholderCantitateDorita);
cantitateDoritaField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
cantitateDoritaField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (cantitateDoritaField.getText().isEmpty()) {
cantitateDoritaField.setText(placeholderCantitateDorita);
showingPlaceholder = true;
}
}
});
panelHome.add(cantitateDoritaField);
//Butonul de cumparare
butonCumpara = new JButton("Cumpara");
butonCumpara.setLocation(180, 200);
butonCumpara.setSize(100, 20);
butonCumpara.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
String plantaselectata = list.getSelectedValue();
int indexplanta = list.getSelectedIndex();
String cantitateselectata = list2.getSelectedValue();
int indexcantitate = list2.getSelectedIndex();
String pretselectat = list3.getSelectedValue();
int indexpret = list3.getSelectedIndex();
String cantitatedorita = cantitateDoritaField.getText();
int valCantitate = Integer.valueOf(cantitateselectata);
int valCantitateDorita = Integer.valueOf(cantitatedorita);
int valPret = Integer.valueOf(pretselectat);
if (indexplanta == indexcantitate && indexplanta == indexpret) {
if (valCantitateDorita <= valCantitate) {
try {
afisPlantaCumparata(plantaselectata, valCantitateDorita);
} catch(IOException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
int a = valCantitate - valCantitateDorita;
String b = Integer.toString(a);
listacantitati[indexcantitate] = b;
panelHome.setVisible(false);
panelHome.setVisible(true);
}
else {
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Cantitatea nu esti disponibila", "Eroare de cumparare", JOptionPane.WARNING_MESSAGE);
}
}
else {
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Planta, cantitate si pretul nu sunt din aceeasi categorie", "Eroare de cumparare", JOptionPane.WARNING_MESSAGE);
}
}
});
panelHome.add(butonCumpara);
//Cumpurile denumire cantitate si pret pt adaugarea plantei
//denumireField
denumireField = new JTextField();
denumireField.setBounds(80, 240, 100, 20);
denumireField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt denumireField
final String placeholderDenumire = "Denumire";
denumireField.setText(placeholderDenumire);
denumireField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
denumireField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (denumireField.getText().isEmpty()) {
denumireField.setText(placeholderDenumire);
showingPlaceholder = true;
}
}
});
panelHome.add(denumireField);
//cantitateField
cantitateField = new JTextField();
cantitateField.setBounds(80, 260, 100, 20);
cantitateField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt cantitateField
final String placeholderCantitate = "Cantitatea";
cantitateField.setText(placeholderCantitate);
cantitateField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
cantitateField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (cantitateField.getText().isEmpty()) {
cantitateField.setText(placeholderCantitate);
showingPlaceholder = true;
}
}
});
panelHome.add(cantitateField);
//pretField
pretField = new JTextField();
pretField.setBounds(80, 280, 100, 20);
pretField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt pretField
final String placeholderPret = "Pret";
pretField.setText(placeholderPret);
pretField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
pretField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (pretField.getText().isEmpty()) {
pretField.setText(placeholderPret);
showingPlaceholder = true;
}
}
});
panelHome.add(pretField);
//Butonul de adaugare a unei plantei noi
butonAdauga = new JButton("Adauga");
butonAdauga.setLocation(180, 260);
butonAdauga.setSize(100, 20);
butonAdauga.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
String denumireNou = denumireField.getText();
String cantitateNou = cantitateField.getText();
String pretNou = pretField.getText();
listaplante[kPlante++] = denumireNou;
listacantitati[kCantitati++] = cantitateNou;
listapreturi[kPreturi++] = pretNou;
panelHome.setVisible(false);
panelHome.setVisible(true);
}
});
panelHome.add(butonAdauga);
//Returnez panelul
panelHome.setOpaque(true);
return panelHome;
}
public static String[] citirePlante() {
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Plante.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listaplante[kPlante] = strCurrentLine;
kPlante++;
}
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null) objReader.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
return listaplante;
}
public static String[] citireCantitati() {
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Cantitati.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listacantitati[kCantitati] = strCurrentLine;
kCantitati++;
}
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null) objReader.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
return listacantitati;
}
public static String[] citirePreturi() {
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Preturi.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listapreturi[kPreturi] = strCurrentLine;
kPreturi++;
}
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null) objReader.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
return listapreturi;
}
public static void afisPlantaCumparata(String p, int c) throws IOException {
FileWriter writer = new FileWriter("PlanteVandute.txt", true);
try (
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(p + " " + c + "\n");
} catch(IOException e) {
System.err.format("IOException: %s%n", e);
}
}
private static void Home() {
JFrame frameHome = new JFrame("PLAFAR * Calinescu George-Catalin * 221");
//Creez panelul peste frame si il stilizez
Home home = new Home();
frameHome.setContentPane(home.createHomeContentPane());
frameHome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameHome.setSize(400, 350);
frameHome.setVisible(true);
}
public static void main(String[] args) {
//Creez GUI si il afisez pe ecran
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Home();
}
});
}
}
Is there any method I can add a scroll pane to list, list2 and list3? I really don't want to set another layout type because I'm not used to them and I worked with absolute layout when I started doing this GUI but I ran into some problems and I decided to wrote all the code by hand.
Thank you for providing example code / minimal working example. (One remark - if no Plante.txt is found an exception is thrown. You could improve your code to handle this behavior, e.g., with a warning or message for the user.)
You can add your JList to a JScrollPane like this:
// to ensure single selection in your list
someList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollPane = new JScrollPane(someList);
Then, you have to add scollPane to a LayoutManager or (in your example) JPanel.
It's strongly recommended to use a normal layout manager, because layout manager allows to handle components sizes, when Window/Panel is resized. It's also provides better support for different Look and Feels and OS.
To get your code working you need to install scroll pane around your list.
DefaultListModel<String> listaPlante = new DefaultListModel<>();
JList<String> list = new JList<>(citirePlante());
JScrollPane scroller = new JScrollPane(list);
scroller.setBounds(50,75, 75,100); // not list!!!
list.setSelectionBackground(Color.ORANGE);
panelHome.add(scroller); // not list!!!

How to switch java Frames?

So i'm doing a school project based on a medical store (it's about plants). I have two classes(each has one JFrame).
Login:
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JOptionPane;
public class Login extends JFrame{
JPanel panelLogin;
JTextField usernameField;
JPasswordField parolaField;
JButton butonLogin,butonCancel;
public JPanel createContentPane (){
//Creez un panel pe care sa pun toate campurile.
panelLogin = new JPanel();
panelLogin.setLayout(null);
panelLogin.setBackground(new java.awt.Color(204, 204, 255));
panelLogin.setBorder(javax.swing.BorderFactory.createTitledBorder("Login"));
//usernameField
usernameField = new JTextField();
usernameField.setLocation(50, 50);
usernameField.setSize(300, 25);
usernameField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt usernameField
final String placeholderUsername = "Username";
usernameField.setText(placeholderUsername);
usernameField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
usernameField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (usernameField.getText().isEmpty()) {
usernameField.setText(placeholderUsername);
showingPlaceholder = true;
}
}
});
panelLogin.add(usernameField);
//parolaField
parolaField = new JPasswordField();
parolaField.setLocation(50, 100);
parolaField.setSize(300, 25);
parolaField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt parolaField
final String placeholderParola = "Parola";
parolaField.setText(placeholderParola);
parolaField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
parolaField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (parolaField.getText().isEmpty()) {
parolaField.setText(placeholderParola);
showingPlaceholder = true;
}
}
});
panelLogin.add(parolaField);
//butonLogin
butonLogin = new JButton("Login");
butonLogin.setLocation(70, 140);
butonLogin.setSize(100, 20);
butonLogin.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
butonLoginActionPerformed(evt);
/*
String uname=usernameField.getText();
String pword=parolaField.getText();
if(uname.equals("admin") && pword.equals("admin")){
Home home=new Home();
home.setVisible(true);
//this.dispose();
}
else{
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Username sau parola incorecte","Eroare la conectare",JOptionPane.WARNING_MESSAGE);
}*/
}
});
panelLogin.add(butonLogin);
//butonCancel
butonCancel = new JButton("Cancel");
butonCancel.setLocation(220, 140);
butonCancel.setSize(100, 20);
butonCancel.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
});
panelLogin.add(butonCancel);
//Returnez panelul
panelLogin.setOpaque(true);
return panelLogin;
}
private static void LoginGUI() {
JFrame frameLogin = new JFrame("PLAFAR * Calinescu George-Catalin * 221");
//Creez panelul peste frame si il stilizez
Login login = new Login();
frameLogin.setContentPane(login.createContentPane());
frameLogin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameLogin.setSize(400, 250);
frameLogin.setVisible(true);
}
private void butonLoginActionPerformed(java.awt.event.ActionEvent evt) {
String uname=usernameField.getText();
String pword=parolaField.getText();
if(uname.equals("admin") && pword.equals("admin")){
Home ho=new Home();
ho.setVisible(true);
this.dispose();
}
else{
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Username sau parola incorecte","Eroare la conectare",JOptionPane.WARNING_MESSAGE);
}
}
public static void main(String[] args) {
//Creez GUI si il afisez pe ecran
SwingUtilities.invokeLater(new Runnable() {
public void run() {
LoginGUI();
}
});
}
}
and Home:
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;
public class Home extends JFrame{
JPanel panelHome;
static String[] listaplante=new String[10];
static String[] listacantitati=new String[10];
static String[] listapreturi=new String[10];
static int kPlante=0, kCantitati=0, kPreturi=0;
JButton butonCumpara,butonAdauga;
JTextField cantitateField;
public JPanel createHomeContentPane (){
//Creez un panel pe care sa pun toate campurile.
panelHome = new JPanel();
panelHome.setLayout(null);
panelHome.setBackground(new java.awt.Color(204, 204, 255));
panelHome.setBorder(javax.swing.BorderFactory.createTitledBorder("Home"));
//Creez lista cu plante
DefaultListModel<String> listaPlante = new DefaultListModel<>();
JList<String> list = new JList<>(citirePlante());
list.setBounds(50,100, 75,75);
panelHome.add(list);
//Creez lista cu cantitatile fiecarei plante
DefaultListModel<String> listaCantitati = new DefaultListModel<>();
JList<String> list2 = new JList<>(citireCantitati());
list2.setBounds(150,100, 75,75);
panelHome.add(list2);
//Creez lista cu preturile fiecarei plante
DefaultListModel<String> listaPreturi = new DefaultListModel<>();
JList<String> list3 = new JList<>(citirePreturi());
list3.setBounds(250,100, 75,75);
panelHome.add(list3);
//Creez titlurile pt fiecare lista
JLabel denumireLabel=new JLabel("Denumire:");
denumireLabel.setBounds(50,80,70,20);
panelHome.add(denumireLabel);
JLabel cantitatiLabel=new JLabel("Cantitati:");
cantitatiLabel.setBounds(150,80,70,20);
panelHome.add(cantitatiLabel);
JLabel preturiLabel=new JLabel("Preturi:");
preturiLabel.setBounds(250,80,70,20);
panelHome.add(preturiLabel);
//Creez un camp pt a adauga cantitatea dorita care urmeaza a fi cumparata
//cantitateField
cantitateField = new JTextField();
cantitateField.setBounds(180,180,100,20);
cantitateField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt cantitateField
final String placeholderCantitate = "Cantitatea dorita";
cantitateField.setText(placeholderCantitate);
cantitateField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
cantitateField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (cantitateField.getText().isEmpty()) {
cantitateField.setText(placeholderCantitate);
showingPlaceholder = true;
}
}
});
panelHome.add(cantitateField);
//Butonul de cumparare
butonCumpara = new JButton("Cumpara");
butonCumpara.setLocation(180, 200);
butonCumpara.setSize(100, 20);
butonCumpara.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
String plantaselectata = list.getSelectedValue();
int indexplanta=list.getSelectedIndex();
String cantitateselectata = list2.getSelectedValue();
int indexcantitate=list2.getSelectedIndex();
String pretselectat = list3.getSelectedValue();
int indexpret=list3.getSelectedIndex();
String cantitatedorita=cantitateField.getText();
int valCantitate=Integer.valueOf(cantitateselectata);
int valCantitateDorita=Integer.valueOf(cantitatedorita);
int valPret=Integer.valueOf(pretselectat);
if(indexplanta==indexcantitate && indexplanta==indexpret){
if(valCantitateDorita<=valCantitate){
try {
afisPlantaCumparata(plantaselectata,valCantitateDorita);
} catch (IOException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
int a=valCantitate-valCantitateDorita;
String b=Integer.toString(a);
listacantitati[indexcantitate]=b;
panelHome.setVisible(false);
panelHome.setVisible(true);
}
else{
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Cantitatea nu esti disponibila","Eroare de cumparare",JOptionPane.WARNING_MESSAGE);
}
}
else{
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Planta, cantitate si pretul nu sunt din aceeasi categorie","Eroare de cumparare",JOptionPane.WARNING_MESSAGE);
}
}
});
panelHome.add(butonCumpara);
//Butonul de adaugare a unei plantei noi
butonAdauga = new JButton("Adauga");
butonAdauga.setLocation(80, 200);
butonAdauga.setSize(100, 20);
butonAdauga.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("DsA");
}
});
panelHome.add(butonAdauga);
//Returnez panelul
panelHome.setOpaque(true);
return panelHome;
}
public static String[] citirePlante(){
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Plante.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listaplante[kPlante] = strCurrentLine;
kPlante++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null)
objReader.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
return listaplante;
}
public static String[] citireCantitati(){
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Cantitati.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listacantitati[kCantitati] = strCurrentLine;
kCantitati++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null)
objReader.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
return listacantitati;
}
public static String[] citirePreturi(){
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Preturi.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listapreturi[kPreturi] = strCurrentLine;
kPreturi++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null)
objReader.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
return listapreturi;
}
public static void afisPlantaCumparata(String p, int c) throws IOException{
FileWriter writer = new FileWriter("PlanteVandute.txt");
try (
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(p+" "+c+"\n");
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
private static void HomeGUI() {
JFrame frameHome = new JFrame("PLAFAR * Calinescu George-Catalin * 221");
//Creez panelul peste frame si il stilizez
Home home = new Home();
frameHome.setContentPane(home.createHomeContentPane());
frameHome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameHome.setSize(400, 300);
frameHome.setVisible(true);
}
public static void main(String[] args) {
//Creez GUI si il afisez pe ecran
SwingUtilities.invokeLater(new Runnable() {
public void run() {
HomeGUI();
}
});
}
}
So i can't switch the frames when i login in with username admin and password admin. It's showing another frame that looks new to me, not my Home Frame. Why? what i did wrong?
And the other question is that: if i buy one plant i write into a text file the name and the amount that the buyer buyed but if i buy another one the file rewrites and i want to have all the plants that are buyed there. any typs?
Why use two frames in the first place??
Just use single main JFrame.
set its layout to be CardLayout
create both Login and Home by extending JPanel.
place them in main frame and show Login or Home panel as required!!
learn about CardLayout here

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 work documentlistener with jtabbedpane?

Open Two files By using Jtabbedpane.Document listener work each file independently.If you modify one file document listener enabled only for particular file. How to do this?. When open two files
Here is my code,
import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.text.Document;
public class Close extends javax.swing.JFrame {
JTextArea tx;
File file;
String filename=null;
int i=0;
boolean update =false;
public Close() {
initComponents();
}
#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();
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);
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.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser jc = new JFileChooser();
int returnVal= jc.showOpenDialog(Close.this);
String title;
String s=null;
if(returnVal == JFileChooser.APPROVE_OPTION)
file = jc.getSelectedFile();
if (jc.getSelectedFile()!= null) {
BufferedReader br = null;
StringBuffer str = new StringBuffer("");
StringBuffer str1 = new StringBuffer("");
StringBuilder st = new StringBuilder("");
StringBuilder sbHex = new StringBuilder();
StringBuilder sbText = new StringBuilder();
StringBuilder sbResult = new StringBuilder();
final StringBuilder pb = new StringBuilder();
int bytesCounter =0;
String helloWorldInHex=null;
int value=0;
try {
br = new BufferedReader(new FileReader(file));
String line;
try {
while ((line = br.readLine()) != null) {
str.append(line + "\n");
}
}
catch (IOException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
}
String t = str.toString();
filename=file.getPath();
final JInternalFrame internalFrame = new JInternalFrame("",true,true);
final String filePath=file.getAbsolutePath();
i++;
internalFrame.setName("Doc "+i);
tx=new JTextArea();
internalFrame.setTitle(filename);
try {
internalFrame.setSelected(true);
}
catch (PropertyVetoException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
}
tp.add(internalFrame);
try{
tp.setSelectedIndex(i-1);
}
catch(IndexOutOfBoundsException ioe){
}
tx.setText(t);
internalFrame.add(tx);
internalFrame.setVisible(true);
Document doc=tx.getDocument();
doc.addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
update =true;
}
#Override
public void removeUpdate(DocumentEvent e) {
update =true;
}
#Override
public void changedUpdate(DocumentEvent e) {
update =true;
}
});
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e) {
String name=tx.getName();
if(update==true){
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 {
DataOutputStream d = new DataOutputStream(new FileOutputStream(filename));
String line = tx.getText();
BufferedReader br = new BufferedReader(new StringReader(line));
while((line = br.readLine())!=null) {
d.writeBytes(line + "\r\n");
}
}
catch (IOException ee) {
success = false;
}
success = true;
i--;
tp.remove(internalFrame);
}
else if(reply==JOptionPane.NO_OPTION)
{
i--;
tp.remove(internalFrame);
}
}
else
{
i--;
tp.remove(internalFrame);
}
}
});
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
}
new Open().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Open;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tp;
// End of variables declaration
}
Thank you.
public class Open extends javax.swing.JFrame {
JTextArea tx;
ArrayList<String> fileList;
File file;
Map<Integer,String> m;
Map<String,Boolean> m1;
String filename=null;
int i=0;
int j=-1;
boolean update =false;
boolean changed=false;
public Open() {
fileList=new ArrayList<String>();
m=new HashMap<Integer,String>();
m1=new HashMap<String, Boolean>();
initComponents();
}
#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();
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);
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.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser jc = new JFileChooser();
int returnVal= jc.showOpenDialog(Open.this);
String title;
String s=null;
if(returnVal == JFileChooser.APPROVE_OPTION)
file = jc.getSelectedFile();
if (jc.getSelectedFile()!= null) {
BufferedReader br = null;
StringBuffer str = new StringBuffer("");
StringBuffer str1 = new StringBuffer("");
StringBuilder st = new StringBuilder("");
StringBuilder sbHex = new StringBuilder();
StringBuilder sbText = new StringBuilder();
StringBuilder sbResult = new StringBuilder();
final StringBuilder pb = new StringBuilder();
int bytesCounter =0;
String helloWorldInHex=null;
int value=0;
try {
br = new BufferedReader(new FileReader(file));
String line;
try {
while ((line = br.readLine()) != null) {
str.append(line + "\n");
}
}
catch (IOException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
}
String t = str.toString();
filename=file.getPath();
final JInternalFrame internalFrame = new JInternalFrame("",true,true);
final String filePath=file.getAbsolutePath();
i++;
internalFrame.setName("Doc "+i);
tx=new JTextArea();
internalFrame.setTitle(filename);
try {
internalFrame.setSelected(true);
}
catch (PropertyVetoException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
}
tp.add(internalFrame);
try{
tp.setSelectedIndex(i-1);
}
catch(IndexOutOfBoundsException ioe){
}
tx.setText(t);
internalFrame.add(tx);
internalFrame.setVisible(true);
final Document doc=tx.getDocument();
doc.addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
System.out.println("insert");
Component c = tp.getSelectedComponent();
if( c instanceof JInternalFrame)
{
JInternalFrame f = (JInternalFrame)c;
if(!fileList.contains(f.getTitle()))
{
fileList.add(f.getTitle());
update =true;
}
}
}
#Override
public void removeUpdate(DocumentEvent e) {
update =true;
}
#Override
public void changedUpdate(DocumentEvent e) {
update =true;
}
});
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e) {
String name=tx.getName();
Component c = tp.getSelectedComponent();
if( c instanceof JInternalFrame)
{
JInternalFrame f = (JInternalFrame)c;
String path=f.getTitle();
if(fileList.contains(path)){
fileList.remove(path);
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 {
FileOutputStream fos = new FileOutputStream(filename);
DataOutputStream d = new DataOutputStream(fos);
System.out.println("conetent2 "+filename);
String line = tx.getText();
System.out.println("conetent "+line);
BufferedReader br = new BufferedReader(new StringReader(line));
while((line = br.readLine())!=null) {
d.writeBytes(line + "\r\n");
}
}
catch (IOException ee) {
System.out.println("conetent qqw112222 ");
success = false;
}
success = true;
i--;
tp.remove(internalFrame);
}
else if(reply==JOptionPane.NO_OPTION)
{
i--;
tp.remove(internalFrame);
}
}
else
{
i--;
tp.remove(internalFrame);
}
}
}
});
j++;
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
}
new Open().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Open;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tp;
// End of variables declaration
}

Automatically Coloring the Java Keywords when i am open a file in JTextpane

i want apply the colors to the java keywords. When i am open a file it raise the Attempt to mutate in notification exception and program not shown completely and colors also not applied.
Here is my code,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FileDialog;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
public class JavaKeywordsColor extends javax.swing.JFrame {
private JTextPane textPane;
private Color color = Color.BLACK;
private int i = 0;
private JPanel noWrapPanel;
private JScrollPane scrollpane;
private JTextField status;
private StyledDocument d;
private String[] keywords = {"import ", "class ", "int ", "public ", "private"};
public JavaKeywordsColor() {
initComponents();
}
private void initComponents() {
tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Open = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
Open.setText("Open");
Open.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenActionPerformed(evt);
}
});
jMenu1.add(Open);
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.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE));
pack();
}// </editor-fold>
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
FileDialog fd = new FileDialog(JavaKeywordsColor.this, "Select File", FileDialog.LOAD);
fd.setVisible(true);
String title;
String sts;
if (fd.getFile() != null) {
sts = fd.getDirectory() + fd.getFile();
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(JavaKeywordsColor.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaKeywordsColor.class.getName()).log(Level.SEVERE, null, ex);
}
String t = str.toString();
final JInternalFrame internalFrame = new JInternalFrame("", true, true);
textPane = new JTextPane();
// textPane.setEditorKit(new WrapEditorKit());
d = textPane.getStyledDocument();
d.addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
jColorActionPerformed(de);
}
#Override
public void removeUpdate(DocumentEvent de) {
jColorActionPerformed(de);
}
#Override
public void changedUpdate(DocumentEvent de) {
jColorActionPerformed(de);
}
});
Document doc = textPane.getDocument();
textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
internalFrame.add(textPane);
i += 1;
internalFrame.setName("Doc" + i);
this.add(new javax.swing.JScrollPane(textPane));
noWrapPanel = new JPanel(new BorderLayout());
noWrapPanel.add(textPane);
scrollpane = new JScrollPane(noWrapPanel);
internalFrame.add(scrollpane);
internalFrame.setTitle(title);
tp.add(internalFrame);
tp.setSelectedIndex(i - 1);
internalFrame.setVisible(true);
textPane.setText(t);
}
}
private void jColorActionPerformed(DocumentEvent evt) {
replace(textPane);
}
public void replace(javax.swing.JTextPane jp) {
int cur = jp.getCaretPosition();
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLUE);
for (int ii = 0; ii < keywords.length; ii++) {
int fromIndex = 0;
String msg = keywords[ii];
int nol = 0; //number of lines upto keyword
int len = 1;
while (len != -1) {
len = jp.getText().indexOf(msg, fromIndex);
jp.setSelectedTextColor(Color.RED);
if (len != -1) {
try {
nol = countLine(jp.getText(0, len + 1));
} catch (BadLocationException ex) {
break;
}
fromIndex = len + msg.length();
System.out.println("len = " + len + " nol=" + nol);
len -= nol;
jp.select(len, len + msg.length());
System.out.println("Selected Text = " + jp.getSelectedText());
jp.replaceSelection("");
jp.setCaretPosition(len);
jp.setCharacterAttributes(aset, false);
jp.replaceSelection(msg);
}
}
}
aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLACK);
jp.setCharacterAttributes(aset, false);
jp.setCaretPosition(cur);
}
public int countLine(String str) {
int n = 0;
for (int ii = 0; ii < str.length(); ii++) {
if (str.charAt(ii) == '\n') {
n++;
}
}
return n;
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new JavaKeywordsColor().setVisible(true);
}
});
}
private javax.swing.JMenuItem Open;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tp;
}
The message of the exception makes it pretty clear. You are not allowed to mutate the document while the listener notification is in progress. The reason is quite clear: the modification would trigger new notifications and in programs like yours, either a StackOverflowError or an infinite loop would be provoked. It also implies that the might be reports for newer modifications at a time where other listeners not yet have learned about the old ones.
You have to schedule the modification to a later time and protect your code from reacting on your own modifications. Scheduling the update to a later time can also help regarding the performance when the user is typing fastly as you don’t want to parse an entire document on every inserted character.
So you should replace the part where you add the DocumentListener
d.addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
jColorActionPerformed(de);
}
#Override
public void removeUpdate(DocumentEvent de) {
jColorActionPerformed(de);
}
#Override
public void changedUpdate(DocumentEvent de) {
jColorActionPerformed(de);
}
});
to something like this:
final class UpdateTrigger implements DocumentListener, ActionListener {
final Timer timer=new Timer(150, this);
boolean enabled=true;
UpdateTrigger() {
timer.setRepeats(false);
}
public void insertUpdate(DocumentEvent e) {
if(enabled) timer.restart();
}
public void removeUpdate(DocumentEvent e) {
if(enabled) timer.restart();
}
public void changedUpdate(DocumentEvent e) {
if(enabled) timer.restart();
}
public void actionPerformed(ActionEvent e) {
enabled=false;
try { jColorActionPerformed(null); }
finally { enabled=true; }
}
}
d.addDocumentListener(new UpdateTrigger());
You might find out then that your code has more issues which are beyond the scope of your question. By the way, just highlighting keywords is not enough for a correct syntax highlighting. You need a parser which understands the syntactical structure, especially comments and String literals, even for the minimum highlighting.
You should study Chapter 3 of the The Java® Language Specification to get the complete picture.

Categories