How to add JLabel to existing JTextField - java

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();
}
});
}
}

Related

jProgressBar with Threads for Database data Insertion

I'm trying to implement a JprogressBar to show the data insertion progress.
Basically the user select how many data sources will be imported to database.
With this parameter the main program Start a method to list those parameters and with a foreach loop it calls the insertion Thread and the ProgressBar update Thread.
for (Maquina i : m.listar()) {
//Passing to Import Thread the object with the data and a Date parameter
ImportarDados imp = new ImportarDados(i, jDateInicial.getDate());
//Calling progress bar update Thread with the progressbar itself and progress parameter
BarraDeProgresso bp = new BarraDeProgresso(progresso, progImportacao);
imp.run();
bp.run();
}
The threads kinda work on their own, but the result is not the one I want, cause the data is being imported and the progressbar is being updated, but it is being update to 100% after all data is imported. I need to update the progress bar as long as the import thread finish the importation for each (Maquina i) object.
If it is necessary I can provide the threads code...but i don't know if this calling method can provide the result I want. Searching on the forum i found something about EDT and i think it is the problem that the bar is not being updated. Can you guys help me solving this?
Minimal and Verifiable example:
My code is pretty short. The code generated by netbeans is huge, sry for that.
That code simulate my problem. The windows is refreshed only after the for loop is finished. But the BarraDeProgresso thread is running at the same as and SysOut some info...
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
public class Minimo extends javax.swing.JFrame {
public Minimo() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int progImportacao[] = {0};
progresso.setMaximum(15);
for (int i = 0; i <= 15; i++) {
ImportarDados imp = new ImportarDados(i,lblProgresso);
BarraDeProgresso bp = new BarraDeProgresso(progresso, progImportacao);
imp.run();
bp.run();
progImportacao[0] += 1;
}
}
Component Initialization (Netbeans Generated)
private void initComponents() {
progresso = new javax.swing.JProgressBar();
lblProgresso = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblProgresso.setText("...");
jButton1.setText("IMPORT DATA");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(60, 60, 60)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblProgresso)
.addComponent(progresso, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(47, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(191, 191, 191))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
.addComponent(lblProgresso)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(progresso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(37, 37, 37))
);
pack();
}// </editor-fold>
Runnable classes
class BarraDeProgresso implements Runnable {
public JProgressBar jProgressBar1;
public int progresso[];
public BarraDeProgresso(JProgressBar barra, int progresso[]) {
this.jProgressBar1 = barra;
this.progresso = progresso;
}
#Override
public void run() {
try {
Thread.sleep(0);
System.out.println("TBARRA PROG " + progresso[0]);
jProgressBar1.setValue(progresso[0]);
jProgressBar1.repaint();
} catch (InterruptedException e) {
}
}
}
class ImportarDados implements Runnable {
private int pi = 0;
JLabel x;
public ImportarDados(int i, JLabel tag) {
this.pi = i;
this.x = tag;
}
#Override
public void run() {
try {
Thread.sleep(500);
x.setText(Integer.toString(pi)+" /15");
} catch (InterruptedException ex) {
Logger.getLogger(Minimo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Main (Netbeans Generated)
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(Minimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Minimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Minimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Minimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Minimo().setVisible(true);
}
});
}
Your current code creates no background thread. Yes you've got Runnables, but you call run() on them, meaning you are calling them on the Swing event thread. When you do this, you block the event thread, effectively freezing your program. Instead, you need to:
Create a true background thread by passing your Runnable into a Thread object's constructor and calling start() on that Thread.
Not mutate Swing components from within these background threads
Or use a SwingWorker as per the Lesson: Concurrency in Swing which will help solve both of the above issues.
For an example of use of a SwingWorker, please see:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
#SuppressWarnings("serial")
public class Minimo2 extends JPanel {
private static final int EB_GAP = 15;
private static final int PROG_BAR_WDTH = 400;
public static final int MAX_DATA = 15;
private JProgressBar progresso;
private JLabel lblProgresso;
private JButton jButton1;
private Action importDataAction = new ImportDataAction("Import Data");
public Minimo2() {
initComponents();
}
private void initComponents() {
progresso = new JProgressBar(0, MAX_DATA);
lblProgresso = new JLabel(" ");
jButton1 = new JButton(importDataAction);
int progBarHeight = progresso.getPreferredSize().height;
progresso.setPreferredSize(new Dimension(PROG_BAR_WDTH, progBarHeight));
progresso.setStringPainted(true);
JPanel btnPanel = new JPanel();
btnPanel.add(jButton1);
JPanel labelPanel = new JPanel();
labelPanel.add(lblProgresso);
JPanel progressPanel = new JPanel();
progressPanel.add(progresso);
setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(btnPanel);
add(Box.createVerticalStrut(EB_GAP));
add(labelPanel);
add(Box.createVerticalStrut(EB_GAP));
add(progressPanel);
}
private class ImportDataAction extends AbstractAction {
public ImportDataAction(String name) {
super(name); // give the button text
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic); // give it a hot key
}
#Override
public void actionPerformed(ActionEvent e) {
setEnabled(false); // disable our button
ImportDataWorker worker = new ImportDataWorker(MAX_DATA);
worker.addPropertyChangeListener(new WorkerListener());
worker.execute();
}
}
private class WorkerListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
int progValue = (int) evt.getNewValue();
progresso.setValue(progValue);
String text = String.format("%02d/15", progValue);
lblProgresso.setText(text);
} else if ("state".equals(evt.getPropertyName())) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
#SuppressWarnings("rawtypes")
SwingWorker worker = (SwingWorker)evt.getSource();
try {
worker.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
progresso.setValue(MAX_DATA);
String text = String.format("%02d/15", MAX_DATA);
lblProgresso.setText(text);
importDataAction.setEnabled(true);
}
}
}
}
private class ImportDataWorker extends SwingWorker<Void, Void> {
private static final long SLEEP_TIME = 500;
private int max;
public ImportDataWorker(int max) {
this.max = max;
}
#Override
protected Void doInBackground() throws Exception {
for (int i = 0; i < max; i++) {
setProgress(i);
Thread.sleep(SLEEP_TIME);
}
return null;
}
}
private static void createAndShowGui() {
Minimo2 mainPanel = new Minimo2();
JFrame frame = new JFrame("Minimo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

ActionListener class doesn't get triggered for CheckBox

I am creating this software for a project and what i did was i created a method "Salad" here what happens is user can select maximum number of 2 salads.the names of the salad are coming from the database and i created checkboxes dynamically.
This works fine and I can get the values and insert it to the database.so then what i wanted was to update the inserted row.i created a method to setselected() the all the check-boxes that user selected before. so as i told above i created this method to select maximum no of 2 check boxes .when i try to insert it works fine..but when i try to update that ActionListener does not work.
I am using setSelected(true) in constructor that ActionListener is not triggering. What should I do this in the Salad() ??
public void Salad()
{
int count =0 ;//to count rows in result set
String sql="Select name from foodmenue where type='Salad' and menue='"+selecmenue+"' ";
try {
pst=con.prepareStatement(sql);
rs=pst.executeQuery();
while(rs.next())
{
count++;
}
if(count!=0)
{
rs=pst.executeQuery();
JCheckBox [] a=new JCheckBox[count];
jPanel7.setLayout(new GridLayout());
int x=0;
while(rs.next())
{
a[x]=new JCheckBox(rs.getString("name"));
a[x].setName(rs.getString("name"));
jPanel7.add(a[x]);
a[x].setVisible(true);
a[x].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if( e.getSource() instanceof JCheckBox){
String s=((JCheckBox) e.getSource()).getName();
if(((JCheckBox) e.getSource()).isSelected())
{
if(selsalad<2)//selsalad is 0 in the bigining
{
selectedsalad[selsalad]=((JCheckBox) e.getSource()).getName();
selsalad=selsalad+1;
}
else
{
((JCheckBox) e.getSource()).setSelected(false);
showMessageDialog(null, "you cant have more than 2 salads");
}
}
if(!((JCheckBox) e.getSource()).isSelected())
{
if(selectedsalad[0].equals(s)|| selectedsalad[1].equals(s) )
{
if(selsalad<2)
{
selectedsalad[selsalad]="";
}
selsalad=selsalad-1;
showMessageDialog(null, selsalad);
}
} }
}
});
x++;
}
}
} catch (Exception e) {
showMessageDialog(null, e);
}
}
this is how i filled the check boxex
for(Component c : jPanel7.getComponents())
{
if(c instanceof JCheckBox)
{
JCheckBox temp=(JCheckBox) c;
if(temp.getName().equals(s1)){
temp.setSelected(true);
}
if(temp.getName().equals(s2)){
temp.setSelected(true);
}
}
}
MCVE : To give a better idea
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static javax.swing.JOptionPane.showMessageDialog;
public class NewJFrame extends javax.swing.JFrame {
int selsalad=0;//count of the selected checkbox this cant go more than 2
String selectedsalad[]=new String[2];
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
public NewJFrame() {
initComponents();
Salad();
showMessageDialog(null, "uncomment promlemmethod to see the probelm after you try this one");
problemmehtod();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 561, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 470, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
public void problemmehtod(){ // this is the problem now i can select any much when i call this i commented this one
for(Component c : jPanel1.getComponents())
{
if(c instanceof JCheckBox)
{
JCheckBox temp=(JCheckBox) c;
if(temp.getName().equals("a1")){
temp.setSelected(true);
}
if(temp.getName().equals("a2")){
temp.setSelected(true);
}
}
}
}
public void Salad()
{
JCheckBox a[]=new JCheckBox[5];
// int count =0 ;//to count rows in result set
try {
for(int x=0;x<5;x++)
{
jPanel1.setLayout(new GridLayout());
a[x]=new JCheckBox("a"+String.valueOf(x));
a[x].setName("a"+String.valueOf(x));
jPanel1.add(a[x]);
a[x].setVisible(true);
a[x].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if( e.getSource() instanceof JCheckBox){
String s=((JCheckBox) e.getSource()).getName();
if(((JCheckBox) e.getSource()).isSelected())
{
if(selsalad<2)
{
selectedsalad[selsalad]=((JCheckBox) e.getSource()).getName();
selsalad=selsalad+1;
}
else
{
((JCheckBox) e.getSource()).setSelected(false);
showMessageDialog(null, "you cant have more than 2 salads");
}
}
if(!((JCheckBox) e.getSource()).isSelected())
{
if(selectedsalad[0].equals(s)|| selectedsalad[1].equals(s) )
{
if(selsalad<2)
{
selectedsalad[selsalad]="";
}
selsalad=selsalad-1;
//showMessageDialog(null, selsalad);
}
}
}
}
});
}
} catch (Exception e) {
showMessageDialog(null, e);
}
}
// End of variables declaration
}
The number of check boxes selected are checked on the actionListener of each of these CheckBox. Action listeners aren't called when you are call setSelected(true) on the choice boxes.
You need to call the doClick(), if you want to call the action listeners.
JCheckBox temp=(JCheckBox) c;
if(temp.getName().equals("a1")){
temp.doClick();
}
if(temp.getName().equals("a2")){
temp.doClick();
}
Further, since both the if statements are doing the same stuff, you can just combine them.
if(temp.getName().equals("a1") || temp.getName().equals("a2")){
temp.doClick();
}
Your problem is that you're not updating the selsalad when you programmatically select a JCheckBox. Better perhaps is to get rid of the selsalad variable completely, and instead within the ActionListener iterate through an ArrayList<JCheckBox> and count exactly how many have been selected. Or make your array of JCheckBox a field, improve its name and iterate through that.
For example:
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class NewPanel extends JPanel {
private static final int CHECK_BOX_COUNT = 5;
public static final int MAX_SELECTED = 2;
private List<JCheckBox> checkBoxes = new ArrayList<>();
public NewPanel() {
setLayout(new GridLayout(0, 1));
ActionListener actionListener = new CheckBoxListener();
for (int i = 0; i < CHECK_BOX_COUNT; i++) {
String name = "a" + i;
JCheckBox checkBox = new JCheckBox(name);
checkBox.setActionCommand(name);
checkBox.addActionListener(actionListener);
add(checkBox); // add to gui
checkBoxes.add(checkBox); // add to ArrayList
}
checkBoxes.get(1).setSelected(true);
checkBoxes.get(2).setSelected(true);
}
private class CheckBoxListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int selectedCount = 0;
for (JCheckBox jCheckBox : checkBoxes) {
if (jCheckBox.isSelected()) {
selectedCount++;
}
}
if (selectedCount > MAX_SELECTED) {
Component parent = NewPanel.this;
String msg = String.format("You've selected too many checkboxes as only %d can be selected",
MAX_SELECTED);
String title = "Too Many CheckBoxes Selected";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(parent, msg, title, type);
((JCheckBox) e.getSource()).setSelected(false);
}
}
}
public List<String> getSelectedActionCommands() {
List<String> resultList = new ArrayList<>();
for (JCheckBox checkBox : checkBoxes) {
if (checkBox.isSelected()) {
resultList.add(checkBox.getActionCommand());
}
}
return resultList;
}
private static void createAndShowGui() {
NewPanel mainPanel = new NewPanel();
int result = JOptionPane.showConfirmDialog(null, mainPanel,
"Select Options", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.out.println("Selected Options: " + mainPanel.getSelectedActionCommands());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

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 Apply Insert key action for all opened Documents

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);
}
}
}
}

Categories