I was trying to do a buffer to display it in a JLabel and use it in a JFrame. I have a problem when I change the image: the image changes only when I resize the window.
package buffer;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class principal extends javax.swing.JFrame {
private JLabel person=new JLabel();
public static final int tCuadrito=60;
private URL url=Buffer.class.getClass().getResource("/imagenes/persona.png");
private ImageIcon imagenIcon=new ImageIcon();
private BufferedImage gato=new BufferedImage(120,60,BufferedImage.BITMASK);
public principal() {
initComponents();
dibujar();
}
public void dibujar(){
try{
gato=ImageIO.read(url);
}catch(IOException e){
System.out.print("ERROR imagen no leida: "+e.toString());
}
imagenIcon.setImage(gato.getSubimage(0, 0, 60, 60));
person.setBounds(0*tCuadrito, 0*tCuadrito, tCuadrito, tCuadrito);
person.setVisible(true);
person.setIcon(imagenIcon);
contenedor.add(person);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
contenedor = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
formKeyReleased(evt);
}
});
javax.swing.GroupLayout contenedorLayout = new javax.swing.GroupLayout(contenedor);
contenedor.setLayout(contenedorLayout);
contenedorLayout.setHorizontalGroup(
contenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
contenedorLayout.setVerticalGroup(
contenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, 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(contenedor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(contenedor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void formKeyReleased(java.awt.event.KeyEvent evt) {
switch(evt.getKeyCode()){
case KeyEvent.VK_RIGHT:
imagen=cat.getSubimage(60, 0, 60, 60);
imagenIcon.setImage(imagen);
person.setIcon(imagenIcon);
break;
}
}
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(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(principal.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 principal().setVisible(true);
}
});
}
private javax.swing.JPanel contenedor;
}
To update a JFrame you must use
revalidate();
repaint();
So after you change anything in your GUI you would want to revalidate() the JFrame and then repaint the contents of it.
Good luck!
Related
I'm doing a login screen with Swing. I edited the enable property of the only button that exists in the screen - the "Entrar", as shown in the picture below:
Login screen
But, when I hit Shift-F6 (Run file) it doesn't shows the change:
Login Screen after running single file
Here's the code:
package view;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
/**
*
* #author User
*/
public class Inicio extends javax.swing.JFrame {
String usuario;
String senha;
int a;
public Inicio() {
initComponents();
DocumentListener dUsuario = new DocumentListener(){
#Override
public void insertUpdate(DocumentEvent e) {
try {
usuario = e.getDocument().getText(0, 0);
a = 1;
} catch (BadLocationException ex) {
Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void removeUpdate(DocumentEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void changedUpdate(DocumentEvent e) {
try {
usuario = e.getDocument().getText(0, 0);
a = 1;
} catch (BadLocationException ex) {
Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
DocumentListener dSenha = new DocumentListener(){
#Override
public void insertUpdate(DocumentEvent e) {
try {
senha = e.getDocument().getText(0, 0);
a = 2;
} catch (BadLocationException ex) {
Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void removeUpdate(DocumentEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void changedUpdate(DocumentEvent e) {
try {
senha = e.getDocument().getText(0, 0);
a = 2;
} catch (BadLocationException ex) {
Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
tUsuario.getDocument().addDocumentListener(dUsuario);
tSenha.getDocument().addDocumentListener(dSenha);
if(a == 2) {
if (bEntrar.isEnabled() == false) {
bEntrar.setEnabled(true);
}
}else{
if (bEntrar.isEnabled() == true) {
bEntrar.setEnabled(false);
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
tSenha = new javax.swing.JPasswordField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
tUsuario = new javax.swing.JFormattedTextField();
bEntrar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jLabel1.setForeground(new java.awt.Color(153, 153, 153));
jLabel1.setText("Informe apenas os dígitos do CPF.");
jLabel2.setText("Senha:");
jLabel3.setText("CPF:");
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel4.setText("LOGIN");
try {
tUsuario.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
bEntrar.setText("Entrar");
bEntrar.setEnabled(false);
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(184, 184, 184)
.addComponent(jLabel4)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 91, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(7, 7, 7)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(tSenha, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bEntrar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE))
.addComponent(tUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(55, 55, 55))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jLabel4)
.addGap(37, 37, 37)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(tUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3)
.addComponent(jLabel1)
.addGap(9, 9, 9)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(tSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
.addComponent(bEntrar)
.addGap(41, 41, 41))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
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(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Inicio().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton bEntrar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPasswordField tSenha;
private javax.swing.JFormattedTextField tUsuario;
// End of variables declaration
}
I edited the button properties using the Project view from Swing. So, what can I do to fix that? Is it a Netbeans bug? I'm using Netbeans IDE 8.2, by the way.
If you want to effect the state of the button based on changes which have occurred on the text fields, then those actions need to take place in the action handlers themselves (ie, the DocumentListeners)
The following is a very basic example, which disables the "action" button until both the user name and password fields are no longer empty
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField userNameField;
private JPasswordField passwordField;
private JButton actionButton;
public TestPane() {
userNameField = new JTextField(15);
passwordField = new JPasswordField(15);
actionButton = new JButton("Do stuff");
actionButton.setEnabled(false);
DocumentListener documentListener = new DocumentListener() {
protected void stateDidChange() {
actionButton.setEnabled(userNameField.getText().length() > 0 && passwordField.getPassword().length > 0);
}
#Override
public void insertUpdate(DocumentEvent e) {
stateDidChange();
}
#Override
public void removeUpdate(DocumentEvent e) {
stateDidChange();
}
#Override
public void changedUpdate(DocumentEvent e) {
stateDidChange();
}
};
userNameField.getDocument().addDocumentListener(documentListener);
passwordField.getDocument().addDocumentListener(documentListener);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
add(userNameField, gbc);
add(passwordField, gbc);
add(actionButton, gbc);
}
}
}
Why is the initial state not been updated?
You define a as....
int a;
which gives it a initial (or default) value of 0.
You then use...
if(a == 2) {
if (bEntrar.isEnabled() == false) {
bEntrar.setEnabled(true);
}
}else{
if (bEntrar.isEnabled() == true) {
bEntrar.setEnabled(false);
}
}
to change the initial state. Since a is 0, the else block is executed, the only condition which would change the button enabled state to false would be if the current enabled state is true
But when I use Shift+F6 to run the code it doesn't work
Do a "clean and build" and run the project, not the file. In testing your code, the UI appears with the button already disabled
i have some problem whene i want to load image
1 class :Draw_Image
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
public class Draw_Image extends Canvas{
BufferedImage image= null;
//Constructeur, prend une image Buffered
public Draw_Image(BufferedImage img){
//copier l'image dans son attribut
image= img;
}
public void paint(Graphics g){
//Peintre le graphique g d e l'image
g.drawImage(image,0,0,this);
}
}
2 class :choose an image and i try to loaded in Jscrollpan(declared in the Main clas)
import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
public class LoadImage extends JPanel{
private String path1;
private String path2;
private String path3;
NewJFrame j;
private JFileChooser parcourir= new JFileChooser();
BufferedImage img = null;
public LoadImage(){
parcourir.showOpenDialog(null);
if(parcourir.showOpenDialog(null)== JFileChooser.APPROVE_OPTION){
//récupérer image à partir du choix de l'utilisateur
String file2= parcourir.getSelectedFile().getPath();
path2= file2;
try {
img = ImageIO.read(new File(file2));
Draw_Image d1= new Draw_Image(img);
//d1.setSize(j.jScrollPane1.getWidth(),j.jScrollPane1.getHeight());
j.jScrollPane1.removeAll();
j. jScrollPane1.add(d1);
add(d1, BorderLayout.CENTER);
}
catch (IOException ex) {
// Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("err");
}
}
}
}
The Main class
public class Main extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public Main() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jButton_Open_Image = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton_Open_Image.setText("Open");
jButton_Open_Image.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_Open_ImageActionPerformed(evt);
}
});
jButton2.setText("Gray_Scale");
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
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(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addComponent(jButton_Open_Image, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
.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(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(53, 53, 53)
.addComponent(jButton_Open_Image)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton_Open_ImageActionPerformed(java.awt.event.ActionEvent evt) {
new LoadImage();
}
/**
* #param args the command line arguments
*/
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(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);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton_Open_Image;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
protected javax.swing.JScrollPane jScrollPane1;
enter image description here
Thanks .
Never use the add(...) method to add a component to a JScrollPane. The component needs to be added to the JViewport of the scroll panel.
This is done automatically when you create a JScrollPane using:
JScrollPane scrollPane = new JScrollPane( someComponent );
or you can use:
scrollPane.setViewportView( someComponent );
If you want to display an image, there is no need to do custom painting. Just add an ImageIcon to a JLabel and add the label to the scroll pane
JLabel label = new JLabel( new ImageIcon(...) );
JScrollPane scrollPane = new JScrollPane( label );
If you do want to do custom painting the DON'T extend Canvas, that is an AWT component. Instead you can extend JPanel. When you extend JPanel you would then need to override paintComponent(...) and implement getPreferredSize() in order to get the scroll pane to work properly.
Read the section from the Swing tutorial on Custom Painting for more information. Keep a link to the tutorial handy for all the Swing basics.
The tutorial also has a section on How to Use Icons you should read.
I am a newbie here. Sorry for any bad post or any other bad things.
This question is the continuation of this stackoverflow question. And I already know about the JFrame problem JFrame Bad Practice. The problem is I'm a newbie using Netbeans to code Java. All I know is how to make program with JFrame. Below is the code that I have made. Please help me correct it so the purpose of my code (set Answer class text from TheCombo class selected combobox) can be done.
Please correct this codes (I have 3 classes). I want to get the ComboBox selected Item to be used in the answer class.
Main Class:
package testing;
public class Testing {
public static void main(String[] args) {
new TheCombo().setVisible(true);
}
}
Combo Class:
package testing;
public class TheCombo extends javax.swing.JFrame {
public TheCombo() {
initComponents();
}
public String getItem()
{
String theItem = jComboBox1.getSelectedItem().toString();
return theItem;
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jButton1.setText("Go");
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(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
new Answer().setVisible(true);
this.dispose();
}
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(TheCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TheCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TheCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TheCombo.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 TheCombo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox1;
// End of variables declaration
}
The Other Class (I want to set text the JTextField1 with selected item from the ComboBox at Combo Class):
package testing;
public class Answer extends javax.swing.JFrame {
TheCombo tc = new TheCombo();
public Answer() {
initComponents();
jTextField1.setText(tc.getItem());
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField1.setEnabled(false);
jButton1.setText("Back");
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(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
new TheCombo().setVisible(true);
this.dispose();
}
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(Answer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Answer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Answer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Answer.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 Answer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
There are a number of ways you might be able to achieve this, but based on the structure of your code, you seem to be wanting to ask the user a question and then based on the response, do something.
This just screams modal dialog. See How to Make Dialogs for more details
And for example...
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new QuestionPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class FruitPane extends JPanel {
private JComboBox<String> cb;
public FruitPane() {
add(new JLabel("Fruit: "));
cb = new JComboBox<String>(new String[]{"Bananas", "Apples", "Pears"});
add(cb);
}
public String getSelectedFruit() {
return (String) cb.getSelectedItem();
}
}
public class QuestionPane extends JPanel {
private JTextField field;
public QuestionPane() {
add(new JLabel("Your fruit selection"));
field = new JTextField(10);
field.setEditable(false);
add(field);
JButton btn = new JButton("Pick");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FruitPane pane = new FruitPane();
pane.setBorder(new EmptyBorder(10, 10, 10, 10));
int option = JOptionPane.showConfirmDialog(QuestionPane.this, pane, "Fruit", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (option == JOptionPane.OK_OPTION) {
String fruit = pane.getSelectedFruit();
field.setText(fruit);
}
}
});
}
}
}
The problem is how to show the length of the text at run time even it was edited or deleted in java gui programming. Please help to fix the problem.
So here's the code:
area1.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
update();
}
#Override
public void removeUpdate(DocumentEvent e) {
update();
}
#Override
public void changedUpdate(DocumentEvent e) {
update();
}
public void update()
{
lblLength.setText(area1.getText().length()+"\160");
}
});
If all you want to do is keep track of the length of the content of the JTextArea then the DocumentListener is the correct approach, for example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
public class TextAreaLength {
public static void main(String[] args) {
new TextAreaLength();
}
private JLabel lengthLabel;
private JTextArea ta;
public TextAreaLength() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
ta = new JTextArea(10, 20);
ta.setWrapStyleWord(true);
ta.setLineWrap(true);
lengthLabel = new JLabel("0");
ta.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
update(e.getDocument());
}
#Override
public void removeUpdate(DocumentEvent e) {
update(e.getDocument());
}
#Override
public void changedUpdate(DocumentEvent e) {
update(e.getDocument());
}
protected void update(Document doc) {
lengthLabel.setText(Integer.toString(doc.getLength()));
}
});
lengthLabel.setHorizontalAlignment(JLabel.RIGHT);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(ta);
frame.add(lengthLabel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
If this isn't working for you then either you've done something else wrong in your code that you're not showing us or you've not stated the problem well enough for us to understand
This is actually wrong and should not be done this way but I will leave it here for future reference
Fairly easy. You just have a KeyTyped listener and every time it gets triggered you update the number of chars.
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jMainPanel = new javax.swing.JPanel();
jCharsTextField = new javax.swing.JTextField();
jCharsNumLabel = new javax.swing.JLabel();
jCharsNumCounterLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jCharsTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jCharsTextFieldKeyTyped(evt);
}
});
jCharsNumLabel.setText("Chars #:");
jCharsNumCounterLabel.setText(" ");
javax.swing.GroupLayout jMainPanelLayout = new javax.swing.GroupLayout(jMainPanel);
jMainPanel.setLayout(jMainPanelLayout);
jMainPanelLayout.setHorizontalGroup(
jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jMainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jCharsTextField)
.addComponent(jCharsNumLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCharsNumCounterLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(303, Short.MAX_VALUE))
);
jMainPanelLayout.setVerticalGroup(
jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jMainPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jCharsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCharsNumLabel)
.addComponent(jCharsNumCounterLabel))
.addContainerGap(242, 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(jMainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jMainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jCharsTextFieldKeyTyped(java.awt.event.KeyEvent evt) {
jCharsNumCounterLabel.setText(Integer.toString(jCharsTextField.getText().length()));
}
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(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);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jCharsNumCounterLabel;
private javax.swing.JLabel jCharsNumLabel;
private javax.swing.JTextField jCharsTextField;
private javax.swing.JPanel jMainPanel;
// End of variables declaration
}
This is your point of interest:
private void jCharsTextFieldKeyTyped(java.awt.event.KeyEvent evt) {
jCharsNumCounterLabel.setText(Integer.toString(jCharsTextField.getText().length()));
}
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. :)