JPanel appears in Netbeans debug but not in run mode - java

I am using NetBeans IDE 7.0 with JDK1.6.0_25. I am trying to compile the following code. When I run this code in "Debug Project" mode (Ctrl+F5) it works fine. However if I try to run by "Run Project" mode (F6) I don't see any panel and button on screen. Please help.
Code:
package pss;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.BorderFactory;
import java.io.IOException;
import java.io.FileNotFoundException;
import org.lirc.util.*;
import org.lirc.LIRCException;
public class ErrMessage extends javax.swing.JFrame {
public static SimpleLIRCClient client;
public static String configFile = "/etc/Remote.lirc";
public ErrMessage(String ErrMessage, String ErrButton) {
initComponents();
setLocationRelativeTo(null);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0, 0, screenSize.width, screenSize.height);
EPanel.setOpaque(false);
EPanel.setPreferredSize(screenSize);
EPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
ImageIcon ii = new ImageIcon("/etc/assets/bg.jpg");
wrapInBackgroundImage inBackgroundImageObj = new wrapInBackgroundImage();
this.setContentPane(wrapInBackgroundImage.wrapInBackgroundImage(EPanel, ii));
EMsgLabel.setText(ErrMessage);
EMsgLabel.setPreferredSize(screenSize);
EMsgButton.setText(ErrButton);
addRemoteListener();
client.addIRActionListener(new IRListenerList());
this.setVisible(true);
}
public static void addRemoteListener() {
try {
client = new SimpleLIRCClient(configFile);
} catch (LIRCException ex) {
Logger.getLogger(ErrMessage.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(ErrMessage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ErrMessage.class.getName()).log(Level.SEVERE, null, ex);
}
}
private class IRListenerList implements IRActionListener {
public void action(String command) {
if (command.equals("Ok")) { // Proceed for selected item
selectOk();
}
}
}
public void selectOk() {
client.stopListening();
this.setVisible(false);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
EPanel = new javax.swing.JPanel();
EMsgLabel = new javax.swing.JLabel();
EMsgButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
setUndecorated(true);
EPanel.setBackground(new java.awt.Color(156, 172, 202));
EMsgLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 36));
EMsgLabel.setForeground(java.awt.Color.red);
EMsgLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
EMsgLabel.setText("jLabel1");
EMsgLabel.setInheritsPopupMenu(false);
EMsgLabel.setMaximumSize(new java.awt.Dimension(1000, 50));
EMsgLabel.setMinimumSize(new java.awt.Dimension(1000, 50));
EMsgButton.setBackground(java.awt.Color.yellow);
EMsgButton.setFont(new java.awt.Font("DejaVu Sans", 0, 18));
EMsgButton.setText("jButton1");
EMsgButton.setBorder(javax.swing.BorderFactory.createEtchedBorder());
EMsgButton.setBorderPainted(false);
EMsgButton.setOpaque(true);
EMsgButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EMsgButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout EPanelLayout = new javax.swing.GroupLayout(EPanel);
EPanel.setLayout(EPanelLayout);
EPanelLayout.setHorizontalGroup(
EPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(EPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EMsgButton, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EMsgLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 740, Short.MAX_VALUE))
.addContainerGap())
);
EPanelLayout.setVerticalGroup(
EPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EPanelLayout.createSequentialGroup()
.addGap(118, 118, 118)
.addComponent(EMsgLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
.addGap(40, 40, 40)
.addComponent(EMsgButton, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(302, 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()
.addComponent(EPanel, 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(EPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void EMsgButtonActionPerformed(java.awt.event.ActionEvent evt) {
selectOk();
}
// Variables declaration - do not modify
private javax.swing.JButton EMsgButton;
private javax.swing.JLabel EMsgLabel;
private javax.swing.JPanel EPanel;
// End of variables declaration
}
Regards
Prakash

Verify that you're using the event dispatch thread correctly. The debugger sometimes slows things down just enough to expose such anomalies.

Related

Basically what i want is to display the usb directoires and a local drive directoires in two jscrollpane side by side

I have made two JScrollPane components. The left one shows the directories in USB and right shows the directories of a local drive. For I am able to display the complete file path as shown in first pic. But I want to display it with icons just like the way directories are displayed in any local drive on PC. This is my designed GUI, here is the example of what I want example
public class MainForm extends javax.swing.JFrame {
iRecordCopy obj = new iRecordCopy();
public MainForm() {
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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jScrollPane2 = new javax.swing.JScrollPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Main From");
setLocation(new java.awt.Point(0, 0));
setName("mainframe"); // NOI18N
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel1.setText("iRecordCopy");
jLabel2.setText("jLabel2");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(48, 48, 48)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(25, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(30, 30, 30))
);
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.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jPanel1, 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()
.addComponent(jPanel1, 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.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public 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(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.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 MainForm().setVisible(true);
}
});
}
public void showusb()
{
File[] usb;
int count = 0;
String str;
usb = obj.detectUSB();
if(usb == null)
{
//USB_window.setText("No USB attached\n");
return;
}
for (File filename : usb) {
str = filename.toString().substring(3);
str = str.substring(0, str.length() - 3);
System.out.println(str);
if(str.equalsIgnoreCase("vehicle"))
{
System.out.print(filename.toString());
//USB_window.append(filename.getPath()+"\n");
count++;
}
}
if(count == 0)
{
System.out.println("No recordings found in usb");
}
else
System.out.println("Number of directries :" + count);
//File currentDir = new File(System.getProperty("user.home"));
JList<File> jlist=new JList<File>(obj.path.listFiles());
jScrollPane1 = new JScrollPane(jlist);
jScrollPane1.setPreferredSize(new Dimension(400, 800));
setContentPane(jScrollPane1);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
}
public void showPc(File f)
{
JList<File> jlist=new JList<File>(f.listFiles());
jScrollPane2 = new JScrollPane(jlist);
//jScrollPane2.setPreferredSize(new Dimension(400, 800));
setContentPane(jScrollPane2);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration
}
Here a short example to create a minimal JList with file icons, it displays the content of the user's home directory using the system file icons.
package test;
import java.awt.Component;
import java.awt.Dimension;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.filechooser.FileSystemView;
public class Test {
public static void main(String[] args) {
JFrame frame=new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File currentDir=new File(System.getProperty("user.home"));
JList<File> jlist=new JList<File>(currentDir.listFiles());
JScrollPane scrollPane=new JScrollPane(jlist);
scrollPane.setPreferredSize(new Dimension(400, 800));
frame.setContentPane(scrollPane);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
frame.pack();
frame.setVisible(true);
}
}

Swing JFrame GUI window is empty when run

I've built a Higher/Lower game, using the Swing library. When I run the code I don't get any errors or warnings. The problem appears when I try running the code, the window is empty, not the way it should be.
I use NetBeans to program.There are 2 different files in my project, here is the code...
HiLoGUI.java:
import java.awt.Dimension;
import javax.swing.*;
public class HiLoGUI extends JFrame {
private JTextField txtGuess;
private JLabel outputLabel;
private int theNumber;
public void newGame() {
theNumber = (int)(Math.random() * 100 + 1);
}
public void checkGuess() {
String guessText = txtGuess.getText();
String message = "";
int guess = Integer.parseInt(guessText);
if (guess < theNumber) {
message = guess + " is too low. Try again.";
}
else if (guess > theNumber) {
message = guess + " is too high. Try again.";
}
else {
message = guess + " is correct. You win!";
}
outputLabel.setText(message);
}
public static void main(String[] args) {
HiLoGUI theGame = new HiLoGUI();
theGame.newGame();
theGame.setSize(new Dimension(450,300));
theGame.setVisible(true);
}
}
The window should look like this:
NetBeans screenshot
EDIT:
The other files code:
public class HiLoJFrame extends javax.swing.JFrame {
/**
* Creates new form HiLoJFrame
*/
public HiLoJFrame() {
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() {
jPanel1 = new javax.swing.JPanel();
titleLabel = new javax.swing.JLabel();
chooseLabel = new javax.swing.JLabel();
txtGuess = new javax.swing.JTextField();
guessButton = new javax.swing.JButton();
outputLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setName("HiLoGame"); // NOI18N
titleLabel.setFont(new java.awt.Font("SansSerif", 1, 24)); // NOI18N
titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
titleLabel.setText("High/Lower Game");
titleLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
chooseLabel.setFont(new java.awt.Font("SansSerif", 0, 15)); // NOI18N
chooseLabel.setText("Guess a name between 1 to 100");
txtGuess.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtGuessActionPerformed(evt);
}
});
guessButton.setFont(new java.awt.Font("Ubuntu", 0, 18)); // NOI18N
guessButton.setText("Guess");
guessButton.setCursor(new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR));
guessButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
guessButtonActionPerformed(evt);
}
});
outputLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
outputLabel.setText("Enter a number and press Guess");
outputLabel.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(50, Short.MAX_VALUE)
.addComponent(chooseLabel)
.addGap(18, 18, 18)
.addComponent(txtGuess, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(136, 136, 136)
.addComponent(guessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(78, 78, 78)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(titleLabel)
.addComponent(outputLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addGap(75, 75, 75)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtGuess, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chooseLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addComponent(guessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(53, 53, 53)
.addComponent(outputLabel)
.addGap(35, 35, 35))
);
titleLabel.getAccessibleContext().setAccessibleDescription("");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 422, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 346, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
getAccessibleContext().setAccessibleName("HiLoGame");
pack();
}// </editor-fold>
private void txtGuessActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void guessButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
HiLoGUI hilogui = new HiLoGUI();
hilogui.checkGuess();
}
/**
* #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(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new HiLoJFrame().setVisible(true);
});
}
// Variables declaration - do not modify
private javax.swing.JLabel chooseLabel;
private javax.swing.JButton guessButton;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel outputLabel;
private javax.swing.JLabel titleLabel;
private javax.swing.JTextField txtGuess;
// End of variables declaration
}
EDIT2:
I've changed the main class of HiLoGUI.java
I was creating a wrong object.
New main:
public static void main(String[] args) {
HiLoJFrame theGame = new HiLoJFrame();
theGame.newGame();
theGame.setSize(new Dimension(450,300));
theGame.setVisible(true);
}
Now it claims that I need to create that method (newGame) in the JFrame file.
You are calling a method from the wrong class, according to the Swing docs, it is not needed to create a new JFrame object, so setting its visibility is enough. Check this out: How To Call JFrame from another Java class

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

Accessing elements from a jFrame that is within a running instance of a thread

I am trying to make an app for communicating between different running instances of a thread. I have a jFrame that has a jTextField and a jButton. In the jTextField I type the number of threads that I want to run and after I press the jButton the threads run. Each thread contains a jFrame with a jButton. So if I type 3 in the jTextField and then press OK, three different jFrames pop out that have an own jButton. If I press the jButton in one of the jFrames of the threads, the jButton is set to disabled (setEnabled(false)). This should happen to each jButton of the jFrames from within the threads when pressed but the one from the last jFrame that is still not pressed.
This is the window class for the thread:
public class Window extends JFrame implements Runnable {
JFrame jr;
JButton bt;
public void run() {
jr=new JFrame();
bt=new jButton();
bt.setTitle("Press Me");
jr.setLayout(new FlowLayout());
jr.add(bt);
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
bt.setEnabled(false);
}
});
jr.setVisible(true);
}
}
Now this is how I run multiple instances of this thread. i is the number of the thread instances that is taken from the jTextField:
( int i=Integer.parseInt(jTextField1.gettext()) )
for (int a=0;a<i;a++) {
Runnable thr=new Window(a);
executor.execute(thr);
}
This is what I want to do: After I press the jButton on every jFrame that is within the thread instances and it is set to setEnabled(false) I get to the last jFrame that is popped up whose jButton is still unpressed. When I press this last JButton I want that all the JButtons on every jFrame to be set back to setEnabled(true). How can I do that?
This is the main class it works 100 % now!
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* #author oliver
*/
public class Hauptklasse extends javax.swing.JFrame {
static int i = 0;
static Random r;
static boolean OkApasat=false;
static int c;
public static Fereastra[] thread;
public Hauptklasse() throws IOException {
initComponents();
Image logo;
logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
jLabel4.setIcon(new ImageIcon(logo));
jLabel4.setVisible(true);
setLocation(200,100);
jPanel1.setBackground(Color.cyan);
jTextField1.setEditable(false);
jButton2.setEnabled(false);
r=new Random();
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton1.setText("Pornire");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Numar maxim de ferestre");
jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addGroup(jPanel1Layout.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)
.addComponent(jButton2))
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setEditable(true);
jButton1.setEnabled(false);
jButton2.setEnabled(true);
jTextArea1.append("\n Welcome! :)");
jTextArea1.append("\n The following app tests the communication between threads");
jTextArea1.append("\n Please enter maximum number of windows to be opened");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
OkApasat=true;
}
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
final Hauptklasse main1 = new Hauptklasse();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
main1.setVisible(true);
}
});
while (true){
if (OkApasat==true){
if (Integer.parseInt(jTextField1.getText())>=3){
i= (Integer.parseInt(jTextField1.getText()));
main1.jTextArea1.append("\n"+i+" windows opened");
Fereastra[] thr=new Fereastra[i];
for (c = 0; c < i; c++) {
thr[c]=new Fereastra(thr);
thr[c].run();
}
OkApasat=false;
main1.jButton2.setEnabled(false);
main1.jTextField1.setEditable(false);
}
else jTextArea1.append("\n Wrong maximum number of windows-must be at least 3");
OkApasat=false;
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration
}
THIS IS THE WINDOW CLASS, WORKS 100 %:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* #author oliver
*/
public class Fereastra extends JFrame implements Runnable {
public JFrame jr;
public JButton bt;
public JLabel l;
public JLabel l2;
public Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
this.thread = thread;
jr = new JFrame();
jr.setSize(250, 250);
jr.setLayout(new FlowLayout());
bt = new JButton();
jr.add(bt);
bt.setText("OK");
bt.setBackground(Color.cyan);
l2 = new JLabel();
l2.setText("Buton activ");
jr.add(l2);
jr.setVisible(true);
}
public void run() {
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.setEnabled(false);
deblocat = true;
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null && thread[c].bt.isEnabled()) {
deblocat = false;
break;
}
}
if (deblocat == true) {
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null) {
thread[c].bt.setEnabled(true);
}
}
}
}
});
}
}
My classes:
1) The Window class (Fereastra means window, deblocat means unlocked, buton activ means Button is enabled)
package concurenta;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* #author oliver
*/
public class Fereastra extends JFrame implements Runnable {
public static JFrame jr;
public static JButton bt;
public static JLabel l;
public static JLabel l2;
public static Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
this.thread = thread;
jr = new JFrame();
jr.setSize(250, 250);
jr.setLayout(new FlowLayout());
bt = new JButton();
jr.add(bt);
bt.setText("OK");
bt.setBackground(Color.cyan);
l2 = new JLabel();
l2.setText("Buton activ");
jr.add(l2);
jr.setVisible(true);
}
public void run() {
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.setEnabled(false);
deblocat = true;
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null && thread[c].bt.isEnabled()) {
deblocat = false;
break;
}
}
if (deblocat == true) {
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null) {
thread[c].bt.setEnabled(true);
}
}
}
}
});
}
}
2) The Main Class(a.k.a Hauptklasse, okApasat means ok is pressed):
/*
* 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 concurenta;
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* #author oliver
*/
public class Hauptklasse extends javax.swing.JFrame {
static int i = 0;
static Random r;
static boolean OkApasat=false;
static int c;
public static Fereastra[] thread;
public Hauptklasse() throws IOException {
initComponents();
Image logo;
logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
jLabel4.setIcon(new ImageIcon(logo));
jLabel4.setVisible(true);
setLocation(200,100);
jPanel1.setBackground(Color.cyan);
jTextField1.setEditable(false);
jButton2.setEnabled(false);
r=new Random();
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton1.setText("Pornire");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Numar maxim de ferestre");
jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addGroup(jPanel1Layout.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)
.addComponent(jButton2))
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setEditable(true);
jButton1.setEnabled(false);
jButton2.setEnabled(true);
jTextArea1.append("\n Welcome! :)");
jTextArea1.append("\n The following app tests the communication between threads");
jTextArea1.append("\n Please enter maximum number of windows to be opened");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
OkApasat=true;
}
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
final Hauptklasse main1 = new Hauptklasse();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
main1.setVisible(true);
}
});
while (true){
if (OkApasat==true){
if (Integer.parseInt(jTextField1.getText())>=3){
i= (int) (Math.random() * (Integer.parseInt(jTextField1.getText()) - 3)) + 3;
main1.jTextArea1.append("\n"+i+" windows opened");
Fereastra[] thr=new Fereastra[i];
for (c = 0; c < i; c++) {
thr[c]=new Fereastra(thr);
thr[c].run();
}
OkApasat=false;
main1.jButton2.setEnabled(false);
main1.jTextField1.setEditable(false);
}
else jTextArea1.append("\n Wrong maximum number of windows-must be at least 3");
OkApasat=false;
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration
}

How I can only close the JDialog box?

I call a JDialog from a JFrame
but the problem is when I exit the JDialog box , whole program is exit means JFrame window also exit.
I can't only exit the JDialog box window.
How I can only close the JDialog box?
enter code here
package subtitlemakerofvedio;
public class About extends javax.swing.JDialog {
/** Creates new form About */
public About(java.awt.Frame parent, boolean modal) {
super(parent, modal);
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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
Close_Button = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("About: SubTitle Editor 4.8.1.1");
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/about.png"))); // NOI18N
jLabel1.setText("jLabel1");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 15));
jLabel2.setText("SubTitle Editor ");
jLabel3.setText("A simple subtitle editor of vedio ");
jLabel4.setText("<html>You can make bangla and english subtitle using this software");
jLabel5.setText("Product version: 4.8.1.1");
Close_Button.setText("Close");
Close_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Close_ButtonActionPerformed(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()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(22, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Close_Button, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Close_Button))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
/*
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
About dialog = new About(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
*/
// Variables declaration - do not modify
private javax.swing.JButton Close_Button;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
// End of variables declaration
}
Now the JFrame sample code
/*
* JFrame_of_subtitle.java
*
* Created on Apr 2, 2012, 5:58:46 AM
*/
package subtitlemakerofvedio;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class JFrame_of_subtitle extends javax.swing.JFrame
{
/** Creates new form JFrame_of_subtitle */
public MediaPanel media_play;
public javax.swing.Timer time;
public JFrame_of_subtitle(MediaPanel media, javax.swing.Timer t)
{
super("Subtitle Editor 4.8.1.1");
media_play=media;
time=t;
initComponents();
}
private void initComponents() {
//some code.......
}
//this is for the JDialog box
private void About_menuitemActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
//About a=new About(this, rootPaneCheckingEnabled);
About dialog = new About(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter()
{
#Override public void windowClosing(java.awt.event.WindowEvent e)
{
System.exit(0);
}
});
dialog.setVisible(true);
}
}
Well, you are telling to exit the program after the window get's closed.
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
Try setting:
dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
So your window will get disposed when it get's closed.
Edit: Just replace the first code I entered with the second one.
Maybe try using closeAndHide() instead of System.exit(0). System.exit(0) is used to tell everything to close down.

Categories

Resources