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.
Related
I am using Netbeans. I set up a graphics program to do graphing. I overrode 3 JPanel paintComponent methods just to get started but these methods are not being called.
I have programs that work. My new override code looks the same. I've tried a plethora of things and have run out of ideas. I am using Borderlayout for the first time but that shouldn't cause a problem.
import java.awt.Graphics;
import java.awt.Graphics2D;
/*
* 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.
*/
public class MainForm extends javax.swing.JFrame
{
/**
* Creates new form NewJFrame
*/
public MainForm()
{
initComponents();
initProgram();
}
private void initProgram()
{
System.out.println("InitProgram");
}
/**
* 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()
{
pnlPrintPanel = new javax.swing.JPanel();
pnlGraphForm = new javax.swing.JPanel();
pnlGraph = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
pnlInputPanel = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation
(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pnlGraphForm.setBorder
(javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
pnlGraph.setBorder
(javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
jLabel2.setText("jLabel2");
javax.swing.GroupLayout pnlGraphLayout =
new javax.swing.GroupLayout(pnlGraph);
pnlGraph.setLayout(pnlGraphLayout);
pnlGraphLayout.setHorizontalGroup(
pnlGraphLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
pnlGraphLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(277, 277, 277))
);
pnlGraphLayout.setVerticalGroup(
pnlGraphLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphLayout.createSequentialGroup()
.addGap(101, 101, 101)
.addComponent(jLabel2)
.addContainerGap(204, Short.MAX_VALUE))
);
jLabel1.setText("jLabel1");
javax.swing.GroupLayout pnlGraphFormLayout =
new javax.swing.GroupLayout(pnlGraphForm);
pnlGraphForm.setLayout(pnlGraphFormLayout);
pnlGraphFormLayout.setHorizontalGroup(
pnlGraphFormLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(pnlGraph, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE,
59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pnlGraphFormLayout.setVerticalGroup(
pnlGraphFormLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addContainerGap()
.addComponent(pnlGraph, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addContainerGap())
);
pnlGraph = new javax.swing.JPanel()
{
//#Override
//public void paint(Graphics g)
#Override
public void paintComponent(Graphics g)
{
System.out.println("In pnlGraph.paintComponent");
//super.paint(g);
/*
if (grapher == null)
{
return;
}
*/
super.paintComponent(g);
// grapher.drawSlate((Graphics2D)g);
pack();
}
};
pnlInputPanel.setBorder(
javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout pnlInputPanelLayout =
new javax.swing.GroupLayout(pnlInputPanel);
pnlInputPanel.setLayout(pnlInputPanelLayout);
pnlInputPanelLayout.setHorizontalGroup(
pnlInputPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlInputPanelLayout.createSequentialGroup()
.addGap(271, 271, 271)
.addComponent(jButton1)
.addContainerGap(297, Short.MAX_VALUE))
);
pnlInputPanelLayout.setVerticalGroup(
pnlInputPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlInputPanelLayout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
javax.swing.GroupLayout pnlPrintPanelLayout =
new javax.swing.GroupLayout(pnlPrintPanel);
pnlPrintPanel.setLayout(pnlPrintPanelLayout);
pnlPrintPanelLayout.setHorizontalGroup(
pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addComponent(pnlInputPanel,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addComponent(pnlGraphForm,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
pnlPrintPanelLayout.setVerticalGroup(
pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(pnlGraphForm,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pnlInputPanel,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
);
pnlGraphForm = new javax.swing.JPanel()
{
//#Override
//public void paint(Graphics g)
#Override
public void paintComponent(Graphics g)
{
System.out.println("In pnlGraphForm.paintComponent");
//super.paint(g);
/*
if (grapher == null)
{
return;
}
*/
super.paintComponent(g);
// grapher.drawSlate((Graphics2D)g);
pack();
}
};
getContentPane().add(pnlPrintPanel, java.awt.BorderLayout.CENTER);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
System.out.println("BUTTON");
pnlGraphForm.paintComponents((Graphics2D)
pnlGraphForm.getGraphics());
}
/**
* #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(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>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel pnlGraph;
private javax.swing.JPanel pnlGraphForm;
private javax.swing.JPanel pnlInputPanel;
private javax.swing.JPanel pnlPrintPanel;
// End of variables declaration
}
At this stage, I expected to see the panel/method names printed but it isn't happening
I'm currently having trouble (as the title states) appending text to a JTextArea from a separate class (or thread).
Here is my code, since I don't know what's causing the problem. (note that I'm using the Netbeans generated code for my GUI):
Chat Box GUI:
public class ChatBoxGUI extends javax.swing.JFrame
{
/**
* Creates new form ChatBoxGUI
* #return
*/
public javax.swing.JTextArea getTextArea()
{
return inputOutputTextArea;
}
public void setLabels(java.net.SocketAddress address, int port) {
this.addressLabel.setText("IP Address: " +address);
this.portLabel.setText("Port: " +Integer.toString(port));
}
public ChatBoxGUI() {
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();
startServerButton = new javax.swing.JButton();
connectServerButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
addressLabel = new javax.swing.JLabel();
portLabel = new javax.swing.JLabel();
outputTextField = new javax.swing.JTextField();
stopButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
inputOutputTextArea = new javax.swing.JTextArea();
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
startServerButton.setText("Start Server");
startServerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startServerButtonActionPerformed(evt);
}
});
connectServerButton.setText("Connect to Server");
connectServerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
connectServerButtonActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
jLabel1.setText("Isaac's Chat Box");
addressLabel.setText("IP Address:");
portLabel.setText("Port: ");
stopButton.setText("Stop");
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopButtonActionPerformed(evt);
}
});
inputOutputTextArea.setEditable(false);
inputOutputTextArea.setColumns(20);
inputOutputTextArea.setRows(5);
jScrollPane2.setViewportView(inputOutputTextArea);
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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2)
.addComponent(outputTextField, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(startServerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(connectServerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(addressLabel))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(stopButton)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(portLabel)))
.addGap(0, 18, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(startServerButton)
.addComponent(jLabel1)
.addComponent(stopButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(connectServerButton)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(addressLabel)
.addComponent(portLabel)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(outputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void startServerButtonActionPerformed(java.awt.event.ActionEvent evt) {
CreateServerDialog createServerDialog = new CreateServerDialog(this, true);
createServerDialog.setVisible(true);
try {
Runnable serverClassRunnable = new ServerClass(createServerDialog.getPort());
Thread serverClassThread = new Thread(serverClassRunnable);
serverClassThread.start();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
private void connectServerButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #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(ChatBoxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChatBoxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChatBoxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChatBoxGUI.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 ChatBoxGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel addressLabel;
private javax.swing.JButton connectServerButton;
private javax.swing.JTextArea inputOutputTextArea;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField outputTextField;
private javax.swing.JLabel portLabel;
private javax.swing.JButton startServerButton;
private javax.swing.JButton stopButton;
// End of variables declaration
}
Create Server Dialog:
public class CreateServerDialog extends javax.swing.JDialog {
private int port; private boolean isValid = false; private java.awt.Frame parent;
public int getPort() {
return port;
}
/**
* Creates new form CreateServerDialog
*/
public CreateServerDialog(java.awt.Frame par, boolean modal) {
super(par, modal);
parent = par;
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();
portInput = new javax.swing.JTextField();
okButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Enter Port:");
okButton.setText("Ok");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(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(okButton)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(portInput)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(portInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(okButton))
);
pack();
}// </editor-fold>
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
ErrorDialog errorDialog = new ErrorDialog(parent, true);
try {
port = Integer.parseInt(this.portInput.getText());
isValid = true;
} catch (NumberFormatException n) {
errorDialog.errorOccured(0);
isValid = false;
}
if (port <= 1024 || port > 65535) {
errorDialog.errorOccured(0);
isValid = false;
}
if (isValid == true) {
this.dispose();
}
}
/**
* #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(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
CreateServerDialog dialog = new CreateServerDialog(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);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JButton okButton;
private javax.swing.JTextField portInput;
// End of variables declaration
}
Server Class:
import java.io.*;
import java.net.*;
public class ServerClass implements Runnable
{
private final ServerSocket serverSocket;
public ServerClass(int port) throws IOException
{
serverSocket = new ServerSocket(port);
}
public void run()
{
ChatBoxGUI chatBoxGUI = new ChatBoxGUI();
try {
chatBoxGUI.getTextArea().append("\nSearching for client connection. \nPort: " +serverSocket.getLocalPort()); //this is the code that isn't working
Socket server = serverSocket.accept();
System.out.println();
chatBoxGUI.setLabels(server.getLocalSocketAddress(), serverSocket.getLocalPort()); //this also isn't working - but that's not the focus of this question
DataOutputStream out = new DataOutputStream(server.getOutputStream());
DataInputStream in = new DataInputStream(server.getInputStream());
chatBoxGUI.getTextArea().append("\nClient found! Connected with: " +server.getRemoteSocketAddress());
//note: this part isn't finished - but it doesn't need to be for that code to work
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've tried to do research on the problem, and what I've found tells me that I have to use either invokeLater or invokeAndWait when running the code so that it runs in the EDT. And I have tried to implement this but it still doesn't seem to work:
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
chatBoxGUI.getTextArea().append("\nSearching for client connection. \nPort: " +serverSocket.getLocalPort());
}
});
Similar output to the terminal works completely fine, so it's definitely an issue with appending the text.
Any help would be appreciated, and thanks in advance.
You have multiple instances of the ChatBoxGUI class, so you are not updating the text area that is visible on the desktop.
So first you create the ChatBoxGUI class. Then when you click on a button you create the ServerClass. In the ServerClass you create a second instance of the ChatBoxGUI.
Don't create the second instance of the ChatBoxGUI class!!!
Instead, if you want to access variables in the ChatBoxGUI class then you need to:
pass a reference of the ChatBoxGUI class to the ServerClass
save this reference as an instance variable in the ServerClass
access this variable when you want to add text to the text area.
Without a more complete example, all I can do is link you to this question that has an answer for a similar issue.
Or you could try changing your approach from:
public javax.swing.JTextArea getTextArea()
{
return inputOutputTextArea;
}
To:
public void setTextArea(String textToAppend)
{
inputOutputTextArea.append(textToAppend);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
A>>>
package ja7;
import javax.swing.JFrame;
/**
*
* #author lalit kumar
*/
public class gframe extends javax.swing.JFrame {
/**
* Creates new form gframe
*/
public gframe() {
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() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("TRY MAGIC");
setResizable(false);
jButton1.setText("cal");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("fing grade ");
jButton2.setEnabled(false);
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jTextField1.setEditable(false);
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(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()
.addGap(49, 49, 49)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(67, 67, 67))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(73, 73, 73)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(143, Short.MAX_VALUE))
);
jButton2.setVisible(false);
jTextField1.setVisible(false );
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int a,b;
int c;
a=50;
b=56;
c=a+b;
jTextField2.setText(Integer.toString(c));
jButton2.setEnabled(true);
jButton2.setVisible(true );
jTextField1.setVisible(true );
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int c;
c=Integer.parseInt ( jTextField2.getText()) ;
if(c>50)
{
jTextField1.setText("A WARD");
}
else
jTextField1.setText(" B WARD");
}
/**
* #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(gframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(gframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(gframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(gframe.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 gframe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}
B>>
package ja7;
import javax.swing.JFrame;
/**
*
* #author lalit kumar
*/
public class gframe extends javax.swing.JFrame {
/**
* Creates new form gframe
*/
public gframe() {
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() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("TRY MAGIC");
setResizable(false);
jButton1.setText("cal");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("fing grade ");
jButton2.setEnabled(false);
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jTextField1.setEditable(false);
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(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()
.addGap(49, 49, 49)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(67, 67, 67))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(73, 73, 73)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(143, Short.MAX_VALUE))
);
jButton2.setVisible(false);
jTextField1.setVisible(false );
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int a,b;
int c;
a=50;
b=56;
c=a+b;
jTextField2.setText(Integer.toString(c));
jButton2.setEnabled(true);
jButton2.setVisible(true );
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int c;
c=Integer.parseInt ( jTextField2.getText()) ;
jTextField1.setVisible(true );
if(c>50)
{
jTextField1.setText("A WARD");
}
else
jTextField1.setText(" B WARD");
}
/**
* #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(gframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(gframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(gframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(gframe.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 gframe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}
IN case A:when I click on CAL button(setvisible used in CALbutton) jTextfield1 become visible .
IN case B:when I click on CAL button(setvisible used in Fing grade)JTextfield1 become visible only if I resize the window.
Why does i need to resize the window in case B?
You just need to add revalidate(); like this:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int c;
c=Integer.parseInt ( jTextField2.getText()) ;
jTextField1.setVisible(true );
if(c>50)
{
jTextField1.setText("A WARD");
}
else
jTextField1.setText(" B WARD");
revalidate();
}
I have JTextField and JTextArea. I would like to get something like that:
TextField <- input String here. Then CLICK ENTER and this string should print in Text Area. Maybe it is bad thinking and I should use other components. I've just started with JFrame.
Here is TextField code:
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
String text = textField.getText();
textArea.setText(text);
}
It throws millions of errors. Should I add something like 'when keypressed' ?
I've changed it a little bit:
setText() replaced by append, and I made objects of TextField and TextArea.
package chatter;
import java.awt.Event;
import java.awt.TextArea;
import java.awt.TextField;
public class GUIFrame extends javax.swing.JFrame {
public GUIFrame() {
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() {
jButton2 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jScrollBar1 = new javax.swing.JScrollBar();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton2.setText("jButton1");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jTextField1.setText("jTextField1");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jButton1.setText("jButton1");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(179, 179, 179)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addGap(0, 193, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1)
.addComponent(jScrollPane1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE))
.addGap(167, 167, 167))
);
pack();
}// </editor-fold>
TextField textField = new TextField();
TextArea textArea = new TextArea();
;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
String text = textField.getText();
textArea.append(text);
}
/**
* #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(GUIFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUIFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUIFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUIFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUIFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JScrollBar jScrollBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
Now it doesn't throw errors, but still nothing shows in TextArea.
Change yourjTextField1ActionPerformed method to:
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
String text = jTextField1.getText();
jTextArea1.append(text);
}
with jTextField1 instead of textField and the same for the text area. You were referencing fields that you didn't use. You should remove them at the same time:
TextField textField = new TextField();
TextArea textArea = new TextArea();
The problem is that you have two TextField objects (textField and jTextField1) and two TextArea objects (textArea and jTextArea1). You added to your JFrame jTextField1 and jTextArea1, but your listener manipulates with textArea and textField which weren't added to the frame at all. To fix the problem change your method like this:
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
String text = jTextField1.getText();
jTextArea1.append(text);
}
Seems that textArea and textField can be removed.
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.