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.
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);
}
}
If I click a row(JTABLE), it must display the specific values back to the textfields/combobox/radiobutton/spinner. But in my case, it's just hard to retrieve the values back to the RADIO BUTTON and SPINNER.
package coffeeshop;
import java.awt.HeadlessException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
public class coffeeframe extends javax.swing.JFrame {
public coffeeframe() {
initComponents();
ArrayList coffeeArray = new ArrayList();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
buttonGroup1 = new javax.swing.ButtonGroup();
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
btnAdd = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
name = new javax.swing.JTextField();
coffeeType = new javax.swing.JComboBox<>();
jLabel3 = new javax.swing.JLabel();
coffeeName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
coffeePrice = new javax.swing.JTextField();
quanOrder = new javax.swing.JSpinner();
jLabel5 = new javax.swing.JLabel();
dinein = new javax.swing.JRadioButton();
togo = new javax.swing.JRadioButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jButton1.setText("jButton1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 51));
table.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
table.setForeground(new java.awt.Color(204, 0, 51));
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Customer", "Coffee Type", "Coffee Name", "Price", "Order Mode", "Quantity", "Total"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
table.setGridColor(new java.awt.Color(0, 102, 102));
table.getTableHeader().setReorderingAllowed(false);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(table);
btnAdd.setBackground(new java.awt.Color(204, 255, 204));
btnAdd.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
btnAdd.setForeground(new java.awt.Color(102, 102, 102));
btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/Add-icon (1).png"))); // NOI18N
btnAdd.setText("ADD ORDER");
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
jPanel1.setBackground(java.awt.Color.gray);
jPanel1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel1.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Customer");
name.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
name.setForeground(new java.awt.Color(51, 51, 51));
name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nameActionPerformed(evt);
}
});
coffeeType.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
coffeeType.setForeground(new java.awt.Color(102, 102, 102));
coffeeType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Choose", "Esprezo $20", "Green Tea Frappe $75", "Barako $22", "Black Coffee $28" }));
coffeeType.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
coffeeTypeItemStateChanged(evt);
}
});
coffeeType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
coffeeTypeActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Coffee name");
coffeeName.setEditable(false);
coffeeName.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
coffeeName.setForeground(new java.awt.Color(102, 102, 102));
coffeeName.setText(" ");
coffeeName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
coffeeNameActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Coffee Type");
jLabel4.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Coffee price");
coffeePrice.setEditable(false);
coffeePrice.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
coffeePrice.setForeground(new java.awt.Color(102, 102, 102));
coffeePrice.setText(" ");
quanOrder.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
quanOrder.setModel(new javax.swing.SpinnerNumberModel(1, 1, 100, 1));
jLabel5.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Quantity");
buttonGroup1.add(dinein);
dinein.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
dinein.setForeground(new java.awt.Color(255, 255, 255));
dinein.setSelected(true);
dinein.setText("Dine-In");
dinein.setBorder(null);
dinein.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dineinActionPerformed(evt);
}
});
buttonGroup1.add(togo);
togo.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
togo.setForeground(new java.awt.Color(255, 255, 255));
togo.setText("To-Go");
togo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
togoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(coffeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(name)
.addComponent(coffeeType, 0, 163, Short.MAX_VALUE))
.addGap(112, 112, 112))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(85, 85, 85)
.addComponent(dinein, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(togo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5)))
.addGap(10, 10, 10)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(coffeePrice, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(quanOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(25, 25, 25))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(coffeeType, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(coffeePrice, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(coffeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jLabel4)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(togo, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(dinein, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(quanOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jButton2.setBackground(new java.awt.Color(255, 204, 204));
jButton2.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jButton2.setForeground(new java.awt.Color(102, 102, 102));
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/edit-icon.png"))); // NOI18N
jButton2.setText("EDIT ORDER");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(255, 51, 51));
jButton3.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jButton3.setForeground(new java.awt.Color(239, 234, 234));
jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/trash-icon.png"))); // NOI18N
jButton3.setText(" ");
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 201, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, 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.TRAILING)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
.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(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
try{
int total = Integer.parseInt(coffeePrice.getText()) * (Integer)quanOrder.getValue();
DefaultTableModel model = (DefaultTableModel)table.getModel();
Coffee coffee = new Coffee(name.getText(),coffeeType.getSelectedItem().toString(),coffeeName.getText(),Integer.parseInt(coffeePrice.getText()),buttonGroup1.getSelection().getActionCommand(),(Integer)quanOrder.getValue(),total);
coffeeArray.add(coffee);
if(name.getText().trim().isEmpty()){
JOptionPane.showMessageDialog(null,"Complete the order details!");
}else if(buttonGroup1.getSelection().getActionCommand()== null){
JOptionPane.showMessageDialog(null,"Complete the order details!");
}else{
String customerName = name.getText();
String cofType = coffeeType.getSelectedItem().toString();
String cofName = coffeeName.getText();
int price = Integer.parseInt(coffeePrice.getText());
String OrderMode= buttonGroup1.getSelection().getActionCommand();
int quantity = (Integer)quanOrder.getValue();
Object[] rowCoffee = {customerName,cofType,cofName,price,OrderMode,quantity,total};
model.addRow(rowCoffee);
}
}catch(NumberFormatException | HeadlessException e){
JOptionPane.showMessageDialog(null,"Complete the order details!");
}
}
private void coffeeTypeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String str_coffee_name = (String)coffeeType.getSelectedItem();
String input_coffee_name = str_coffee_name.replaceAll("[^a-zA-Z]","");
coffeeName.setText(input_coffee_name);
String str_coffee_price = (String)coffeeType.getSelectedItem();
String input_coffee_price = str_coffee_price.replaceAll("[^0-9]","");
coffeePrice.setText(input_coffee_price);
}
private void coffeeNameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void togoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
togo.setActionCommand("TO-GO");
}
private void dineinActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
dinein.setActionCommand("DINE-IN");
}
private void nameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void coffeeTypeItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)table.getModel();
int i = table.getSelectedRow();
int total = Integer.parseInt(coffeePrice.getText()) * (Integer)quanOrder.getValue();
if(i >= 0)
{
model.setValueAt(name.getText(), i, 0);
model.setValueAt(coffeeType.getSelectedItem(), i, 1);
model.setValueAt(coffeeName.getText(), i, 2);
model.setValueAt(Integer.parseInt(coffeePrice.getText()), i, 3);
model.setValueAt(buttonGroup1.getSelection().getActionCommand(), i, 4);
model.setValueAt((Integer)quanOrder.getValue(), i, 5);
model.setValueAt(total, i, 6);
}
else{
System.out.println("Update Error");
}
}
private void tableMouseClicked(java.awt.event.MouseEvent evt) {
try{
DefaultTableModel model = (DefaultTableModel)table.getModel();
int row = table.getSelectedRow();
name.setText(model.getValueAt(row, 0).toString());
coffeeType.setSelectedItem(table.getValueAt(row, 1).toString());
coffeeName.setText(model.getValueAt(row, 2).toString());
coffeePrice.setText(model.getValueAt(row, 3).toString());
quanOrder.setValue(model.getValueAt(row, 5).toString());
}catch(Exception e){
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(coffeeframe.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 coffeeframe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnAdd;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JTextField coffeeName;
private javax.swing.JTextField coffeePrice;
private javax.swing.JComboBox<String> coffeeType;
private javax.swing.JRadioButton dinein;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
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.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField name;
private javax.swing.JSpinner quanOrder;
private javax.swing.JTable table;
private javax.swing.JRadioButton togo;
// End of variables declaration
ArrayList<Coffee> coffeeArray = new ArrayList<>();
int length = 0;
}
How to change the values of spinner and radio button
The spinner should be easily settable by calling its setValue(...) method, and passing in the number from the selected table row item.
For the JRadioButtons, probably the easiest solution is to use a Map that maps the selection to its radio button, and then using this map to get a reference to the proper JRadioButton, and calling setSelected(true) on it.
For an example, and for an example of a Minimal, Complete, and Verifiable example, please have a look at:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.EnumMap;
import java.util.Map;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class CoffeeMcve extends JPanel {
private CoffeeTableModel tableModel = new CoffeeTableModel();
private JTable table = new JTable(tableModel);
private Map<OrderMode, ButtonModel> modeButtonMap = new EnumMap<>(OrderMode.class);
private JSpinner quantSpinner = new JSpinner(new SpinnerNumberModel(1, 0, 20, 1));
private JTextField nameTField = new JTextField(10);
private ButtonGroup modeBtnGroup = new ButtonGroup();
public CoffeeMcve() {
JPanel modePanel = new JPanel();
modePanel.setBorder(BorderFactory.createTitledBorder("Order Mode"));
for (OrderMode mode : OrderMode.values()) {
JRadioButton rBtn = new JRadioButton(mode.getText());
rBtn.setActionCommand(mode.toString());
modeBtnGroup.add(rBtn);
modePanel.add(rBtn);
modeButtonMap.put(mode, rBtn.getModel());
}
JPanel orderPanel = new JPanel();
orderPanel.add(new JLabel("Name:"));
orderPanel.add(nameTField);
orderPanel.add(new JLabel("Quantity:"));
orderPanel.add(quantSpinner);
orderPanel.add(modePanel);
orderPanel.add(new JButton(new AddAction("Add", KeyEvent.VK_A)));
table.getColumnModel().getColumn(2).setCellRenderer(new OrderModeColumnRenderer());
JScrollPane scrollPane = new JScrollPane(table);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(orderPanel, BorderLayout.PAGE_END);
table.getSelectionModel().addListSelectionListener(new MyTableListener());
}
public void setOrderData(CoffeeOrder2 order) {
nameTField.setText(order.getName());
quantSpinner.setValue(order.getQuant());
ButtonModel btnModel = modeButtonMap.get(order.getOrderMode());
modeBtnGroup.setSelected(btnModel, true);
}
private class MyTableListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
int index = table.getSelectedRow();
CoffeeOrder2 order = tableModel.getRow(index);
setOrderData(order);
}
}
}
private class OrderModeColumnRenderer extends DefaultTableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null && value instanceof OrderMode) {
value = ((OrderMode) value).getText();
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
private class AddAction extends AbstractAction {
public AddAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
String name = nameTField.getText();
int quant = (int) quantSpinner.getValue();
ButtonModel model = modeBtnGroup.getSelection();
if (model != null) {
String actionCommand = model.getActionCommand();
OrderMode orderMode = OrderMode.valueOf(actionCommand);
CoffeeOrder2 coffeeOrder2 = new CoffeeOrder2(name, quant, orderMode);
tableModel.addRow(coffeeOrder2);
}
}
}
private static void createAndShowGui() {
CoffeeMcve mainPanel = new CoffeeMcve();
JFrame frame = new JFrame("CoffeeMcve");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class CoffeeTableModel extends DefaultTableModel {
public static final String[] TITLES = {"Name", "Quantity", "Order Mode"};
public CoffeeTableModel() {
super(TITLES, 0);
}
public void addRow(CoffeeOrder2 coffee2) {
Vector<Object> rowData = new Vector<>();
rowData.add(coffee2.getName());
rowData.add(coffee2.getQuant());
rowData.add(coffee2.getOrderMode());
super.addRow(rowData);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Object value = getValueAt(0, columnIndex);
if (value == null) {
return super.getColumnClass(columnIndex);
} else {
return value.getClass();
}
}
public CoffeeOrder2 getRow(int rowIndex) {
if (rowIndex < 0 || rowIndex >= getRowCount()) {
String text = "For rowIndex: " + rowIndex;
throw new IllegalArgumentException(text);
}
String name = getValueAt(rowIndex, 0).toString();
int quant = (int) getValueAt(rowIndex, 1);
OrderMode orderMode = (OrderMode) getValueAt(rowIndex, 2);
return new CoffeeOrder2(name, quant, orderMode);
}
}
class CoffeeOrder2 {
private String name;
private int quant;
private OrderMode orderMode;
public CoffeeOrder2(String name, int quant, OrderMode orderMode) {
this.name = name;
this.quant = quant;
this.orderMode = orderMode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuant() {
return quant;
}
public void setQuant(int quant) {
this.quant = quant;
}
public OrderMode getOrderMode() {
return orderMode;
}
public void setOrderMode(OrderMode orderMode) {
this.orderMode = orderMode;
}
}
enum OrderMode {
HERE("Here"), TO_GO("To Go");
private String text;
private OrderMode(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
This is what the textfield looks like before clicking the check button:
This is what happens after clicking check. This only happens with a string that is longer than the textfield.
This is the code from netbeans:
package filevalidator;
import java.awt.Color;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
/**
*
* #author Kosar
*/
public class Validator extends javax.swing.JFrame {
static String path1 = null;
static String path2 = null;
/**
* Creates new form Validator
*/
public Validator() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
file1path = new javax.swing.JTextField();
select1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
file2path = new javax.swing.JTextField();
select2 = new javax.swing.JButton();
hash1 = new javax.swing.JLabel();
hash2 = new javax.swing.JLabel();
result = new javax.swing.JLabel();
checkBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jLabel1.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jLabel1.setText("Original File:");
file1path.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
file1path.setAutoscrolls(false);
select1.setText("Select");
select1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
select1ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jLabel2.setText("Second File:");
file2path.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
file2path.setAutoscrolls(false);
file2path.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
select2.setText("Select");
select2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
select2ActionPerformed(evt);
}
});
hash1.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
hash1.setForeground(java.awt.Color.blue);
hash1.setText(" ");
hash2.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
hash2.setForeground(java.awt.Color.blue);
hash2.setText(" ");
result.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
result.setText(" ");
checkBtn.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
checkBtn.setText("Check");
checkBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkBtnActionPerformed(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()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(32, 32, 32)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(result, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(151, 151, 151)
.addComponent(hash2, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE))
.addComponent(hash1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(30, 30, 30))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(file1path, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(file2path))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(select1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select2, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(checkBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(331, 331, 331))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(59, 59, 59)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(file1path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select1))
.addGap(27, 27, 27)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(file2path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(hash1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hash2)
.addGap(13, 13, 13)
.addComponent(result)
.addGap(5, 5, 5)
.addComponent(checkBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jPanel1, 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();
setLocationRelativeTo(null);
}// </editor-fold>
private void select1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select file");
if (chooser.showOpenDialog(select1) == JFileChooser.APPROVE_OPTION) {
path1 = chooser.getSelectedFile().getAbsolutePath();
}
file1path.setText(path1);
file1path.setBackground(Color.white);
}
private void select2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select file");
if (chooser.showOpenDialog(select2) == JFileChooser.APPROVE_OPTION) {
path2 = chooser.getSelectedFile().getAbsolutePath();
}
file2path.setText(path2);
file2path.setBackground(Color.white);
}
private void checkBtnActionPerformed(java.awt.event.ActionEvent evt) {
try {
HashMD5 hasher = new HashMD5();
try {
hash1.setText(hasher.hash(path1));
hash2.setText(hasher.hash(path2));
} catch (NoSuchAlgorithmException | IOException ex) {
}
if ( hash1.getText().equals(hash2.getText())) {
result.setForeground(Color.GREEN);
result.setText("Hashes are the same. File has not been modified.");
}
else {
result.setForeground(Color.RED);
result.setText("Hashes are not the same. File has been modified.");
}
} catch (NullPointerException e) {
if (file1path.getText() == null) {
file1path.setBackground(Color.red);
}
else if (file2path.getText() == null) {
file2path.setBackground(Color.red);
}
else {
file1path.setBackground(Color.red);
file2path.setBackground(Color.red);
}
}
}
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JButton checkBtn;
private javax.swing.JTextField file1path;
private javax.swing.JTextField file2path;
private javax.swing.JLabel hash1;
private javax.swing.JLabel hash2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel result;
private javax.swing.JButton select1;
private javax.swing.JButton select2;
// End of variables declaration
}
You can handle it by using TextField and its method to set columns i.e. "setColumns(int numOfCols)"
import java.awt.FlowLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class TextFieldExample extends JFrame {
JFrame frame = new JFrame();
public TextFieldExample()
{
frame = new JFrame("Test");
Container container = frame.getContentPane();
JTextField fld1 = new JTextField("Java C++ C");
JTextField fld2 = new JTextField("");
JTextField fld3 = new JTextField("");
fld1.setColumns(5); //Now, it will not be resized.
fld2.setColumns(7); //Now, it will not be resized.
fld3.setColumns(9); //Now, it will not be resized.
container.setLayout(new FlowLayout());
container.add(fld1);
container.add(fld2);
container.add(fld3);
frame.setVisible(true);
frame.setSize(150,150);
}
public static void main(String[] args) {
TextFieldExample obj = new TextFieldExample();
}
}
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
}