How to add a JInternalFrame to JFrame? - java

I have my JFrame, and I want to attach to a button an ActionListener that triggers the JInternalFrame.
I do:
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
AboutFrame about = new AboutFrame(); //jInternalFrame
this.add(about);
}
But it doesn't bring it to front. What did I miss?

You probable want to use a JDesktopPane, then set the content pane of your frame to the desktop pane
JDesktopPane desktop = new JDesktopPane(); //a specialized layered pane
createFrame(); //create first "window"
setContentPane(desktop);
Then you can do something like this
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt)
{
AboutFrame about = new AboutFrame(); <--- JInternalFrame
about.setVisible(true); //necessary as of 1.3 <--- set it visible
desktop.add(about); <--- add to desktop
try {
about.setSelected(true); <--- set it selected
} catch (java.beans.PropertyVetoException e) {}
}
See How to Us Internal Frames
UDATE
Run this example, I made on NetBeans GUI Builder also. It works fine, without the behavior yout're talking about.
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jDesktopPane1 = new javax.swing.JDesktopPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1);
jDesktopPane1.setLayout(jDesktopPane1Layout);
jDesktopPane1Layout.setHorizontalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 376, Short.MAX_VALUE)
);
jDesktopPane1Layout.setVerticalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 302, Short.MAX_VALUE)
);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("About");
jMenuItem1.setText("About");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem1);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jDesktopPane1)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
AboutFrame about = new AboutFrame();
about.setVisible(true);
jDesktopPane1.add(about);
try {
about.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JDesktopPane jDesktopPane1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
// End of variables declaration
}
AboutFrame.java
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
public class AboutFrame extends JInternalFrame{
public AboutFrame() {
add(new Panel());
pack();
}
private class Panel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("About Screen", 100, 100);
}
public Dimension getPreferredSize(){
return new Dimension(300, 300);
}
}
}
Steps I took
Opened a new JFrame form
Dragged a JDesktopPane to the main frame and expanded it the size of the frame
Dragged a JMenuBar to the top of the frame
Dragged a JMenuItem to the JMenuBar
Added an event listener to the JMenuItem
Added the action code that i provided for you earlier. That's all I did, and it works fine.
EDIT
A different apprach would be instead of using an JInternalFrame for this. Use a modal JDialog. You can create it the same way you did the JInternalFrame , and show it the same way. This will guarantee you don't get this result. :)

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
}

How to change the color of JInternalFrame Titlebar?

I want to change the color of JInternalFrame Title bar. For this I had tried with some forum suggestions but it doesn't work. In my application Click on create menu item then it shows an internal frame. I want to change the color of that title bar.
Here is my code:
public class CreateDocs extends javax.swing.JFrame {
int i=0;
JTextPane textPane;
public CreateDocs() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tabbedPane = new javax.swing.JTabbedPane();
menuBar = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
create = 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);
menuBar.add(jMenu1);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 410, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 410, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 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 createActionPerformed(java.awt.event.ActionEvent evt) {
final JInternalFrame internalFrame = new JInternalFrame("");
i++;
UIManager.put("InternalFrame.activeTitleBackground", new ColorUIResource(new Color(248,250,175)));
UIManager.put("InternalFrame.inactiveTitleBackground", new ColorUIResource(new Color(248,250,175)));
javax.swing.plaf.basic.BasicInternalFrameUI ui =
new javax.swing.plaf.basic.BasicInternalFrameUI(internalFrame);
internalFrame.setUI(ui);
internalFrame.setName("Document"+i);
internalFrame.setClosable(true);
internalFrame.setAutoscrolls(true);
textPane=new JTextPane();
textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 14));
internalFrame.add(textPane);
tabbedPane.add(internalFrame);
}
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(CreateDocs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CreateDocs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CreateDocs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CreateDocs.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 CreateDocs().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem create;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar menuBar;
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration
}
Try using this one line:
internalFrame.getRootPane().setWindowDecorationStyle(5);
Use any number between 1 to 8.

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
}

Dynamically create jCheckBox and add to a jScrollPane

EDIT: Using the solutions presented below, I have changed the code to have a JPanel inside a JScrollPane. Using a JButton i add JCheckBoxes to the JPanel inside the JScrollPane. This was one problem solved, as the a JScrollPanecan only take one JComponent. The rest of the issues were solved setting a gridlayout to the JPanel inside JScrollPane. I have kept my original question here for the sake of posterity:
ORIGINAL QUESTION: I'm trying to dynamically create JCheckBox and add them to a JScrollPane, but alas i am achieving little success. I have reduced this to a single proof-of-concept implementation.
I have a JScrollPaneon a JPanel inside a JFrame. Also on the JPanel, i have added a button that is supposed to add a JCheckBox to the JScrollPane when clicked. Should be simple enough. The code inside the button is as follows:
private void addCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {
JCheckBox cb = new JCheckBox("New CheckBox");
jScrollPaneCheckBoxes.add(cb);
jScrollPaneCheckBoxes.revalidate();
}
The code runs seemingly without error. I have no exceptions and using the debugger shows that the JCheckBox is in fact added to the JScrollPane . Unfortunately, nothing is displayed in the application. I need direction as to where to look for the problem.
Here is a quick piece of code that you can just run. Unfortunately i threw this together using Netbeans and it's GUI designer and as such it's a bit longer than it needs to be, especially the generated code. Focus on the method jButton1ActionPerformed, that's where the above code is taken from.
EDIT: This code now does what i need it to. :-)
package dynamiccheckboxsscce;
import javax.swing.JCheckBox;
public class Main extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public Main() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 250));
jPanel1.setPreferredSize(new java.awt.Dimension(300, 250));
jPanel1.setLayout(new java.awt.GridLayout(0, 2, 10, 10));
jScrollPane1.setViewportView(jPanel1);
jButton1.setText("Add Checkbox");
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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(112, 112, 112)))));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap()));
pack();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JCheckBox cb = new JCheckBox("New CheckBox");
jPanel1.add(cb);
jPanel1.revalidate();
jPanel1.repaint();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
}
Thanks in advance.
without posting a SSCCE you have to accepting that JScrollPane is designated to nest only one JComponent,
if you want to add more that one JComponent to the JScrollPane, the put there JPanel and then add a new JComponent to the JPanel instead of JScrollPane
to check how dynamically add / remove JComponents
EDIT
you have to set proper LayoutManager to the JPanel
you ahve to add JPanel to the JScrollPane
for example (without using built_in designer, even safe time for ..., required best knowledge about used SwingFramework and Swing too, I'm satisfied with plain Swing)
code
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class AddJCheckBoxToJScrollPane {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
private JButton jButton1;
private JPanel jPanel1;
private JScrollPane jScrollPane1;
public AddJCheckBoxToJScrollPane() {
jPanel1 = new JPanel();
jPanel1.setLayout(new GridLayout(0, 2, 10, 10));
jScrollPane1 = new JScrollPane(jPanel1);
jButton1 = new JButton("Add Checkbox");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JCheckBox cb = new JCheckBox("New CheckBox");
jPanel1.add(cb);
jPanel1.revalidate();
jPanel1.repaint();
}
});
frame.add(jScrollPane1);
frame.add(jButton1, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
//frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
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) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AddJCheckBoxToJScrollPane();
}
});
}
}
You should be calling repaint() instead of revalidate().
See Revalidate vs. Repaint

Categories

Resources