How to add Line Numbers through menuitem using swing - java

I want to display line numbers through JMenuItem. But, it was display line numbers separate frame not currently opened frame and the create menuitem is also not working after click on viewLineNumbers.
Here is my code:
public class LineNumbers extends javax.swing.JFrame {
int i=0;
JTextArea tx,lines;
public LineNumbers() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
scrollPane = new javax.swing.JScrollPane();
tabbedPane = new javax.swing.JTabbedPane();
menuBar = new javax.swing.JMenuBar();
file = new javax.swing.JMenu();
create = new javax.swing.JMenuItem();
viewLineNumbers = new javax.swing.JCheckBoxMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
scrollPane.setViewportView(tabbedPane);
file.setText("File");
create.setText("Create");
create.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createActionPerformed(evt);
}
});
file.add(create);
viewLineNumbers.setSelected(true);
viewLineNumbers.setText("ViewLineNumbers");
viewLineNumbers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewLineNumbersActionPerformed(evt);
}
});
file.add(viewLineNumbers);
menuBar.add(file);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(scrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void createActionPerformed(java.awt.event.ActionEvent evt) {
final JInternalFrame internalFrame = new JInternalFrame("");
i++;
internalFrame.setName("Document"+i);
internalFrame.setClosable(true);
tx = new JTextArea();
internalFrame.add(tx, BorderLayout.CENTER);
tabbedPane.add(internalFrame);
internalFrame.pack();
internalFrame.setVisible(true);
}
private void viewLineNumbersActionPerformed(java.awt.event.ActionEvent evt) {
lines = new JTextArea("");
lines.setEditable(false);
lines.setSize(10,10);
tx.getDocument().addDocumentListener(new DocumentListener(){
public String getText(){
int caretPosition = tx.getDocument().getLength();
Element root = tx.getDocument().getDefaultRootElement();
String text = "1" + System.getProperty("line.separator");
int c=root.getElementIndex( caretPosition );
for(int i = 2; i < c + 2; i++){
text += i + System.getProperty("line.separator");
}
return text;
}
#Override
public void changedUpdate(DocumentEvent de) {
lines.setText(getText());
}
#Override
public void insertUpdate(DocumentEvent de) {
lines.setText(getText());
}
#Override
public void removeUpdate(DocumentEvent de) {
lines.setText(getText());
}
});
scrollPane.getViewport().add(tx);
scrollPane.setRowHeaderView(lines);
}
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(LineNumbers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LineNumbers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LineNumbers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LineNumbers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LineNumbers().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem create;
private javax.swing.JMenu file;
private javax.swing.JMenuBar menuBar;
private javax.swing.JScrollPane scrollPane;
private javax.swing.JTabbedPane tabbedPane;
private javax.swing.JCheckBoxMenuItem viewLineNumbers;
// End of variables declaration
}

You need to add the text area to a scroll pane and then add the scroll pane to the internal frame.
Then you update the row header of the above scroll pane (that contains the text area), NOT the scroll pane that contains the tabbed pane.

Related

Can't call custom JPanel class methods in main frame class

tl;dr
I just started learning java and swing and I have this problem where inside the main class if I try to call any custom method defined in my custom class which extends JPanel, i get an error which says "cannot find symbol", it's as if that method isn't even declared.
I tripled checked the custom class object looks properly initiated and the method is set as public. Any idea why this happens?
At first I was using Intellij Idea but it's gui designer was so frustrating to use that i thought it was the IDE's fault but even after switching to NetBeans and rewriting code from scratch I get the same error.
I wanted to write a class called Drawing which extends JPanel that could draw my custom Circuit class objects. Basically what i wanted to do for the app is that selecting New from the File menu would create and draw that Circuit object. For that I wanted that pressing the New button would call setCircuit() method defined in the Drawing class which initializes the circuit and then the paintComponent() would draw the circuit.
Code below:
import circuit.*;
import java.awt.Graphics;
public class Drawing extends javax.swing.JPanel {
private Circuit circuit = null;
public Drawing(){
}
public void setCircuit(Circuit circuit) {
this.circuit = circuit;
}
#Override
public void paintComponent(Graphics graphics){
super.paintComponent(graphics);
if(circuit == null){
graphics.drawString("Create a new circuit.", 10, 20);
} else{
// draws the circuit
}
}
}
import circuit.*;
public class GUI extends javax.swing.JFrame {
private Circuit circuit = null;
public GUI() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
drawing = new Drawing();
menuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
newMenuItem = new javax.swing.JMenuItem();
exitMentuItem = new javax.swing.JMenuItem();
exitMenu = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("My app");
setName("mainFrame"); // NOI18N
javax.swing.GroupLayout drawingLayout = new javax.swing.GroupLayout(drawing);
drawing.setLayout(drawingLayout);
drawingLayout.setHorizontalGroup(
drawingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
drawingLayout.setVerticalGroup(
drawingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
fileMenu.setText("File");
newMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
newMenuItem.setText("New");
newMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newMenuItemActionPerformed(evt);
}
});
fileMenu.add(newMenuItem);
exitMentuItem.setText("Exit");
exitMentuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMentuItemActionPerformed(evt);
}
});
fileMenu.add(exitMentuItem);
menuBar.add(fileMenu);
exitMenu.setText("Edit");
menuBar.add(exitMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(drawing, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(drawing, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void newMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
circuit = new Circuit();
drawing.setCircuit(circuit); // this is where I get the error:
/*
cannot find symbol
symbol: setCircuit(Circuit)
location: variable drawing of type JPanel
*/
}
private void exitMentuItemActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
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(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI.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 GUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel drawing;
private javax.swing.JMenuItem exitMentuItem;
private javax.swing.JMenu exitMenu;
private javax.swing.JMenu fileMenu;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenuItem newMenuItem;
// End of variables declaration
}

Swing window empty when used from other class

I am new to Swing and have a problem starting a window from another class. If i create a new object of the window in the same class it shows up just fine, but as soon as i try to start it from another class it shows up empty.
This is what i tried, but it's not working:
ProgressWindow dow = new ProgressWindow(this, null);
Here the code for my Swing window:
package example;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ProgressWindow extends javax.swing.JFrame {
private final JPanel panel;
private final javax.swing.JLabel jLabel1;
private final javax.swing.JLabel jLabel2;
private String message = "Vorgang läuft...";
private final int maxLength = 30;
public ProgressWindow(JFrame frame, String pMessage) {
super("Bitte warten");
//Set Message
setMessage(pMessage);
//Labels und panel anlegen
panel = new JPanel(new GridLayout(2, 1));
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
//Position
this.setLocationRelativeTo(frame);
//Close-Operation
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//Size
setMaximumSize(new java.awt.Dimension(240, 90));
setMinimumSize(new java.awt.Dimension(240, 90));
setResizable(false);
//Content
jLabel1.setText(message);
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xyz/ajax-loader.gif")));
//Alignment
jLabel1.setHorizontalAlignment(JLabel.CENTER);
jLabel2.setHorizontalAlignment(JLabel.CENTER);
//Finish Layout
panel.add(jLabel1);
panel.add(jLabel2);
getContentPane().add(panel);
pack();
setVisible(true);
}
private void setMessage(String pMessage) {
if (pMessage != null) {
//Cut string if too long
if (pMessage.length() > maxLength) {
pMessage = pMessage.substring(0, maxLength) + "...";
}
this.message = pMessage;
}
}
//This works as expected:
public static void main(String[] args) {
try {
ProgressWindow pr = new ProgressWindow(null, null);
Thread.sleep(2000);
pr.dispose();
}
catch (InterruptedException ex) {
}
}
}
Here a quick and dirty example-class i created with the Netbeans GUI-Builder, to demonstrate the code that does not work:
package example;
public class Otherclass extends javax.swing.JFrame {
public Otherclass() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
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()
.addContainerGap()
.addComponent(jButton1)
.addContainerGap(317, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addContainerGap(266, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
ProgressWindow pr = new ProgressWindow(this, null);
Thread.sleep(2000);
pr.dispose();
} catch (InterruptedException ex) {
System.err.println(ex);
}
}
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(Otherclass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Otherclass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Otherclass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Otherclass.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 Otherclass().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}
Use Swing Timer instead of Thread.sleep(2000) in a Swing application.
Read more How to Use Swing Timers
Sample code:
final ProgressWindow pr = new ProgressWindow(null, null);
Timer timer=new Timer(2000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
pr.dispose();
}
});
timer.setRepeats(false);
timer.start();
You should use the frame passed to constructor.
Change those calls in your constructor to:
frame.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//Size
frame.setMaximumSize(new java.awt.Dimension(240, 90));
frame.setMinimumSize(new java.awt.Dimension(240, 90));
frame.setResizable(false);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);

Check state and Uncheck state of JCheckBox MenuItem ActinListner

I have WordWrap checkBox MenuItem.By default it is unchecked(false) state.When I run the program and click on New menuitem and write some text after I click on WordWrap menuItem,The WordWrap state in not changed for first two times.I want to change the state(checked) for first time only.I had tried that but not working.
Here is code:
public class CheckBoxMenuItem extends javax.swing.JFrame {
int i=0;
JTextArea textArea;
JScrollPane scrollpane;
public CheckBoxMenuItem() {
initComponents();
WordWrap.setSelected(false);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tabbedPane = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Create = new javax.swing.JMenuItem();
WordWrap = new javax.swing.JCheckBoxMenuItem();
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);
WordWrap.setSelected(true);
WordWrap.setText("WordWrap");
WordWrap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
WordWrapActionPerformed(evt);
}
});
jMenu1.add(WordWrap);
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(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void CreateActionPerformed(java.awt.event.ActionEvent evt) {
final JInternalFrame internalFrame = new JInternalFrame("");
i++;
internalFrame.setName("Document"+i);
internalFrame.setClosable(true);
internalFrame.setAutoscrolls(true);
textArea=new JTextArea();
textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
scrollpane=new JScrollPane(textArea);
internalFrame.add(scrollpane);
tabbedPane.add(internalFrame);
internalFrame.setSize(internalFrame.getMaximumSize());
internalFrame.pack();
internalFrame.setVisible(true);
}
private void WordWrapActionPerformed(java.awt.event.ActionEvent evt) {
WordWrap.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
AbstractButton button = (AbstractButton) ie.getItem();
if(button.isSelected()){
textArea.setLineWrap(true);
scrollpane.validate();
}
else
{
textArea.setLineWrap(false);
scrollpane.validate();
}
}
});
}
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(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new CheckBoxMenuItem().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Create;
private javax.swing.JCheckBoxMenuItem WordWrap;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration
}
In your WordWrapActionPerformed method, you're doing nothing but adding an ItemListener to do, this won't do much...
Instead, you should simply carry out the requirements of the event, for example...
private void WordWrapActionPerformed(java.awt.event.ActionEvent evt) {
AbstractButton button = (AbstractButton) evt.getSource();
if (button.isSelected()) {
textArea.setLineWrap(true);
} else {
textArea.setLineWrap(false);
}
textArea.revalidate();
}
Either that or change the listener on the menu item in the GUI properties to use a ItemListener instead of an ActionListener
You'll probably also want to become farmiluar with Code Conventions for the Java Programming Language, it will make your code eaiser to read for others ;)

Set a selected text color using Swing

I want to display a selected text with user selected color.My problem here is I had select some text and click on settextcolor it was applied to all the text not selected text.Please give me..
Here is my code:
public class SetTextColor extends javax.swing.JFrame {
int i=0;
JTextPane textPane;
JScrollPane scrollPane;
public SetTextColor() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tabbedPane = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Create = new javax.swing.JMenuItem();
SetTextColor = 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);
SetTextColor.setText("SetTextColor");
SetTextColor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SetTextColorActionPerformed(evt);
}
});
jMenu1.add(SetTextColor);
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(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void CreateActionPerformed(java.awt.event.ActionEvent evt) {
final JInternalFrame internalFrame = new JInternalFrame("");
i++;
internalFrame.setName("Document"+i);
internalFrame.setClosable(true);
internalFrame.setAutoscrolls(true);
textPane=new JTextPane();
textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
scrollPane=new JScrollPane(textPane);
internalFrame.add(scrollPane);
tabbedPane.add(internalFrame);
internalFrame.setSize(internalFrame.getMaximumSize());
internalFrame.pack();
internalFrame.setVisible(true);
}
private void SetTextColorActionPerformed(java.awt.event.ActionEvent evt) {
Color color = JColorChooser.showDialog(this, "Colors",Color.BLUE);
StyledDocument doc = textPane.getStyledDocument();
String text=textPane.getSelectedText();
Style style = textPane.addStyle("I'm a Style", null);
StyleConstants.setForeground(style, color);
textPane.setForeground(color);
}
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(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new SetTextColor().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Create;
private javax.swing.JMenuItem SetTextColor;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration
}
This likely the default behaviour of the Caret, which will hide the selection when the text component loses focus.
You can change this by creating a custom Caret and overriding the isSelectionVisible method to always return true
For example...
DefaultCaret caret = new DefaultCaret() {
#Override
public boolean isSelectionVisible() {
return true;
}
};
...Runnable example...
import java.awt.Color;
import javax.swing.JColorChooser;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultCaret;
public class SetTextColor extends javax.swing.JFrame {
int i = 0;
JTextArea textArea;
JScrollPane scrollPane;
public SetTextColor() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tabbedPane = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Create = new javax.swing.JMenuItem();
SetTextColor = 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);
SetTextColor.setText("SetTextColor");
SetTextColor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SetTextColorActionPerformed(evt);
}
});
jMenu1.add(SetTextColor);
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(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void CreateActionPerformed(java.awt.event.ActionEvent evt) {
final JInternalFrame internalFrame = new JInternalFrame("");
i++;
internalFrame.setName("Document" + i);
internalFrame.setClosable(true);
internalFrame.setAutoscrolls(true);
textArea = new JTextArea();
DefaultCaret caret = new DefaultCaret() {
#Override
public boolean isSelectionVisible() {
return true;
}
};
textArea.setCaret(caret);
textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
scrollPane = new JScrollPane(textArea);
internalFrame.add(scrollPane);
tabbedPane.add(internalFrame);
internalFrame.setSize(internalFrame.getMaximumSize());
internalFrame.pack();
internalFrame.setVisible(true);
}
private void SetTextColorActionPerformed(java.awt.event.ActionEvent evt) {
Color color = JColorChooser.showDialog(this, "Colors", Color.BLUE);
// textArea.setBackground(color);
textArea.setSelectedTextColor(color);
}
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(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SetTextColor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new SetTextColor().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Create;
private javax.swing.JMenuItem SetTextColor;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration
}

Closing JInternalFrame with JTabbedPane

I want to close the JInternalFrame.I am developing A MenuItem as Crete,whenever click on open it is opening an JInternalFrame,but it's not closing.
Please help me.
Here is my code
import javax.swing.JInternalFrame;
import javax.swing.JTextArea;
public class CloseWindow extends javax.swing.JFrame {
JTextArea tx;
int i=1;
public CloseWindow() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tPane = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Crete = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
Crete.setText("Create");
Crete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CreteActionPerformed(evt);
}
});
jMenu1.add(Crete);
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(tPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void CreteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JInternalFrame internalFrame = new JInternalFrame();
internalFrame.setName("Document"+i);
internalFrame.setClosable(true);
i++;
internalFrame.setSize(700, 700);
tx = new JTextArea();
internalFrame.add(tx);
tPane.add(internalFrame);
internalFrame.setSize(internalFrame.getMaximumSize());
internalFrame.pack();
internalFrame.setVisible(true);
}
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(CloseWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CloseWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CloseWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CloseWindow.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 CloseWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Crete;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tPane;
// End of variables declaration
}
Add the following:
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e) {
tPane.remove(internalFrame);
}
});
But don't forget to make internalFrame variable to be final.

Categories

Resources