Why this java program not working properly? - java

I am newcomer to java and as you see this program in java swing consists of one jframe and one jpanel. When you click a button its color changes to red and automatically button 1 pressed and its color changed to blue.
But the problem is I want a delay between these actions and when I use Thread.sleep(1000) it causes a delay between pressing a button and changing its color and I don't want that.
What can i do that when I press the button 2 (for example) its color changed immediately and after 1 second button 1 pressed?
jframe:
public class NewJFrame extends javax.swing.JFrame {
private String player = "Player 1";
private JButton[] btn = new JButton[4];
public NewJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
newJPanel1 = new NewJPanel();
newJPanel2 = new NewJPanel();
btn1 = new javax.swing.JButton();
btn2 = new javax.swing.JButton();
btn3 = new javax.swing.JButton();
javax.swing.GroupLayout newJPanel1Layout = new javax.swing.GroupLayout(newJPanel1);
newJPanel1.setLayout(newJPanel1Layout);
newJPanel1Layout.setHorizontalGroup(
newJPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
newJPanel1Layout.setVerticalGroup(
newJPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
newJPanel2.setBackground(new java.awt.Color(255, 255, 255));
newJPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
btn1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAction(evt);
}
});
btn2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAction(evt);
}
});
btn3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAction(evt);
}
});
javax.swing.GroupLayout newJPanel2Layout = new javax.swing.GroupLayout(newJPanel2);
newJPanel2.setLayout(newJPanel2Layout);
newJPanel2Layout.setHorizontalGroup(
newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(newJPanel2Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(btn1)
.addGap(74, 74, 74)
.addComponent(btn2)
.addGap(66, 66, 66)
.addComponent(btn3)
.addContainerGap(104, Short.MAX_VALUE))
);
newJPanel2Layout.setVerticalGroup(
newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(newJPanel2Layout.createSequentialGroup()
.addGap(31, 31, 31)
.addGroup(newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn3, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(222, Short.MAX_VALUE))
);
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(newJPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(newJPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void btnAction(java.awt.event.ActionEvent evt) {
JButton btn = (JButton) evt.getSource();
if (player.equals("Player 1")) {
player = "Player 2";
btn.setBackground(Color.RED);
} else {
player = "Player 1";
btn.setBackground(Color.BLUE);
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
player2Action();
}
private void player2Action() {
if (player.equals("Player 2")) {
btn1.doClick();
}
}
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.JButton btn1;
private javax.swing.JButton btn2;
private javax.swing.JButton btn3;
private NewJPanel newJPanel1;
private NewJPanel newJPanel2;
// End of variables declaration
}
jpanel:
public class NewJPanel extends javax.swing.JPanel {
public NewJPanel() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
}

In this case, use Timer in stead of Thread. Look at comments from Andrew Thompson for more details.
To fix your code, just remove the try-catch block of the Thread.sleep and the player2Action() method next to it. Then add following codes to make it work:
ActionListener player2ActionListener = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
player2Action();
}
};
Timer timer = new Timer(1000, player2ActionListener);
timer.setRepeats(false);
timer.start();
And don't forget to import javax.swing.Timer.

Related

Java Swing GUI freezes after boutton pressed

I'm a newbie in java, and i"m trying to makge a simple GUI that will allow once a button clicked, to execute a .bat file and display the outpus in a JTextPane.
But once the button is pressed (The .bat file is excecuted), the whole GUI freezes, even after all the commands of the .bat file are excecuted.
I made some searchs and i've been told to create another thread in which the action on the bat file will be process, and i don't know how to do it.
This is my code :
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.casys.appletloader;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* #author ADMIN
*/
public class View1 extends javax.swing.JFrame {
/**
* Creates new form View1
*/
public View1() {
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() {
jInternalFrame1 = new javax.swing.JInternalFrame();
jMenuItem2 = new javax.swing.JMenuItem();
jFrame1 = new javax.swing.JFrame();
fileButton = new javax.swing.JButton();
installBoutton = new javax.swing.JButton();
listBoutton = new javax.swing.JButton();
jProgressBar1 = new javax.swing.JProgressBar();
jLabel1 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
apduOutput = new javax.swing.JTextPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem3 = new javax.swing.JMenuItem();
jMenu4 = new javax.swing.JMenu();
jMenuItem4 = new javax.swing.JMenuItem();
jInternalFrame1.setVisible(true);
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jMenuItem2.setText("jMenuItem2");
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Application Loader - Casys Technology");
setLocationByPlatform(true);
setMaximumSize(new java.awt.Dimension(693, 492));
setMinimumSize(new java.awt.Dimension(693, 492));
setResizable(false);
fileButton.setText("Choose File...");
fileButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileButtonActionPerformed(evt);
}
});
installBoutton.setText("Install Applet");
installBoutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
installBouttonActionPerformed(evt);
}
});
listBoutton.setText("List applets");
listBoutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
listBouttonActionPerformed(evt);
}
});
jLabel1.setText("File Name");
jScrollPane1.setViewportView(apduOutput);
jMenu1.setText("Instaling Applet");
jMenu1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu1ActionPerformed(evt);
}
});
jMenuBar1.add(jMenu1);
jMenu2.setText("Encoding");
jMenu2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu2ActionPerformed(evt);
}
});
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_DOWN_MASK));
jMenuItem1.setText("Encode");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem1);
jMenuBar1.add(jMenu2);
jMenu3.setText("APDU");
jMenu3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu3ActionPerformed(evt);
}
});
jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_DOWN_MASK));
jMenuItem3.setText("Excecute an APDU command");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu3.add(jMenuItem3);
jMenuBar1.add(jMenu3);
jMenu4.setText("About");
jMenu4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu4ActionPerformed(evt);
}
});
jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.CTRL_DOWN_MASK));
jMenuItem4.setText("About the program");
jMenu4.add(jMenuItem4);
jMenuBar1.add(jMenu4);
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()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(237, 237, 237))
.addGroup(layout.createSequentialGroup()
.addGap(119, 119, 119)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(installBoutton, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(fileButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(listBoutton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap(56, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(fileButton)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(installBoutton)
.addGap(19, 19, 19)
.addComponent(listBoutton)
.addGap(43, 43, 43)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(21, Short.MAX_VALUE))
);
getAccessibleContext().setAccessibleDescription("");
pack();
}// </editor-fold>
private void fileButtonActionPerformed(java.awt.event.ActionEvent evt) {
new javax.swing.JFileChooser().setVisible(true);
}
private void listBouttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jMenu4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {
// new encoding_view().setVisible(true);
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
new encoding_view().setVisible(true);
}
private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
new apdu_view().setVisible(true);
}
private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void installBouttonActionPerformed(java.awt.event.ActionEvent evt) {
Runtime runtime = Runtime.getRuntime();
try {
Process p1 = runtime.exec("cmd /c C:\\Java\\commandes_applet\\delete.bat");
InputStream is = p1.getInputStream();
int i = 0;
while ((i = is.read()) != -1) {
System.out.print((char) i);
apduOutput.setText(String.valueOf((char) i));
}
} catch (IOException ioException) {
System.out.println(ioException.getMessage());
JOptionPane.showMessageDialog(null, ioException);
}
/* try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
JOptionPane.showMessageDialog(null, ex);
}*/
}
/**
* #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(View1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(View1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(View1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(View1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new View1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextPane apduOutput;
private javax.swing.JButton fileButton;
private javax.swing.JButton installBoutton;
private javax.swing.JFrame jFrame1;
private javax.swing.JInternalFrame jInternalFrame1;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField2;
private javax.swing.JButton listBoutton;
// End of variables declaration
}
This is the code of the listener of the boutton :
Runtime runtime = Runtime.getRuntime();
try {
Process p1 = runtime.exec("cmd /c C:\\Java\\commandes_applet\\delete.bat");
InputStream is = p1.getInputStream();
int i = 0;
while ((i = is.read()) != -1) {
System.out.print((char) i);
apduOutput.setText(String.valueOf((char) i));
}
} catch (IOException ioException) {
System.out.println(ioException.getMessage());
JOptionPane.showMessageDialog(null, ioException);
}
/* try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
JOptionPane.showMessageDialog(null, ex);
}*/
} ```
I'm using the NetBeans GUI drag and drop feature to make the UI.

Frame resets when label or text change

I am currently having some problem in some javaFrame application. It is a simple game where the ball is running around and there is one button which starts and stops the ball. The problem is whenever i change the text of a label or a button while the ball is running the frame resets(the ball is resetting where it was in the first place) and i don't want that to happen. I created the frame and the panel by dragging from the side(i did not write code to create frame and panels). I don't know all the rules in this site and i don't know if it is permissible but i could not find any ways to show this to you so i linked 2 short youtube videos at the end so you can see what it is(i apologize for that).
What i did in frame:
Created 2 panels.
Added a button to panel1(upper one) and added ball image on top of it.
Added 2 buttons on panel2(lower one) which are Start/Stop and changeLabel.
My NewJFrame Class:
package view;
import controller.BallAction;
public class NewJFrame extends javax.swing.JFrame {
private BallAction ba;
private boolean isBallRolling = false;
private int labelAsciiValue = 65;
public NewJFrame() {
initComponents();
ba = new BallAction(ball);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
ball = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jButton2 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Ball Game");
ball.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/top.png"))); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(ball, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(515, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(ball, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(291, Short.MAX_VALUE))
);
jButton2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton2.setText("Start");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton1.setText("Change Label");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(85, 85, 85)
.addComponent(jButton1)
.addGap(107, 107, 107)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap(35, Short.MAX_VALUE))
);
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(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
//Start-Stop Button
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
if(isBallRolling){
ba.stop();
jButton2.setText("Start");
isBallRolling = false;
}
else{
ba.start();
jButton2.setText("Stop");
isBallRolling = true;
}
}
//Change Label Button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel1.setText(String.valueOf((char)(labelAsciiValue++)));
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
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.JButton ball;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
// End of variables declaration
}
My BallAction Class:
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.Timer;
public class BallAction {
private Timer time;
private final ClockListener clock = new ClockListener();
private JButton ball;
public BallAction(JButton ball){
this.ball=ball;
time = new Timer(20,clock);
}
public void start(){
time.start();
}
public void stop(){
time.stop();
}
//If ball.x <= panel.x go right else ball.x = 0.
public void update(){
if(ball.getLocation().x<=ball.getParent().getSize().width-100)
ball.setLocation(ball.getLocation().x+5,ball.getLocation().y);
else{
ball.setLocation(0,ball.getLocation().y);
}
}
private class ClockListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
update();
}
}
}
Frame without changing anything : https://www.youtube.com/watch?v=yC_8tyUmal0
Frame with changing the text : https://www.youtube.com/watch?v=zGvhCnRRTtw
EDIT:
If i create the frame on my own it works fine.
Why is that please help me thank you.
My Own Frame:
package ballgame0;
import controller.BallAction;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class BallGame0 {
private static boolean isBallRunning = false;
private static int labelAsciiValue = 65;
public static void main(String[] args) {
JFrame frame = new JFrame("New Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000,800);
frame.setVisible(true);
JPanel panel= new JPanel(null);
frame.add(panel);
JLabel changeLabel = new JLabel();
changeLabel.setSize(100,50);
changeLabel.setLocation(500,650);
changeLabel.setFont(new Font("Tahoma", 0, 36));
JButton buttonLabel = new JButton("Change Label");
buttonLabel.setSize(150,40);
buttonLabel.setLocation(300,650);
JButton button = new JButton("asd");
button.setSize(70,70);
JButton button1 = new JButton("Start");
button1.setSize(100,60);
button1.setLocation(100,650);
panel.add(changeLabel);
panel.add(buttonLabel);
panel.add(button);
panel.add(button1);
BallAction ba = new BallAction(button);
ActionListener alis = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
changeLabel.setText(String.valueOf((char)labelAsciiValue++));
}
};
buttonLabel.addActionListener(alis);
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(isBallRunning){
ba.stop();
button1.setText("Start");
isBallRunning = false;
}else{
ba.start();
button1.setText("Stop");
isBallRunning = true;
}
}
};
button1.addActionListener(al);
}
}

Add the selected item of a popup menu to a text field which is in same form

How to add the selected item of a popup menu to a text field which is in same form?
I have created a form using Swing. I am posting the code below. I want the selected item of my pop-up menu to be added to a text field. As I am new to the topic. Please help me out.
My objective is to store jmenuitem1 in textfield1 when I'll select it.
public class XXX extends javax.swing.JFrame {
public XXX() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
jPopupMenu1 = new javax.swing.JPopupMenu();
John = new javax.swing.JMenuItem();
Smith = new javax.swing.JMenuItem();
Jacob = new javax.swing.JMenuItem();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
John.setText("jMenuItem1");
John.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JohnActionPerformed(evt);
}
});
jPopupMenu1.add(John);
Smith.setText("jMenuItem2");
jPopupMenu1.add(Smith);
Jacob.setText("jMenuItem3");
jPopupMenu1.add(Jacob);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Name");
jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
jTextField1MouseReleased(evt);
}
});
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jLabel2.setText("CLASS");
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(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField2)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))
.addContainerGap(226, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(226, Short.MAX_VALUE))
);
pack();
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void JohnActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jTextField1MouseReleased(java.awt.event.MouseEvent evt) {
if(evt.isPopupTrigger())
{
jPopupMenu1.show(this,evt.getX(),evt.getY());
}
}
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(XXX.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(XXX.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(XXX.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(XXX.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new XXX().setVisible(true);
}
});
}
private javax.swing.JMenuItem Jacob;
private javax.swing.JMenuItem John;
private javax.swing.JMenuItem Smith;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPopupMenu jPopupMenu1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
}
You need to use setText() method of JTextField. And getSource() of ActionEvent for determine selected JMenuItem`.
You can store text of your JMenuItem in next way:
private void JohnActionPerformed(java.awt.event.ActionEvent evt) {
JMenuItem source = (JMenuItem) evt.getSource();
jTextField1.setText(source.getText());
}
If you need to store object(JMenuItem), you need to extends JTextField with your implementation.

Why doesn't repaint() work on my JPanel?

I've made my own subclass of JPanel, called SubPatternPanel. I want to use it in a frame to draw a grid, but when I call repaint() for the SubPatternPanel from the frame, it doesn't work.
When run, the frame is displayed with a "New" button. When New is pressed, a grid should be painted by my panel, but it isn't and I can't find the cause.
Below is the code for the SubPatternPanel:
package View;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class SubPatternPanel extends JPanel
{
public SubPatternPanel()
{
setLayout(null);
setBackground(Color.white);
setPreferredSize(new Dimension(240, 240));
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.black);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
g.drawLine(i * 80, j * 80, 240, j * 80);
g.drawLine(i * 80, j * 80, i * 80, 240);
}
}
}
}
Most of the frame code has been autogenerated, so I'm not sure what to leave out for a clearer picture.
package View;
import java.awt.BorderLayout;
public class PatternsMainFrame extends javax.swing.JFrame
{
private SubPatternPanel subPatternPanel;
public PatternsMainFrame()
{
initComponents();
subPatternPanel = new SubPatternPanel();
patternStartPanel.add(subPatternPanel, BorderLayout.CENTER);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents()
{
patternStartPanel = new javax.swing.JPanel();
newButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout patternStartPanelLayout = new javax.swing.GroupLayout(patternStartPanel);
patternStartPanel.setLayout(patternStartPanelLayout);
patternStartPanelLayout.setHorizontalGroup(
patternStartPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 277, Short.MAX_VALUE)
);
patternStartPanelLayout.setVerticalGroup(
patternStartPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 278, Short.MAX_VALUE)
);
newButton.setText("New");
newButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
newButtonActionPerformed(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(patternStartPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 248, Short.MAX_VALUE)
.addComponent(newButton)
.addGap(112, 112, 112))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(patternStartPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(newButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}
private void newButtonActionPerformed(java.awt.event.ActionEvent evt)
{
subPatternPanel.repaint();
}
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(PatternsMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(PatternsMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(PatternsMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(PatternsMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new PatternsMainFrame().setVisible(true);
}
});
}
private javax.swing.JButton newButton;
private javax.swing.JPanel patternStartPanel;
}
You should use setVisible(true) instead of repaint().
repaint checks first whether visibility was set to true. repaint() is typically invoked when you want to repaint something that has already been painted once.

Close an Opened JInternalFrame that is been opened within another JInternalFrame while changing the tab of a JTabbedPane

I've created and application in which there are two tabs titled Tabbedpane 1 and Tabbedpane 2. In one tab body Tabbedpane 1 contains a JInternalFrame in which there is a search button. On clicking the button another JInternalFrame opens within the main JInternalFrame.
Can anyone please tell me how to close the said opened JInternalFrame ie the search JInternalFrame while clicking on to the second tab titled Tabbedpane 2
I've tried .setClosed(true) and .setVisible(true) on property change still it does'nt works for me.
Use a ChangeListener which will get notified when JTabbedPane state changes (i.e tabs switched):
final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
//tab has been changed
}
});
The problem is we will need a way to monitor the previous tab i.e the tab we were on before it was changed this can be done via:
tabbedPane.addChangeListener(new ChangeListener() {
int prev_index = 0;
int curr_index = 0;
public void stateChanged(ChangeEvent e) {
prev_index = curr_index;
curr_index = tabbedPane.getSelectedIndex();
System.out.println("Tab (Current): " + curr_index);
System.out.println("Tab (Previous): " + prev_index);
}
});
UPDATE 1:
To close JInternalFrame I'd suggest calling dispose() on its instance
UPDATE 2:
Here is your fixed code, basically added a getter for Search class, thus JIFrame1 has a getSearch() method which allows us to gaim access to the Search classes current instance created in JIFrame1, in changedState(..) I call jiFrame1.getSearch().dispose() which will make sure we dispose of the instance that has already been created:
import java.awt.Container;
import java.awt.event.MouseListener;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Sample extends javax.swing.JFrame {
JIFrame1 jiframe1 = new JIFrame1();
public Sample() {
initComponents();
Container jiframe1cont = tab1;
for (MouseListener listener : ((javax.swing.plaf.basic.BasicInternalFrameUI) jiframe1.getUI()).getNorthPane().getMouseListeners()) {
((javax.swing.plaf.basic.BasicInternalFrameUI) jiframe1.getUI()).getNorthPane().removeMouseListener(listener);
}
jiframe1.setLocation(10, 10);
jiframe1cont.add(jiframe1);
jiframe1.setVisible(true);
JIFrame2 jiframe2 = new JIFrame2();
Container jiframe2cont = tab2;
for (MouseListener listener : ((javax.swing.plaf.basic.BasicInternalFrameUI) jiframe2.getUI()).getNorthPane().getMouseListeners()) {
((javax.swing.plaf.basic.BasicInternalFrameUI) jiframe2.getUI()).getNorthPane().removeMouseListener(listener);
}
jiframe2.setLocation(10, 10);
jiframe2cont.add(jiframe2);
jiframe2.setVisible(true);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tab1 = new javax.swing.JDesktopPane();
tab2 = new javax.swing.JDesktopPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tabbedPane.setTabPlacement(javax.swing.JTabbedPane.LEFT);
tabbedPane.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
tabbedPaneStateChanged(evt);
}
});
tab1.setBackground(new java.awt.Color(240, 240, 240));
tabbedPane.addTab("Tabbedpane 1", tab1);
tab2.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.background"));
tabbedPane.addTab("Tabbedpane 2", tab2);
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.DEFAULT_SIZE, 731, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 503, Short.MAX_VALUE));
pack();
}// </editor-fold>
private void tabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {
try {
jiframe1.getSearch().dispose();
} catch (Exception ex) {
Logger.getLogger(Sample.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Sample().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JDesktopPane tab1;
private javax.swing.JDesktopPane tab2;
private final javax.swing.JTabbedPane tabbedPane = new javax.swing.JTabbedPane();
// End of variables declaration
}
class Search extends javax.swing.JInternalFrame {
public Search() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jTextField1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object[][]{
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String[]{
"Title 1", "Title 2", "Title 3", "Title 4"
}));
jScrollPane1.setViewportView(jTable1);
jButton1.setText("CLOSE");
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, 385, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(205, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(172, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
class JIFrame1 extends javax.swing.JInternalFrame {
public JIFrame1() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
pane = new javax.swing.JDesktopPane();
jButton1 = new javax.swing.JButton();
pane.setBackground(new java.awt.Color(240, 240, 240));
jButton1.setText("SEARCH");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton1.setBounds(170, 60, 90, 23);
pane.add(jButton1, javax.swing.JLayeredPane.DEFAULT_LAYER);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pane, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pane, javax.swing.GroupLayout.DEFAULT_SIZE, 322, Short.MAX_VALUE));
pack();
}// </editor-fold>
private Search search;
public Search getSearch() {
return search;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
search = new Search();
Container searchcont = pane;
for (MouseListener listener : ((javax.swing.plaf.basic.BasicInternalFrameUI) search.getUI()).getNorthPane().getMouseListeners()) {
((javax.swing.plaf.basic.BasicInternalFrameUI) search.getUI()).getNorthPane().removeMouseListener(listener);
}
search.setLocation(10, 10);
searchcont.add(search);
search.setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JDesktopPane pane;
// End of variables declaration
}
class JIFrame2 extends javax.swing.JInternalFrame {
public JIFrame2() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel1.setText("JIFrame2..............");
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(100, 100, 100)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(137, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(86, 86, 86)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(145, Short.MAX_VALUE)));
pack();
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
UPDATE 3:
The reason for NPE is here:
private void tabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {
try {
jiframe1.getSearch().dispose();
} catch (Exception ex) {
Logger.getLogger(Sample.class.getName()).log(Level.SEVERE, null, ex);
}
}
change to this:
private void tabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {
try {
Search s=jiframe1.getSearch();
if(s!=null)
s.dispose();
} catch (Exception ex) {
Logger.getLogger(Sample.class.getName()).log(Level.SEVERE, null, ex);
}
}

Categories

Resources