Progressbar not starting with Timer in Java - java

I have a problem. My splash program isn't running. please excuse me as I am new and cant put the code properly.i Think my Timer code is wrong. Any help will be appreciated. My connection to the database is working perfectly fine.
My splash code
package Splash_package;
import DataConnection.connection;
import Mainframe.main_frame;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.Timer;
/**
*
* #author Aaqib Jan
*/
public class Splash extends javax.swing.JFrame {
/**
* Creates new form splash
*/
public Splash() {
initComponents();
}
connection cn=new connection();
Timer tm = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
count+=5;
if(count==10)
{
jLabel2.setText("Initializing");
jProgressBar1.setStringPainted(true);
jProgressBar1.setValue(10);
}
if (count == 20) {
try {
Class.forName(cn.classname);
jLabel2.setText("Loading ...");
jProgressBar1.setValue(20);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 30) {
try {
cn.con = DriverManager.getConnection(cn.url);
jLabel2.setText("Checking database ...");
jProgressBar1.setValue(30);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 40) {
try {
cn.st = cn.con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
jLabel2.setText("Finding resources ...");
jProgressBar1.setValue(40);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 50) {
try {
cn.rs = cn.st.executeQuery("select * from usertable");
jLabel2.setText("Checking Errors ...");
jProgressBar1.setValue(50);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 60) {
try {
cn.rs = cn.st.executeQuery("select * from labourinfo");
jLabel2.setText("No Error Getting ...");
jProgressBar1.setValue(60);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 70) {
try {
cn.rs = cn.st.executeQuery("select * from salarygrade");
jLabel2.setText("Checking Modules ...");
jProgressBar1.setValue(70);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 80) {
try {
cn.rs = cn.st.executeQuery("select * from labourattendence");
jLabel2.setText("Almost Finish ...");
jProgressBar1.setValue(80);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
System.exit(0);
}
}
if (count == 90) {
try {
cn.rs = cn.st.executeQuery("select * from labourattendence");
jLabel2.setText("Starting ...");
jProgressBar1.setValue(90);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getStackTrace());
}
}
if(count==95){
jProgressBar1.setValue(100);
}
if (count == 100) {
main_frame main = new main_frame();
main.show();
dispose();
}
}
});
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jProgressBar1 = new javax.swing.JProgressBar();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("jLabel1");
jLabel2.setText("jLabel2");
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(207, 207, 207)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(89, 89, 89)
.addComponent(jLabel1)))
.addContainerGap(307, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(217, 217, 217))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(57, 57, 57)
.addComponent(jLabel2)
.addGap(37, 37, 37)
.addComponent(jLabel1)
.addGap(59, 59, 59)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(230, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void formWindowOpened(java.awt.event.WindowEvent evt) {
this.setLocationRelativeTo(null);
this.setBackground(new Color(0, 255, 0, 0));
tm.start();
}
/**
* #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(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Splash().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JProgressBar jProgressBar1;
// End of variables declaration
int count=0;
}
My Main class
import Splash_package.Splash;
/*
* 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 Main_Class {
public static void main(String[] args) {
new Splash().setVisible(true);
}
}

The following method is never called and this causes the timer to never start:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
this.setLocationRelativeTo(null);
this.setBackground(new Color(0, 255, 0, 0));
tm.start();
}
Move tm.start() as follow:
public Splash() {
initComponents();
tm.start();
}

Related

class Canvas doesn't open from a JFrame class

This is the JFrame class. When I click the button the Canvas class doesn't open and I don't know why.
I use the NetBeans auto compiler.
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package giochino;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
/**
*
* #author spriz
*/
public class Giochinoo extends JFrame implements KeyListener {
public Giochinoo() throws IOException {
initComponents();
A();
jTextField1.setText("inserisci "+random);
}
String random;
public final void A(){
random = "";
String characters = "aBcDeFgHiJkLmNoPqRsTuVwXyZ1234567890";
Random rnd = new Random();
int lunghezza = rnd.nextInt(7);
char[] text = new char[lunghezza];
for (int i = 0; i < lunghezza; i++) {
text[i] = characters.charAt(rnd.nextInt(characters.length()));
}
for (int i = 0; i < text.length; i++) {
random += text[i];
}
jTextField1.setText("inserisci "+random);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N
jButton1.setText("Gioca");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextField1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N
jTextField1.setToolTipText("");
jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextField1FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextField1FocusLost(evt);
}
});
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N
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(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(197, 197, 197))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(102, 102, 102)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(115, 115, 115)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(107, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(67, 67, 67)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(57, 57, 57)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(115, 115, 115))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
new Mossa().setVisible(true);
if (jTextField1.getText().equals(random)) {
A();
jLabel1.setText("bravo!");
}else{
// Mossa mossa = new Mossa();
// mossa.setVisible(true);
// try {
// Thread.sleep(2000);
// } catch (InterruptedException ex) {
// Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
// }
// try {
// String url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
// java.awt.Desktop myNewBrowserDesktop = java.awt.Desktop.getDesktop ();
// java.net.URI myNewLocation = new java.net.URI (url);
// myNewBrowserDesktop.browse (myNewLocation);
// } catch (URISyntaxException ex) {
// Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
// } catch (IOException ex) {
// Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {
if (jTextField1.getText().equals("inserisci "+random)) {
jTextField1.setText("");
}
}
private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {
// if (jTextField1.getText().equals("")) {
// jTextField1.setText(random);
// }
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
//<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(Giochinoo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Giochinoo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Giochinoo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Giochinoo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new Giochinoo().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify
public javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
#Override
public void keyTyped(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
#Override
public void keyPressed(KeyEvent e) {
// int keycode = e.getKeyCode();
//
// if (keycode == KeyEvent.VK_ENTER) {
//
// if (jTextField1.getText().equals(random)) {
// A();
// }else{
// try {
// String url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
// java.awt.Desktop myNewBrowserDesktop = java.awt.Desktop.getDesktop ();
// java.net.URI myNewLocation = new java.net.URI (url);
// myNewBrowserDesktop.browse (myNewLocation);
// } catch (URISyntaxException ex) {
// Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
// } catch (IOException ex) {
// Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
// }
// }
// }
}
#Override
public void keyReleased(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
}
This is the Canvas class and if I change Canvas to JFrame I get an error on the finestra.add(mossa); line
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package giochino;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* #author spriz
*/
public class Mossa extends JPanel /*javax.swing.JFrame Canvas*/ implements Runnable{
BufferedImage mossaImg = null;
boolean attivo = false;
public Mossa(){
caricaRisorse();
}
public static void main(String[] args) {
Mossa mossa = new Mossa();
JFrame finestra = new JFrame();
Dimension dimensione = new Dimension(400,582);
finestra.setPreferredSize(dimensione);
finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
finestra.add(mossa);
finestra.pack();
finestra.setVisible(true);
Thread thread = new Thread(mossa);
thread.start();
}
private void caricaRisorse(){
CaricaImmagini loader = new CaricaImmagini();
mossaImg = loader.caricaImg("/Immagini/mossa.png");
}
private void disegna(){
Graphics g = this.getGraphics();
g.drawImage(mossaImg, 0, 0, 400,582,this);
g.dispose();
}
#Override
public void run() {
attivo = true;
while (attivo) {
disegna();
}
}
}
I tried to make the Canvas a JFrame and I saw that it opened but doesn't load the image.

JavaFX app crashing or freezing when button clicked for downloading and showing the progress in a jprogressbar

I am writing a java app using netbeans IDE and using the gui creator, I created a simple project and some buttons for downloading a jar from a website, but, when I click on the button app freezes/crashes and doesn't allow me to click any buttons or anything else and when I maximize the app then minimize the window turn into black thing.
Here is the code generated by gui creator :
/*
* 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 mcsm;
/**
*
* #author YReza
*/
import mcsm.download;
public class MCSM1 extends javax.swing.JFrame {
/**
* Creates new form MCSM1
*/
public MCSM1() {
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();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jProgressBar1 = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("MCSM");
setBackground(new java.awt.Color(0, 0, 0));
setForeground(java.awt.Color.white);
jButton1.setText("Run...");
jButton1.setToolTipText("Run Your Server");
jButton1.setFocusPainted(false);
jButton2.setText("Create...");
jButton2.setToolTipText("Create The Server Using Th Downoaded Jar");
jButton2.setFocusPainted(false);
jButton3.setText("Configuration..");
jButton3.setToolTipText("Configure The Server");
jButton3.setFocusPainted(false);
jButton4.setText("Download");
jButton4.setToolTipText("Download The Jar From Official WebSite");
jButton4.setBorderPainted(false);
jButton4.setFocusPainted(false);
jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton4MouseClicked(evt);
}
});
jProgressBar1.setToolTipText("The Progress Of Your Task");
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(122, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3))
.addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(125, 125, 125))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(130, Short.MAX_VALUE)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))
.addGap(153, 153, 153))
);
pack();
}// </editor-fold>
private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {
download task = new download();
task.Task();
}
/**
* #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(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MCSM1.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 MCSM1().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JButton jButton1;
public javax.swing.JButton jButton2;
public javax.swing.JButton jButton3;
public javax.swing.JButton jButton4;
public javax.swing.JProgressBar jProgressBar1;
// End of variables declaration
}
And it is my Download class (I used This method for showing the progress on jprogressbar) :
package mcsm;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
public class download extends javax.swing.JFrame {
public void Task() {
MCSM1 jp = new MCSM1();
JProgressBar jp1 = jp.jProgressBar1;
try {
URL url = new URL("https://cdn.getbukkit.org/spigot/spigot-1.16.5.jar");
try {
HttpURLConnection httpConnection = (HttpURLConnection)(url.openConnection());
long completeFileSize = httpConnection.getContentLength();
java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
try {
byte[] data = new byte[1024];
long downloadedFileSize = 0;
int x = 0;
while ((x = in .read(data, 0, 1024)) >= 0) {
downloadedFileSize += x;
final int currentProgress = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 100000d);
// update progress bar
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
jp1.setValue(currentProgress);
}
});
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
} catch (IOException ioe2) {
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
}
try {
java.io.FileOutputStream fos = new java.io.FileOutputStream("Spigot.jar");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
}
// calculate progress
}
}
If you want to run it you should have these in lib folder :

Handling several events in one JButton

I have a homework with Celsius to Fahrenheit converter, which asks such things:
User should insert the Celsius value, click the “Convert” button and get the Fahrenheit value;
User should insert the Fahrenheit value, click the “Convert” button and get the Celsius value;
After showing the result for the temperature conversion, if the button “Convert” is clicked-on again, all input-output text-fields in the GUI should be cleared.
However, I have struggled in implementing several actions in one button. Where is my mistake (the code of events in jButton1ActionPerformed)?
There is a code in Java, I use Netbeans 8.1: as follows
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TConverter extends javax.swing.JFrame {
/**
* Creates new form TConverter
*/
public TConverter() {
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();
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);
jLabel1.setText("Celcius");
jLabel2.setText("Fahrenheit");
jButton1.setText("Convert");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Reset");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel1)))
.addGap(39, 39, 39))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(47, 47, 47)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField1)
.addComponent(jTextField2))
.addContainerGap(177, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(72, 72, 72)
.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))
.addGap(27, 27, 27)
.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))
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap(90, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText("");
jTextField2.setText("");
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
float CelciusInput = Float.parseFloat(jTextField1.getText());
float FahrenheitInput = Float.parseFloat(jTextField1.getText());
if (!(jTextField1.getText().isEmpty()))
{
try
{
jTextField2.setText(String.valueOf((CelciusInput * 1.8) + 32));
}
catch (Exception ex)
{
}
}
else if (!(jTextField2.getText().isEmpty()))
{
try
{
jTextField1.setText(String.valueOf((FahrenheitInput - 32) * 5 / 9));
}
catch (Exception ex)
{
}
}
else if (String.valueOf(jTextField2.getText()).equals(String.valueOf(jTextField1.getText())))
{
jTextField1.setText("");
jTextField2.setText("");
}
else
{
JOptionPane.showMessageDialog(null, "Wrong type of input",
"Error dialog message", JOptionPane.ERROR_MESSAGE);
}
}
/**
* #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(TConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TConverter.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 TConverter().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration }
Try the below code and see if it suits you :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
float CelciusInput;
float FahrenheitInput;
if (!(jTextField1.getText().isEmpty())) {
if (jTextField2.getText().isEmpty()) {
try {
CelciusInput = Float.parseFloat(jTextField1.getText());
jTextField2.setText(String.valueOf((CelciusInput * 1.8) + 32));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Wrong type of input",
"Error dialog message", JOptionPane.ERROR_MESSAGE);
jTextField1.setText("");
jTextField2.setText("");
return;
}
} else {
jTextField1.setText("");
jTextField2.setText("");
}
} else if (!(jTextField2.getText().isEmpty())) {
try {
FahrenheitInput = Float.parseFloat(jTextField2.getText());
jTextField1.setText(String.valueOf((FahrenheitInput - 32) * 5 / 9));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Wrong type of input",
"Error dialog message", JOptionPane.ERROR_MESSAGE);
jTextField1.setText("");
jTextField2.setText("");
}
}
}
you already found out how to handle events. to performe different actions according to input, you have to check these condidtions (as you already do)...
it would be really helpful to put these into seperate methods
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (isCelsionSet() && !isFarenheitSet() )
{
convertCelsiusToFarenheit();
}
else if(!isCelsionSet() && !isFarenheitSet()){
notifyEmptyFields();
}
else if(!isCelsionSet() && isFarenheitSet()){
convertFarenheitToCelsius();
}
else if(isCelsionSet() && isFarenheitSet()){
clearInput();
}
}
now you can test and verify each method seperate
private boolean isCelsionSet(){
//FIXME rename jTextField1 into celsiusInput
try{
Float.parseFloat(jTextField1.getText());
return true; //field is indeed properly set
}catch(NumberFormatException e){
return false; //field is not properly set
}
}
private void convertFahrenheitToCelsius(){
//FIXME rename jTextField2 into farenheitInput
float celsius = getTempInCelsius();
jTextField2.setText(String.valueOf((celsius * 1.8) + 32));
}
if you follow up this road you will easily find your mistake and creat code that is readable and maintainable.
I'm sorry that i don't read all your code, its (hopefully soon no more) messy, right now...
Note for Testing
once you have made the code changes you can easily create a test:
#Test
public void testIsCelsiusEmpty(){
TConverter tconverter = new TConverter();
tconverter.celsiusInput.setText("12.3"); //after renaming jTextField1 into celsiusInput
Assert.assertTrue(tconverter.isCelsionSet());
}

Components are maximizing but not moving to TOP

I'm making one jInternalFrame where I'am adding tabs dynamically.
now adding a new TAB I have coded,
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ui;
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JTabbedPane;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.plaf.basic.BasicInternalFrameUI;
/**
*
* #author santoshg
*/
public class jTAB extends javax.swing.JFrame {
/**
* Creates new form jTAB
*/
JTabbedPane tabList = new JTabbedPane();
int nUserCount = 1;
boolean isDrag = true;
private static int pressedX = 0, pressedY = 0;
JDesktopPane sDesktoppane = new JDesktopPane();
JComponent northPane;
public jTAB() {
this.setUndecorated(true);
initComponents();
drag();
jInternalFrame1.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("maximum")) {
if (jInternalFrame1.isMaximum()) {
try { // Maximizing TAB window with the size of Screen.
jInternalFrame1.setMaximum(true);
Toolkit tk = getToolkit();
jInternalFrame1.setSize((int) getToolkit().getScreenSize().getWidth(), (int) getToolkit().getScreenSize().getHeight());
setLocation(0, 0);
isDrag = false;
} catch (Exception e) {
e.printStackTrace();
}
} else {
try { // Setting it to it's actual size.
jInternalFrame1.setMaximum(false);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
isDrag = true;
setLocation(pressedX, pressedY);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
public final void drag() {
setContentPane(sDesktoppane);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
jInternalFrame1.addInternalFrameListener(new InternalFrameListener() {
#Override
public void internalFrameOpened(InternalFrameEvent e) {
}
#Override
public void internalFrameClosing(InternalFrameEvent e) {
}
#Override
public void internalFrameClosed(InternalFrameEvent e) {
}
#Override
public void internalFrameIconified(InternalFrameEvent e) {
jInternalFrame1.setIconifiable(true);
}
#Override
public void internalFrameDeiconified(InternalFrameEvent e) {
}
#Override
public void internalFrameActivated(InternalFrameEvent e) {
}
#Override
public void internalFrameDeactivated(InternalFrameEvent e) {
}
});
jInternalFrame1.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("maximum")) {
if (jInternalFrame1.isMaximum()) {
try { // Maximizing TAB window with the size of Screen.
jInternalFrame1.setMaximum(true);
Toolkit tk = getToolkit();
jInternalFrame1.setSize((int) getToolkit().getScreenSize().getWidth(), (int) getToolkit().getScreenSize().getHeight());
`enter code here` setLocation(0, 0);
isDrag = false;
} catch (Exception e) {
e.printStackTrace();
}
} else {
try { // Setting it to it's actual size.
jInternalFrame1.setMaximum(false);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
isDrag = true;
setLocation(pressedX, pressedY);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
if (northPane == null) {
northPane = ((BasicInternalFrameUI) jInternalFrame1.getUI()).getNorthPane();
northPane.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
if (isDrag) {
System.out.println("pressedX and pressedY " + pressedX + " " + pressedY);
pressedX = e.getX();
pressedY = e.getY();
}
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
northPane.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
if (isDrag) {
int draggedObjX = getLocation().x + e.getX() - pressedX;
int draggedObjY = getLocation().y + e.getY() - pressedY;
setLocation(draggedObjX, draggedObjY);
getjInternalFrame().setLocation(0, 0);
}
}
public void mouseMoved(MouseEvent e) {
}
});
}
sDesktoppane.add(jInternalFrame1);
jInternalFrame1.setVisible(true);
jInternalFrame1.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
setSize(jInternalFrame1.getSize().width, jInternalFrame1.getSize().height);
}
});
setSize(jInternalFrame1.getSize());
if (northPane == null) {
setLocation(new Point(pressedX, pressedY));
}
super.setVisible(true);
}
public JInternalFrame getjInternalFrame() {
return jInternalFrame1;
}
public JComponent getNorthPane() {
return northPane;
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jInternalFrame1 = new javax.swing.JInternalFrame();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jInternalFrame1.setMaximizable(true);
jInternalFrame1.setVisible(true);
jButton1.setText("Add TAB");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup()
.addGap(0, 512, Short.MAX_VALUE)
.addComponent(jButton1))
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 301, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1, javax.swing.GroupLayout.Alignment.TRAILING)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
tabList.addTab("User " + nUserCount, new ChatWindow("user " + nUserCount).getFrameComponent());
JComponent jif = (JComponent) jInternalFrame1.getContentPane();
jif.setLayout(new BorderLayout());
jif.add(tabList);
nUserCount++;
}//GEN-LAST:event_jButton1ActionPerformed
/**
* #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(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(jTAB.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 jTAB().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JInternalFrame jInternalFrame1;
// End of variables declaration//GEN-END:variables
}
Where ChatWindow,java is
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ui;
import javax.swing.JComponent;
/**
*
* #author santoshg
*/
public class ChatWindow extends javax.swing.JFrame {
/**
* Creates new form ChatWindow
*/
public ChatWindow() {
initComponents();
}
public ChatWindow(String userName) {
initComponents();
lblUserName.setText(userName);
}
public JComponent getFrameComponent(){
return jPanel1;
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblUserName = new javax.swing.JLabel();
lblAvatar = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
lblUserDept = new javax.swing.JLabel();
lblContactInfo = new javax.swing.JLabel();
lblSendFile = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblUserName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblUserName.setText("UserName");
lblUserName.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
lblAvatar.setText("Avatar");
lblAvatar.setAlignmentX(0.5F);
lblAvatar.setAlignmentY(0.2F);
lblAvatar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
lblAvatar.setIconTextGap(2);
lblAvatar.setPreferredSize(new java.awt.Dimension(35, 15));
jTextArea1.setEditable(false);
jTextArea1.setBackground(new java.awt.Color(249, 251, 252));
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jTextArea2.setColumns(20);
jTextArea2.setRows(2);
jTextArea2.setMinimumSize(new java.awt.Dimension(3, 22));
jScrollPane2.setViewportView(jTextArea2);
lblUserDept.setText("Department");
lblContactInfo.setToolTipText("User Info");
lblSendFile.setToolTipText("Send File");
jLabel1.setToolTipText("View History");
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(6, 6, 6)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(lblAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lblUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE)
.addComponent(lblUserDept, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 355, Short.MAX_VALUE)
.addComponent(lblContactInfo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblSendFile)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addContainerGap())))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblContactInfo)
.addComponent(lblSendFile))
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblUserDept))
.addComponent(lblAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.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.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* #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(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChatWindow.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 ChatWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JLabel lblAvatar;
private javax.swing.JLabel lblContactInfo;
private javax.swing.JLabel lblSendFile;
private javax.swing.JLabel lblUserDept;
private javax.swing.JLabel lblUserName;
// End of variables declaration//GEN-END:variables
}
Hit the add button twice you'll get 2 TABS not when I maximize it "Add TAB" moved to Middle and Textareas are in top.
I want jTextAtrea1 to expand till the bottom of the page during maximize and restore to actual size during toggle.
I want jTextAtrea1 to expand till the bottom of the page during maximize
Sounds like you should be using a BorderLayout for the panel you add to the tab. Then you add the text area to the BorderLayout.CENTER and the other components to the BorderLayout.NORTH.
It looks like your layout code is generated by an IDE. Don't use the IDE to generate layout code. Do the layout yourself and you will be in full control.

why textbox is not auto update in java?

below my code i code wright for gps is give me coninue data on 4800 baud rate this data display continue by "System.out.println(st)" but same data not dispaly in a.setText(st) where a is Textbox variable. some know how to my textbox update like System.out.println line.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.UnsupportedCommOperationException;
import javax.comm.*;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* test.java
*
* Created on Mar 11, 2013, 9:08:52 AM
*/
/**
*
* #author DJ ROCKS
*/
public class test extends javax.swing.JFrame {
public boolean bp=true;
/** Creates new form test */
public test() {
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() {
ok = new javax.swing.JButton();
a = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
ok.setText("ok");
ok.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okActionPerformed(evt);
}
});
a.setText(" ");
a.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, 394, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(238, 238, 238)
.addComponent(ok)))
.addContainerGap(124, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(67, 67, 67)
.addComponent(ok)
.addContainerGap(160, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void okActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==ok)
{
CommPortIdentifier portId = null;
String wantedPortName="COM16";
Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
while(portIdentifiers.hasMoreElements())
{
CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();
if(pid.getPortType() == CommPortIdentifier.PORT_SERIAL &&
pid.getName().equals(wantedPortName))
{
portId = pid;
break;
}
}
if(portId == null)
{
System.err.println("Could not find serial port " + wantedPortName);
System.exit(1);
}
else
{
System.out.println("system find gps reciever");
}
SerialPort port = null;
try {
port = (SerialPort) portId.open(
"RMC",
1);
System.out.println("all are ok");
} catch(PortInUseException e) {
System.err.println("Port already in use: " + e);
System.exit(1);
}
try {
//int i=Integer.parseInt(new vps().baud_rate.getItemAt(new vps().baud_rate.getItemCount()));
port.setSerialPortParams(
4800,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader is = null;
try {
is = new BufferedReader(new InputStreamReader(port.getInputStream()));
System.out.println("data is ok");
} catch (IOException e) {
System.err.println("Can't open input stream: write-only");
is = null;
}
//this is variable is ouside of class and define by public it work
while(true)
{
String st = null;
try {
st = is.readLine();
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(st);
//st = st.replace(st, "");
a.setText(st);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
System.out.printf(ie.getMessage());
}
}
/*if (is != null) try {
is.close();
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
if (port != null) port.close();
*/
}
}
private void aActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField a;
private javax.swing.JButton ok;
// End of variables declaration
}
It seems as though you may be trying to rewrite the same String. I would try to call a "get" method that returns a String instead of referring to the variable "st". I do this to avoid a situations in which the program will try to rewrite the String since Strings are immutable.
I would try something like this:
private String getString()
{
try {
String st = new String(""+is.ReadLine());
return st;
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
Use this to refer to the new String from BufferedReader "is":
a.setText(getString());
Also, it looks as if you have a code block within comment lines here:
/*if (is != null) try {
is.close();
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
if (port != null) port.close();
}*/
Please correct me if I'm wrong here.

Categories