I am creating 4 threads and each thread is associated with a UI.
The UI performs a long running task, for that I have used a SwingWorker.
But the problem that arises is instead of running as a multithreaded app, it is running in queue.
Interesting to note that when I remove the SwingWorker it behaves and runs as multithreaded.
My code is as:
NewClass
package thread;
public class NewClass
{
public static void main(String[] args) throws Exception
{
for(int i=0; i<4 ; i++)
{
new ThreadFront().startsThread();
Thread.sleep(2000);
}
}
}
class ThreadFront implements Runnable
{
private Thread t;
public ThreadFront()
{
t = new Thread(this, "");
}
public void startsThread()
{
t.start();
}
#Override
public void run()
{
try
{
UI ui = new UI();
ui.startThread();
}
catch(Exception ae)
{
ae.printStackTrace();
}
}
}
UI class
package thread;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
public class UI extends javax.swing.JFrame
{
public UI()
{
initComponents();
setVisible(true);
}
public void startThread() throws Exception
{
new SwingWorker<Integer, Integer>()
{
#Override
protected Integer doInBackground() throws Exception
{
for(int i=0; i<10;i++)
{
jTextArea1.append(""+i);
Thread.sleep(3000);
}
return 0;
}
#Override
protected void process(List<Integer> chunks)
{
for(Integer message : chunks)
{
jProgressBar1.setValue(message);
jProgressBar1.repaint();
}
}
#Override
protected void done()
{
try
{
get();
}
catch(final Exception ex)
{
ex.printStackTrace();
}
}
}.execute();
}
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel2 = new javax.swing.JLabel();
jobid_field = new javax.swing.JLabel();
jProgressBar1 = new javax.swing.JProgressBar();
work_field = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
session_field = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel2.setBackground(new java.awt.Color(204, 204, 204));
jPanel2.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(255, 255, 255)));
jPanel2.setForeground(new java.awt.Color(204, 204, 204));
jLabel1.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N
jLabel1.setText("iZoneX Math Process");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 304, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(86, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);
jPanel3.setBackground(new java.awt.Color(204, 204, 204));
jPanel3.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(255, 255, 255)));
jTextArea1.setEditable(false);
jTextArea1.setBackground(new java.awt.Color(255, 255, 204));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 0, 0));
jTextArea1.setLineWrap(true);
jTextArea1.setRows(5);
jTextArea1.setWrapStyleWord(true);
jScrollPane1.setViewportView(jTextArea1);
jLabel2.setText("Job ID. :");
jLabel4.setText("Processing: ");
jLabel3.setText("Session ID: ");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jobid_field, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(session_field, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(work_field, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jobid_field, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addComponent(session_field, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(work_field, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel1.add(jPanel3, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
private void formWindowClosing(java.awt.event.WindowEvent evt) {
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JLabel jobid_field;
private javax.swing.JLabel session_field;
private javax.swing.JLabel work_field;
// End of variables declaration
}
What would be the alternative to worker Threads in Swing in that case?
Um, no, this is not how multithreading works in Swing.
There is a single UI thread (known as the Event Dispatching Thread), all updates and interactions with the UI are expected to be done from within the context of the EDT, so doing things like...
#Override
public void run()
{
try
{
UI ui = new UI();
ui.startThread();
}
catch(Exception ae)
{
ae.printStackTrace();
}
}
And...
#Override
protected Integer doInBackground() throws Exception
{
for(int i=0; i<10;i++)
{
jTextArea1.append(""+i);
Thread.sleep(3000);
}
return 0;
}
Are actually breaking this rule.
Instead, each UI should have its own SwingWorker (as it does now), but should be created from within the context of the EDT.
Each SwingWorker should be calling publish in order to push the results of the doInBackground method back to the EDT.
SwingWorker has its own progress support via the PropertyChange support
For example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MultiThreadedUI {
public static void main(String[] args) {
new MultiThreadedUI();
}
public MultiThreadedUI() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
final List<TestPane> panes = new ArrayList<>(5);
for (int index = 0; index < 5; index++) {
panes.add(new TestPane(Integer.toString(index)));
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1));
for (TestPane pane : panes) {
frame.add(pane);
}
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
for (TestPane pane : panes) {
pane.makeItSo();
}
}
});
}
});
}
public class TestPane extends JPanel {
private JTextArea textArea;
private JProgressBar pb;
private String name;
public TestPane(String name) {
this.name = name;
textArea = new JTextArea(10, 5);
pb = new JProgressBar();
setLayout(new BorderLayout());
add(new JScrollPane(textArea));
add(pb, BorderLayout.SOUTH);
}
public void makeItSo() {
BackgroundWorker worker = new BackgroundWorker();
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
pb.setValue((Integer)evt.getNewValue());
}
}
});
worker.execute();
}
protected class BackgroundWorker extends SwingWorker<Integer, Integer> {
#Override
protected void process(List<Integer> chunks) {
for (Integer value : chunks) {
textArea.append(name + ": " + value + "\n");
}
}
#Override
protected Integer doInBackground() throws Exception {
int delay = (int)(Math.random() * 3000);
for (int i = 0; i < 10; i++) {
publish(i);
setProgress((int) (Math.round(((double) i / (double) 9) * 100)));
Thread.sleep(delay);
}
return 0;
}
}
}
}
Related
I am currently having some problem in some javaFrame application. It is a simple game where the ball is running around and there is one button which starts and stops the ball. The problem is whenever i change the text of a label or a button while the ball is running the frame resets(the ball is resetting where it was in the first place) and i don't want that to happen. I created the frame and the panel by dragging from the side(i did not write code to create frame and panels). I don't know all the rules in this site and i don't know if it is permissible but i could not find any ways to show this to you so i linked 2 short youtube videos at the end so you can see what it is(i apologize for that).
What i did in frame:
Created 2 panels.
Added a button to panel1(upper one) and added ball image on top of it.
Added 2 buttons on panel2(lower one) which are Start/Stop and changeLabel.
My NewJFrame Class:
package view;
import controller.BallAction;
public class NewJFrame extends javax.swing.JFrame {
private BallAction ba;
private boolean isBallRolling = false;
private int labelAsciiValue = 65;
public NewJFrame() {
initComponents();
ba = new BallAction(ball);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
ball = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jButton2 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Ball Game");
ball.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/top.png"))); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(ball, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(515, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(ball, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(291, Short.MAX_VALUE))
);
jButton2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton2.setText("Start");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton1.setText("Change Label");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(85, 85, 85)
.addComponent(jButton1)
.addGap(107, 107, 107)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap(35, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
//Start-Stop Button
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
if(isBallRolling){
ba.stop();
jButton2.setText("Start");
isBallRolling = false;
}
else{
ba.start();
jButton2.setText("Stop");
isBallRolling = true;
}
}
//Change Label Button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel1.setText(String.valueOf((char)(labelAsciiValue++)));
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton ball;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
// End of variables declaration
}
My BallAction Class:
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.Timer;
public class BallAction {
private Timer time;
private final ClockListener clock = new ClockListener();
private JButton ball;
public BallAction(JButton ball){
this.ball=ball;
time = new Timer(20,clock);
}
public void start(){
time.start();
}
public void stop(){
time.stop();
}
//If ball.x <= panel.x go right else ball.x = 0.
public void update(){
if(ball.getLocation().x<=ball.getParent().getSize().width-100)
ball.setLocation(ball.getLocation().x+5,ball.getLocation().y);
else{
ball.setLocation(0,ball.getLocation().y);
}
}
private class ClockListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
update();
}
}
}
Frame without changing anything : https://www.youtube.com/watch?v=yC_8tyUmal0
Frame with changing the text : https://www.youtube.com/watch?v=zGvhCnRRTtw
EDIT:
If i create the frame on my own it works fine.
Why is that please help me thank you.
My Own Frame:
package ballgame0;
import controller.BallAction;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class BallGame0 {
private static boolean isBallRunning = false;
private static int labelAsciiValue = 65;
public static void main(String[] args) {
JFrame frame = new JFrame("New Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000,800);
frame.setVisible(true);
JPanel panel= new JPanel(null);
frame.add(panel);
JLabel changeLabel = new JLabel();
changeLabel.setSize(100,50);
changeLabel.setLocation(500,650);
changeLabel.setFont(new Font("Tahoma", 0, 36));
JButton buttonLabel = new JButton("Change Label");
buttonLabel.setSize(150,40);
buttonLabel.setLocation(300,650);
JButton button = new JButton("asd");
button.setSize(70,70);
JButton button1 = new JButton("Start");
button1.setSize(100,60);
button1.setLocation(100,650);
panel.add(changeLabel);
panel.add(buttonLabel);
panel.add(button);
panel.add(button1);
BallAction ba = new BallAction(button);
ActionListener alis = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
changeLabel.setText(String.valueOf((char)labelAsciiValue++));
}
};
buttonLabel.addActionListener(alis);
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(isBallRunning){
ba.stop();
button1.setText("Start");
isBallRunning = false;
}else{
ba.start();
button1.setText("Stop");
isBallRunning = true;
}
}
};
button1.addActionListener(al);
}
}
Actually my registerKeyBoardAction with following code not working after I pressed Alt key for first time and again if I press Alt key it works means that Alt key is acting as a lock and unlock states i.e while in lock state keyBoard action doesnot work and in unlock state it works:
package com.remittance;
import Util.DayBookDetails;
import Util.MultiLineTableCellRenderer;
import Util.ReportPrint;
import UtilClass.DayBookDataList;
import com.fa.converter.DateUtil;
import java.awt.Container;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.awt.print.PrinterException;
import java.io.File;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
/**
*
* #author Ashmin
*/
public class DayBook extends javax.swing.JInternalFrame {
/**
* Creates new form DayBook
*/
private Session session;
private Connection connect;
private ResultSet result;
private PreparedStatement statement;
static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(DayBook.class.getName());
private String className = "com.remittance.DayBook";
private ActionListener showForm;
private final MultiLineTableCellRenderer renderer;
public DayBook(Session session) {
initComponents();
Action actionView = new AbstractAction("View") {
#Override
public void actionPerformed(ActionEvent evt) {
}
};
buttonView.setAction(actionView);
actionView.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_V);
buttonView.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.CTRL_DOWN_MASK), buttonView);
buttonView.getActionMap().put(buttonView, actionView);
this.panel.setVisible(false);
showForm = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (panel.isVisible()) {
panel.setVisible(false);
} else {
panel.setVisible(true);
}
}
};
this.getRootPane().registerKeyboardAction(showForm, KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
this.getRootPane().registerKeyboardAction(showForm, KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), JComponent.WHEN_FOCUSED);
ActionListener actionRefresh = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Refreshed");
showDayBook();
}
};
buttonRefresh.getRootPane().registerKeyboardAction(actionRefresh, KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
buttonRefresh.getRootPane().registerKeyboardAction(actionRefresh, KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), JComponent.WHEN_FOCUSED);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
tableDayBook = new javax.swing.JTable();
labelDateAd = new javax.swing.JLabel();
panel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
inputTextFieldDateBsFrom = new javax.swing.JTextField();
inputTextFieldDateBsTo = new javax.swing.JTextField();
checkBoxRemark = new javax.swing.JCheckBox();
buttonView = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jScrollPane4 = new javax.swing.JScrollPane();
tableShortcut = new javax.swing.JTable();
buttonRefresh = new javax.swing.JButton();
panelTitle = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
labelPan = new javax.swing.JLabel();
labelLogo = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
labelContact = new javax.swing.JLabel();
labelCompanyName = new javax.swing.JLabel();
labelLocation = new javax.swing.JLabel();
labelDayBook = new javax.swing.JLabel();
labelDate = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setTitle("Day Book");
setPreferredSize(new java.awt.Dimension(1180, 560));
tableDayBook.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Date", "Particular", "Vouchar Type", "VNo", "Dr. Amount", "Cr. Amount"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tableDayBook.getTableHeader().setReorderingAllowed(false);
tableDayBook.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
tableDayBookKeyPressed(evt);
}
});
jScrollPane1.setViewportView(tableDayBook);
if (tableDayBook.getColumnModel().getColumnCount() > 0) {
tableDayBook.getColumnModel().getColumn(0).setResizable(false);
tableDayBook.getColumnModel().getColumn(1).setResizable(false);
tableDayBook.getColumnModel().getColumn(2).setResizable(false);
tableDayBook.getColumnModel().getColumn(3).setResizable(false);
tableDayBook.getColumnModel().getColumn(4).setResizable(false);
tableDayBook.getColumnModel().getColumn(5).setResizable(false);
}
labelDateAd.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labelDateAd.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 0, 0));
jLabel1.setText("*");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("Date (YYYY-MM-DD) In BS: From:");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setText("To:");
inputTextFieldDateBsFrom.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
inputTextFieldDateBsFromFocusLost(evt);
}
});
inputTextFieldDateBsFrom.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
inputTextFieldDateBsFromKeyPressed(evt);
}
});
inputTextFieldDateBsTo.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
inputTextFieldDateBsToFocusLost(evt);
}
});
inputTextFieldDateBsTo.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
inputTextFieldDateBsToKeyPressed(evt);
}
});
checkBoxRemark.setText("Remark");
checkBoxRemark.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
checkBoxRemarkKeyPressed(evt);
}
});
buttonView.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
buttonView.setText("View");
buttonView.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
buttonViewFocusGained(evt);
}
});
buttonView.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonViewActionPerformed(evt);
}
});
buttonView.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
buttonViewKeyPressed(evt);
}
});
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(inputTextFieldDateBsFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(inputTextFieldDateBsTo, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(checkBoxRemark)
.addGap(33, 33, 33)
.addComponent(buttonView)
.addContainerGap(330, Short.MAX_VALUE))
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout.createSequentialGroup()
.addGap(3, 3, 3)
.addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(inputTextFieldDateBsFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(inputTextFieldDateBsTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkBoxRemark)
.addComponent(buttonView))
.addGap(0, 2, Short.MAX_VALUE))
);
tableShortcut.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Shortcut Keys"
}
) {
Class[] types = new Class [] {
java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane4.setViewportView(tableShortcut);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane4)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 15, Short.MAX_VALUE))
);
buttonRefresh.setText("Refresh");
buttonRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonRefreshActionPerformed(evt);
}
});
buttonRefresh.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
buttonRefreshKeyPressed(evt);
}
});
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setText("Pan No:");
labelPan.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labelPan.setText("Pan");
labelLogo.setBackground(new java.awt.Color(0, 0, 0));
labelLogo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("Contact:");
labelContact.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labelContact.setText("PHone");
labelCompanyName.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
labelCompanyName.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labelCompanyName.setText("Company Name");
labelLocation.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labelLocation.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labelLocation.setText("Location");
labelDayBook.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
labelDayBook.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labelDayBook.setText("Day Book");
labelDate.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labelDate.setText("Date in AD: ");
javax.swing.GroupLayout panelTitleLayout = new javax.swing.GroupLayout(panelTitle);
panelTitle.setLayout(panelTitleLayout);
panelTitleLayout.setHorizontalGroup(
panelTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelTitleLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(panelTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(panelTitleLayout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(22, 22, 22)
.addComponent(labelPan))
.addComponent(labelLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panelTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelTitleLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panelTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelCompanyName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(panelTitleLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(labelContact))
.addComponent(labelLocation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(labelDayBook, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelTitleLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(labelDate)
.addGap(19, 19, 19))))
);
panelTitleLayout.setVerticalGroup(
panelTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelTitleLayout.createSequentialGroup()
.addGroup(panelTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(labelPan)
.addComponent(jLabel4)
.addComponent(labelContact))
.addGap(30, 30, 30)
.addGroup(panelTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelTitleLayout.createSequentialGroup()
.addComponent(labelCompanyName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(labelLocation)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelDayBook)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(labelDate))
.addComponent(labelLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))
);
jButton1.setText("Print");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(panelTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonRefresh)))
.addGap(0, 0, 0)
.addComponent(labelDateAd))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(123, 123, 123)
.addComponent(labelDateAd))
.addComponent(panelTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonRefresh)
.addComponent(jButton1))))
);
pack();
}// </editor-fold>
private void buttonViewActionPerformed(java.awt.event.ActionEvent evt) {
panel.setVisible(false);
}
private void inputTextFieldDateBsFromKeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
inputTextFieldDateBsTo.requestFocus();
}
}
private void inputTextFieldDateBsToKeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
buttonView.requestFocus();
}
}
private void checkBoxRemarkKeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
checkBoxRemark.setSelected(true);
}
}
private void tableDayBookKeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_F2) {
//panel.setVisible(true);
showForm.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null) {
//Nothing need go here, the actionPerformed method (with the
//above arguments) will trigger the respective listener
});
}
if (evt.getKeyCode() == KeyEvent.VK_ALT) {
evt.consume();
}
}
// Variables declaration - do not modify
private javax.swing.JButton buttonRefresh;
private javax.swing.JButton buttonView;
private javax.swing.JCheckBox checkBoxRemark;
private javax.swing.JTextField inputTextFieldDateBsFrom;
private javax.swing.JTextField inputTextFieldDateBsTo;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JLabel labelCompanyName;
private javax.swing.JLabel labelContact;
private javax.swing.JLabel labelDate;
private javax.swing.JLabel labelDateAd;
private javax.swing.JLabel labelDayBook;
private javax.swing.JLabel labelLocation;
private javax.swing.JLabel labelLogo;
private javax.swing.JLabel labelPan;
private javax.swing.JPanel panel;
private javax.swing.JPanel panelTitle;
private javax.swing.JTable tableDayBook;
private javax.swing.JTable tableShortcut;
// End of variables declaration
}
I have searched and found that if I consume the event on Alt key pressed then I will have problem fixed but I am unable to addKeyListener to JInternalFrame. Please! Help me and thanks in advance.
Hi friends I'm actually developing my own video player, using VLCJ libraries , I use a canvas over a JFrame and a options bar with buttons to play,stop etc..
in this moment the video player and all the buttons works, but
it is so slow and the fps are so low too, I think that using a canvas is not the best method to play videos , or maybe my code is not optimized .
Main class:
package vlcvideo;
import java.io.File;
import javax.swing.JFileChooser;
public class VlcVideo {
static JFileChooser filex = new JFileChooser();
public static void main(String[] args)
{
String rutaVlc = "C:/vlc64/vlc";
String rutaVideo="/src/vlcVideo/c.mp4";
File ourFile;
//seleccionar la ruta de instalacion del vlc
/*filex.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//selecciona solo directorios
filex.showSaveDialog(null);
ourFile=filex.getSelectedFile();
rutaVlc=ourFile.getAbsolutePath();*/
/*
filex.setFileSelectionMode(JFileChooser.FILES_ONLY);
filex.showSaveDialog(null);
ourFile=filex.getSelectedFile();
rutaVideo=ourFile.getAbsolutePath();*/
System.out.println(rutaVlc + "ruta DLL");
System.out.println(rutaVideo + " ruta video");
//new MediaPlayer(rutaVlc,rutaVideo).run();
//MediaPlayer mediaPlayer = new MediaPlayer(rutaVlc,rutaVideo);
prueba pb = new prueba(rutaVlc,rutaVideo);
// reproductor rp = new reproductor(rutaVlc,rutaVideo);
// rp.setVisible(true);
}
}
Frame class:
package vlcvideo;
import com.sun.jna.NativeLibrary;
/*import com.xuggle.xuggler.IContainer;
import com.xuggle.xuggler.ICodec;
import com.xuggle.xuggler.IStream;
import com.xuggle.xuggler.IStreamCoder;*/
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
public class prueba extends javax.swing.JFrame
{
private static final int SKIP_TIME_MS = 10 * 1000;
private boolean mousePressedPlaying = false;
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension tm = tk.getScreenSize();
private final String vlc;
Canvas c;
private final String video;
EmbeddedMediaPlayer mediaPlayer;
public prueba(String vlc,String video)
{
this.video=video;
this.vlc=vlc;
initComponents();
initMyComponentes();
createCanvas();
createMedia();
printTime();
}
public void printTime()
{
/*while(true)
{
final long time = mediaPlayer.getTime();
final int position = (int)(mediaPlayer.getPosition() * 1000.0f);
final int chapter = mediaPlayer.getChapter();
final int chapterCount = mediaPlayer.getChapterCount();
int posicionSlider=positionSlider.getValue();
if(mediaPlayer.isPlaying())
{
updateTime(time);
updatePosition(position);
updateChapter(chapter, chapterCount);
}
} */
timeThread tt = new timeThread(this,mediaPlayer);
tt.start();
}
public void createCanvas()
{
c = new Canvas();
c.setBackground(Color.black);
int panelHeight = panelVideo.getHeight();
int panelWidth = panelVideo.getWidth();
System.out.println(panelHeight + " " +panelWidth);
c.setBounds(0, 0,panelWidth, panelHeight);
panelVideo.add(c);
}
public void initMyComponentes()
{
positionSlider.setMinimum(0);
positionSlider.setMaximum(1000);
positionSlider.setValue(0);
positionSlider.setToolTipText("Position");
volumeSlider.setOrientation(JSlider.HORIZONTAL);
volumeSlider.setToolTipText("Change volume");
System.out.println(tm.height + " * "+tm.width);
}
/* public void duracion()
{
IContainer container = IContainer.make();
int result = container.open(video, IContainer.Type.READ, null);
if(result<0)
throw new RuntimeException("Failed to open media file");
long duration = container.getDuration();
System.out.println("Duration (ms): " + duration);
}*/
public void createMedia()
{
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(),vlc);
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(c));
mediaPlayer.toggleFullScreen();
mediaPlayer.setEnableMouseInputHandling(false);
mediaPlayer.setEnableKeyInputHandling(true);
mediaPlayer.prepareMedia(video);
mediaPlayer.play();
this.setVisible(true);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
panelVideo = new javax.swing.JPanel();
btnMute = new javax.swing.JButton();
btnPlay = new javax.swing.JButton();
btnPause = new javax.swing.JButton();
btnStop = new javax.swing.JButton();
positionSlider = new javax.swing.JSlider();
lblTime = new javax.swing.JLabel();
chapterLabel = new javax.swing.JLabel();
volumeSlider = new javax.swing.JSlider();
btnRewind = new javax.swing.JButton();
btnRewind2 = new javax.swing.JButton();
lblTotal = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel2.setBackground(new java.awt.Color(255, 51, 51));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout panelVideoLayout = new javax.swing.GroupLayout(panelVideo);
panelVideo.setLayout(panelVideoLayout);
panelVideoLayout.setHorizontalGroup(
panelVideoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
panelVideoLayout.setVerticalGroup(
panelVideoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 256, Short.MAX_VALUE)
);
btnMute.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fotos/mute.jpg"))); // NOI18N
btnMute.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnMuteActionPerformed(evt);
}
});
btnPlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fotos/Play.png"))); // NOI18N
btnPlay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPlayActionPerformed(evt);
}
});
btnPause.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fotos/Pause.jpg"))); // NOI18N
btnPause.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPauseActionPerformed(evt);
}
});
btnStop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fotos/stop.jpg"))); // NOI18N
btnStop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnStopActionPerformed(evt);
}
});
positionSlider.setMinorTickSpacing(10);
positionSlider.setPaintTicks(true);
positionSlider.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
positionSliderMousePressed(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
positionSliderMouseReleased(evt);
}
});
lblTime.setText("0");
chapterLabel.setText("00/00");
volumeSlider.setMinorTickSpacing(10);
volumeSlider.setPaintLabels(true);
volumeSlider.setPaintTicks(true);
volumeSlider.setToolTipText("");
volumeSlider.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
volumeSliderStateChanged(evt);
}
});
btnRewind.setText("<<");
btnRewind.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRewindActionPerformed(evt);
}
});
btnRewind2.setText(">>");
btnRewind2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRewind2ActionPerformed(evt);
}
});
lblTotal.setText("/0t");
jLabel1.setText("Volumen");
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(178, 178, 178)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(panelVideo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(btnPlay, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnPause, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnStop, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(61, 61, 61)
.addComponent(positionSlider, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(91, 91, 91))
.addGroup(layout.createSequentialGroup()
.addGap(171, 171, 171)
.addComponent(lblTime)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblTotal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 152, Short.MAX_VALUE)
.addComponent(btnRewind)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(chapterLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(37, 37, 37)
.addComponent(btnMute, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(19, 19, 19))
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(btnRewind2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 109, Short.MAX_VALUE)
.addComponent(volumeSlider, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(panelVideo, 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)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(positionSlider, 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(lblTime)
.addComponent(lblTotal)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(chapterLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnRewind)
.addComponent(btnRewind2)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(btnMute, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(volumeSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnPause, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnPlay)
.addComponent(btnStop, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(19, 19, 19))))
);
pack();
}// </editor-fold>
private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {
mediaPlayer.play();
}
private void btnPauseActionPerformed(java.awt.event.ActionEvent evt) {
mediaPlayer.pause();
}
private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {
mediaPlayer.stop();
}
private void btnMuteActionPerformed(java.awt.event.ActionEvent evt) {
mediaPlayer.mute();
}
private void positionSliderMousePressed(java.awt.event.MouseEvent evt) {
if(mediaPlayer.isPlaying()) {
mousePressedPlaying = true;
mediaPlayer.pause();
}
else
{
mousePressedPlaying = false;
}
setSliderBasedPosition();
}
private void positionSliderMouseReleased(java.awt.event.MouseEvent evt) {
setSliderBasedPosition();
updateUIState();
}
private void volumeSliderStateChanged(javax.swing.event.ChangeEvent evt) {
JSlider source = (JSlider)evt.getSource();
// if(!source.getValueIsAdjusting()) {
mediaPlayer.setVolume(source.getValue());
// }
}
private void btnRewindActionPerformed(java.awt.event.ActionEvent evt) {
skip(-SKIP_TIME_MS);
}
private void btnRewind2ActionPerformed(java.awt.event.ActionEvent evt) {
skip(SKIP_TIME_MS);
}
public void setSliderBasedPosition()
{
if(!mediaPlayer.isSeekable()) {
return;
}
float positionValue = positionSlider.getValue() / 1000.0f;
// Avoid end of file freeze-up
if(positionValue > 0.99f) {
positionValue = 0.99f;
}
mediaPlayer.setPosition(positionValue);
}
private void updateUIState()
{
if(!mediaPlayer.isPlaying()) {
// Resume play or play a few frames then pause to show current position in video
mediaPlayer.play();
if(!mousePressedPlaying) {
try {
// Half a second probably gets an iframe
Thread.sleep(500);
}
catch(InterruptedException e) {
// Don't care if unblocked early
}
mediaPlayer.pause();
}
}
long time = mediaPlayer.getTime();
int position = (int)(mediaPlayer.getPosition() * 1000.0f);
int chapter = mediaPlayer.getChapter();
int chapterCount = mediaPlayer.getChapterCount();
updateTime(time);
updatePosition(position);
updateChapter(chapter, chapterCount);
}
public void skip(int skipTime)
{
// Only skip time if can handle time setting
if(mediaPlayer.getLength() > 0) {
mediaPlayer.skip(skipTime);
updateUIState();
}
}
public void updateTime(long millis)
{
String s = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
lblTime.setText(s);
}
public void updatePosition(int value)
{
// positionProgressBar.setValue(value);
positionSlider.setValue(value);
}
public void updateChapter(int chapter, int chapterCount) {
String s = chapterCount != -1 ? (chapter + 1) + "/" + chapterCount : "-";
chapterLabel.setText(s);
chapterLabel.invalidate();
validate();
}
public void updateVolume(int value) {
volumeSlider.setValue(value);
}
// Variables declaration - do not modify
private javax.swing.JButton btnMute;
private javax.swing.JButton btnPause;
private javax.swing.JButton btnPlay;
private javax.swing.JButton btnRewind;
private javax.swing.JButton btnRewind2;
private javax.swing.JButton btnStop;
private javax.swing.JLabel chapterLabel;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JLabel lblTime;
private javax.swing.JLabel lblTotal;
private javax.swing.JPanel panelVideo;
public javax.swing.JSlider positionSlider;
private javax.swing.JSlider volumeSlider;
// End of variables declaration
}
The Thread used for print the time:
package vlcvideo;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
public class timeThread extends Thread
{
prueba pb;
EmbeddedMediaPlayer mediaPlayer;
public timeThread(prueba pb,EmbeddedMediaPlayer mediaPlayer)
{
this.pb=pb;
this.mediaPlayer=mediaPlayer;
}
public void run()
{
while(true)
{
final long time = mediaPlayer.getTime();
final int position = (int)(mediaPlayer.getPosition() * 1000.0f);
final int chapter = mediaPlayer.getChapter();
final int chapterCount = mediaPlayer.getChapterCount();
int posicionSlider=pb.positionSlider.getValue();
if(mediaPlayer.isPlaying())
{
pb.updateTime(time);
pb.updatePosition(position);
pb.updateChapter(chapter, chapterCount);
}
}
}
}
libraries used:
-jna 3.4.0.jar
-vlcj 2.1.0.jar
jdk:1.8
You have a tight loop in your thread that will consume just about all of your CPU.
Rather than polling inside a tight loop you should use media player events to get the information you want.
Or at worst you should sleep in that loop.
I am trying to make an app for communicating between different running instances of a thread. I have a jFrame that has a jTextField and a jButton. In the jTextField I type the number of threads that I want to run and after I press the jButton the threads run. Each thread contains a jFrame with a jButton. So if I type 3 in the jTextField and then press OK, three different jFrames pop out that have an own jButton. If I press the jButton in one of the jFrames of the threads, the jButton is set to disabled (setEnabled(false)). This should happen to each jButton of the jFrames from within the threads when pressed but the one from the last jFrame that is still not pressed.
This is the window class for the thread:
public class Window extends JFrame implements Runnable {
JFrame jr;
JButton bt;
public void run() {
jr=new JFrame();
bt=new jButton();
bt.setTitle("Press Me");
jr.setLayout(new FlowLayout());
jr.add(bt);
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
bt.setEnabled(false);
}
});
jr.setVisible(true);
}
}
Now this is how I run multiple instances of this thread. i is the number of the thread instances that is taken from the jTextField:
( int i=Integer.parseInt(jTextField1.gettext()) )
for (int a=0;a<i;a++) {
Runnable thr=new Window(a);
executor.execute(thr);
}
This is what I want to do: After I press the jButton on every jFrame that is within the thread instances and it is set to setEnabled(false) I get to the last jFrame that is popped up whose jButton is still unpressed. When I press this last JButton I want that all the JButtons on every jFrame to be set back to setEnabled(true). How can I do that?
This is the main class it works 100 % now!
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* #author oliver
*/
public class Hauptklasse extends javax.swing.JFrame {
static int i = 0;
static Random r;
static boolean OkApasat=false;
static int c;
public static Fereastra[] thread;
public Hauptklasse() throws IOException {
initComponents();
Image logo;
logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
jLabel4.setIcon(new ImageIcon(logo));
jLabel4.setVisible(true);
setLocation(200,100);
jPanel1.setBackground(Color.cyan);
jTextField1.setEditable(false);
jButton2.setEnabled(false);
r=new Random();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton1.setText("Pornire");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Numar maxim de ferestre");
jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2))
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setEditable(true);
jButton1.setEnabled(false);
jButton2.setEnabled(true);
jTextArea1.append("\n Welcome! :)");
jTextArea1.append("\n The following app tests the communication between threads");
jTextArea1.append("\n Please enter maximum number of windows to be opened");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
OkApasat=true;
}
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
final Hauptklasse main1 = new Hauptklasse();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
main1.setVisible(true);
}
});
while (true){
if (OkApasat==true){
if (Integer.parseInt(jTextField1.getText())>=3){
i= (Integer.parseInt(jTextField1.getText()));
main1.jTextArea1.append("\n"+i+" windows opened");
Fereastra[] thr=new Fereastra[i];
for (c = 0; c < i; c++) {
thr[c]=new Fereastra(thr);
thr[c].run();
}
OkApasat=false;
main1.jButton2.setEnabled(false);
main1.jTextField1.setEditable(false);
}
else jTextArea1.append("\n Wrong maximum number of windows-must be at least 3");
OkApasat=false;
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration
}
THIS IS THE WINDOW CLASS, WORKS 100 %:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* #author oliver
*/
public class Fereastra extends JFrame implements Runnable {
public JFrame jr;
public JButton bt;
public JLabel l;
public JLabel l2;
public Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
this.thread = thread;
jr = new JFrame();
jr.setSize(250, 250);
jr.setLayout(new FlowLayout());
bt = new JButton();
jr.add(bt);
bt.setText("OK");
bt.setBackground(Color.cyan);
l2 = new JLabel();
l2.setText("Buton activ");
jr.add(l2);
jr.setVisible(true);
}
public void run() {
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.setEnabled(false);
deblocat = true;
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null && thread[c].bt.isEnabled()) {
deblocat = false;
break;
}
}
if (deblocat == true) {
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null) {
thread[c].bt.setEnabled(true);
}
}
}
}
});
}
}
My classes:
1) The Window class (Fereastra means window, deblocat means unlocked, buton activ means Button is enabled)
package concurenta;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* #author oliver
*/
public class Fereastra extends JFrame implements Runnable {
public static JFrame jr;
public static JButton bt;
public static JLabel l;
public static JLabel l2;
public static Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
this.thread = thread;
jr = new JFrame();
jr.setSize(250, 250);
jr.setLayout(new FlowLayout());
bt = new JButton();
jr.add(bt);
bt.setText("OK");
bt.setBackground(Color.cyan);
l2 = new JLabel();
l2.setText("Buton activ");
jr.add(l2);
jr.setVisible(true);
}
public void run() {
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.setEnabled(false);
deblocat = true;
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null && thread[c].bt.isEnabled()) {
deblocat = false;
break;
}
}
if (deblocat == true) {
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null) {
thread[c].bt.setEnabled(true);
}
}
}
}
});
}
}
2) The Main Class(a.k.a Hauptklasse, okApasat means ok is pressed):
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package concurenta;
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* #author oliver
*/
public class Hauptklasse extends javax.swing.JFrame {
static int i = 0;
static Random r;
static boolean OkApasat=false;
static int c;
public static Fereastra[] thread;
public Hauptklasse() throws IOException {
initComponents();
Image logo;
logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
jLabel4.setIcon(new ImageIcon(logo));
jLabel4.setVisible(true);
setLocation(200,100);
jPanel1.setBackground(Color.cyan);
jTextField1.setEditable(false);
jButton2.setEnabled(false);
r=new Random();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton1.setText("Pornire");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Numar maxim de ferestre");
jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2))
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setEditable(true);
jButton1.setEnabled(false);
jButton2.setEnabled(true);
jTextArea1.append("\n Welcome! :)");
jTextArea1.append("\n The following app tests the communication between threads");
jTextArea1.append("\n Please enter maximum number of windows to be opened");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
OkApasat=true;
}
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
final Hauptklasse main1 = new Hauptklasse();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
main1.setVisible(true);
}
});
while (true){
if (OkApasat==true){
if (Integer.parseInt(jTextField1.getText())>=3){
i= (int) (Math.random() * (Integer.parseInt(jTextField1.getText()) - 3)) + 3;
main1.jTextArea1.append("\n"+i+" windows opened");
Fereastra[] thr=new Fereastra[i];
for (c = 0; c < i; c++) {
thr[c]=new Fereastra(thr);
thr[c].run();
}
OkApasat=false;
main1.jButton2.setEnabled(false);
main1.jTextField1.setEditable(false);
}
else jTextArea1.append("\n Wrong maximum number of windows-must be at least 3");
OkApasat=false;
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration
}
I want to display string in textbox of vpsfame class below my code, but I am unable to dispaly it. Can you give me suggestion this string in new8 class show in code and serial class gives me string from gps continue. It also displays it at run time via System.out.println, but does not display it through the textbox of vpsfame class
package vpspro;
import javax.comm.*;
import java.util.*;
import java.io.*;
public class Serial
{
public void com() throws UnsupportedCommOperationException, IOException, TooManyListenersException
{
int c=1;
String wantedPortName="COM6";
Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portId = null;
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);
}
port.setSerialPortParams(
4800,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
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;
}
String pt=null;
while(true)
{
String st = is.readLine();
System.out.print("(" + c + ")");
c++;
new8 obj1 = new new8();
obj1.decode(st);
System.out.println(st);
st = st.replace(st, "");
}
if (is != null) is.close();
/*if (os != null) os.close();*/
if (port != null) port.close();
}
}
this code for start communication with serial class
package vpspro;
import java.io.IOException;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.UnsupportedCommOperationException;
public class getcon extends javax.swing.JFrame {
public getcon() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
sc = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
br = new javax.swing.JComboBox();
help = new javax.swing.JButton();
ok = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("select comport");
sc.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM10", "COM11", "COM12" }));
sc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
scActionPerformed(evt);
}
});
sc.addInputMethodListener(new java.awt.event.InputMethodListener() {
public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
}
public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
scInputMethodTextChanged(evt);
}
});
jLabel2.setText("select buad rate");
br.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "4800", "1900", "150000" }));
br.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
brActionPerformed(evt);
}
});
help.setText("help");
ok.setText("ok");
ok.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okActionPerformed(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, false)
.addGroup(layout.createSequentialGroup()
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(sc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(105, 105, 105))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(171, Short.MAX_VALUE)
.addComponent(ok)
.addGap(28, 28, 28)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(help)
.addComponent(br, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(80, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(57, 57, 57)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(br, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(57, 57, 57)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(help)
.addComponent(ok))
.addContainerGap(118, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void brActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==br)
br.addItem("4800");
br.addItem("9600");
}
private void scActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==sc)
sc.addItem("COM6");
sc.addItem("COM7");
}
private void scInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==sc)
sc.addItem("COM6");
sc.addItem("COM7");
}
private void okActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==ok)
{
try {
new Serial().com();
} catch (UnsupportedCommOperationException ex) {
Logger.getLogger(getcon.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getcon.class.getName()).log(Level.SEVERE, null, ex);
} catch (TooManyListenersException ex) {
Logger.getLogger(getcon.class.getName()).log(Level.SEVERE, null, ex);
}
new new8();
}
}
public void getcom() {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new getcon().setVisible(true);
}
});
}
private javax.swing.JComboBox br;
private javax.swing.JButton help;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
public javax.swing.JButton ok;
private javax.swing.JComboBox sc;
}
this code decoding my gps string and dispaly and hear problem created i can not dispaly below string in textbox when i rum program textbox are empty.
package vpa.io.*;
import vpspro.vpsfame;
public class new8
{
static String[] a2;
static String a1[];
static String c;
public static String[] t;
public void decode(String st)
{
if(st.isEmpty())
{
System.out.println("System has proble");
vpsfame obj=new vpsfame();
obj.ab.setText("ok");
}
else
{
a1=st.split("\\$",0);
a2=a1[1].split("\\*",0);
checksum();
if(a2[1].equalsIgnoreCase(c))
{
t=st.split(",",0);
switch (t[0].charAt(0))
{
case '$':
String s=t[0].substring(3,6);
String s3="RMC";
if (s.compareTo(s3)==0)
{
System.out.println(" NMEA 0183 Details.....");
System.out.println("System identity: "+t[0].substring(1,3));
System.out.println("NMEA Formate: "+t[0].substring(3,6));
System.out.println("(UTC)Time: "+t[1].substring(1,2));
new vpsfame().ac.setText(t[1].substring(1,2));
System.out.println("Lattitude: "+t[3]);
System.out.println("Direction of Lattitude: "+t[4]);
new vpsfame().ab.setText(t[3].concat(t[4]));
System.out.println("Longitude: "+t[5]);
System.out.println("Direction of Longitude: "+t[6]);
new vpsfame().bc.setText(t[5].concat(t[6]));
System.out.println("Speed over Ground: "+t[7]);
new vpsfame().cd.setText(t[7]);
/*System.out.println("Track mode: "+t[8]);
System.out.println(st.isEmpty());
System.out.println("DATE: "+t[9]);
System.out.println("adjustment declination "+t[10]);
System.out.println("Direction of Magnetic variation: "+t[11].charAt(0));*/
}
}
else
System.out.println(" Invalid Formate...");
break;
default:
System.out.println(" Invalid DATA....");
}
}
else
System.out.println(" no match checksum");
}
}
public static void checksum()
{
int l=a2[0].length();
char[] a=a2[0].toCharArray();
int b=0;
for(int i=0;i<l;i++)
{
b=b^a[i];
}
c=Integer.toHexString(b);
}
}
and this is my main class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* vpsfame.java
*
* Created on Jan 26, 2013, 11:02:32 PM
*/
package vpspro;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Image;
import java.awt.TextField;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.UnsupportedCommOperationException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
/**
*
* #author DHARMA
*/
public class vpsfame extends javax.swing.JFrame {
public vpsfame()
{
initComponents();
}
/** Creates new form vpsfame */
/** 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() {
jComboBox1 = new javax.swing.JComboBox();
ab = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
bc = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
ac = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
cd = new javax.swing.JTextField();
jPanel1 = new javax.swing.JPanel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
gc = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
lm = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();
jMenuItem5 = new javax.swing.JMenuItem();
jMenuItem6 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem7 = new javax.swing.JMenuItem();
jMenuItem8 = new javax.swing.JMenuItem();
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
ab.setEditable(false);
ab.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
abActionPerformed(evt);
}
});
jLabel1.setText("latitude");
jLabel2.setText("longitude");
bc.setText(" ");
bc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bcActionPerformed(evt);
}
});
jLabel4.setText("UTC");
ac.setText(" ");
ac.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
acActionPerformed(evt);
}
});
jLabel5.setText("Speed of vessel");
cd.setText(" ");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 621, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 368, Short.MAX_VALUE)
);
jMenu1.setText("File");
gc.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
gc.setIcon(new javax.swing.ImageIcon("C:\\Users\\DHARMA\\Desktop\\png\\20x20\\55.png")); // NOI18N
gc.setText("get connection");
gc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
gcActionPerformed(evt);
}
});
jMenu1.add(gc);
jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem2.setText("track");
jMenu1.add(jMenuItem2);
lm.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.ALT_MASK));
lm.setText("load map");
lm.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lmActionPerformed(evt);
}
});
jMenu1.add(lm);
jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem4.setText("data save");
jMenu1.add(jMenuItem4);
jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.META_MASK));
jMenuItem5.setText("set time zone");
jMenu1.add(jMenuItem5);
jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem6.setText("quit");
jMenu1.add(jMenuItem6);
jMenuBar1.add(jMenu1);
jMenu2.setText("view");
jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK));
jMenuItem7.setText("saved data");
jMenu2.add(jMenuItem7);
jMenuItem8.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.ALT_MASK));
jMenuItem8.setText("about us");
jMenu2.add(jMenuItem8);
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()
.addGap(52, 52, 52)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(19, 19, 19))
.addGroup(layout.createSequentialGroup()
.addComponent(cd, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35))
.addComponent(ab, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
.addComponent(jLabel3)
.addComponent(ac, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
.addComponent(jLabel4)
.addComponent(bc, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ab, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(43, 43, 43)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addGap(16, 16, 16)
.addComponent(bc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(ac, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(45, 45, 45)
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addComponent(cd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
pack();
}// </editor-fold>
private void gcActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource()==gc)
{
getcon obj3=new getcon();
obj3.setVisible(true);
}
}
private void lmActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void abActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void acActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void bcActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) throws UnsupportedCommOperationException, IOException, TooManyListenersException {
/*public vpsfame()
{
initComponents();*/
new new8();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
/*URL url=getClass().getResource("C:\\Users\\DHARMA\\Documents\\NetBeansProjects\\vpspro\\src");*/
vpsfame obj4=new vpsfame();
new vpsfame().setBackground(Color.yellow);
obj4.setSize(1000,
500);
ImageIcon image1=new ImageIcon("C:\\Users\\DHARMA\\Documents\\NetBeansProjects\\vpspro\\src");
System.out.println("jjdfhj");
obj4.setIconImage(image1.getImage());
obj4.setTitle("VPS");
obj4.setVisible(true);
new new8();
}
});
}
/*public vpsfame()
{
fm=new JFrame("VPS");
fm.setSize(1000, 1000);
fm.setVisible(true);
fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}*/
// Variables declaration - do not modify
public static javax.swing.JTextField ab;
public javax.swing.JTextField ac;
public static javax.swing.JTextField bc;
public javax.swing.JTextField cd;
private javax.swing.JMenuItem gc;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JMenuItem jMenuItem7;
private javax.swing.JMenuItem jMenuItem8;
private javax.swing.JPanel jPanel1;
private javax.swing.JMenuItem lm;
// End of variables declaration
}
I would seriously advise you to take a time out, and refactor all of your code. Igonoring that in the class new8, in method decode replace this code:
new vpsfame().ac.setText(t[1].substring(1,2));
System.out.println("Lattitude: "+t[3]);
System.out.println("Direction of Lattitude: "+t[4]);
new vpsfame().ab.setText(t[3].concat(t[4]));
System.out.println("Longitude: "+t[5]);
System.out.println("Direction of Longitude: "+t[6]);
new vpsfame().bc.setText(t[5].concat(t[6]));
System.out.println("Speed over Ground: "+t[7]);
new vpsfame().cd.setText(t[7]);
With this:
//use one object, dont just create new frames
vpsfame myFrame = new vpsfame();
myFrame.ac.setText(t[1].substring(1,2));
System.out.println("Lattitude: "+t[3]);
System.out.println("Direction of Lattitude: "+t[4]);
myFrame.ab.setText(t[3].concat(t[4]));
System.out.println("Longitude: "+t[5]);
System.out.println("Direction of Longitude: "+t[6]);
myFrame.bc.setText(t[5].concat(t[6]));
System.out.println("Speed over Ground: "+t[7]);
myFrame.cd.setText(t[7]);
//Also set the frame to visible, so it can be displayed once you've done all this work.
myFrame.setVisible(true);
The problem is that:
Firstly, you are creating multiple vpsframe objects where you should only have one. It makes no sense to create 5 frames where each will have 4 empty fields. Create one object and initialise all it's fields rather than using 5 diffrent objects.
You are not tracking the objects you are creating, the garbage collector will just get rid of the, so create one object, assign it to a variable and use that.
Set the vpsfame object to visible, otherwise you will never see it.
Your code also needs refactoring, you should be using the camelCase naming convention, and classes should always begin with Capital letters.