Related
I am generating voucher no with the concatenation of jdatechooer and jCombobox, when user selects the jcombobox it creates a voucher no and put it in the jTextField1 and passes focus to jTextField2. Till that the Application works fine. However, after submitting data, after two or three times, when I create a voucher all the JTextFields freezes and I cannot put the data into database. enter code here
public class Voucher extends javax.swing.JInternalFrame {
private java.util.Date Current_Date ;
private java.sql.Date sqlDate;
private Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
private SimpleDateFormat dateformat =new SimpleDateFormat("HH:mm:ss");
private SimpleDateFormat simpleformat =new SimpleDateFormat("yyyy-MM-dd");
private Connection connection;
private PreparedStatement preparedStatement;
private ResultSet resultSet, AccountChartSet;
private DBConnection dbc =null;
private StringTokenizer xToken ;
private String Query, CreatedVoucher, DateVal;
private String firstval,secondVal;
private Integer MaxVoucher , VoucherType, COF;
private Double Balance=0.0;
private Double DEBIT = 0.0 , CREDIT = 0.0;
private int row = 0;
private DefaultTableModel dmodel = new DefaultTableModel(new Object[][]
{
{ null, null, null , null, null },
{ null, null, null , null, null },
{ null, null, null , null, null },
{ null, null, null , null, null }
},new String []
{
"Account Code", "Acct Name", "DR /CR", "Amount"
}){
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};
/**
* Creates new form Voucher
*/
public Voucher() {
initComponents();
setTitle("Create Voucher");
dbc = new DBConnection();
connection = dbc.dbcon();
dmodel.setNumRows(0);
Current_Date = new java.util.Date();
jDateChooser1.setDate(Current_Date);
jTextField6.setText(Balance.toString());
FetchCOF();
setVisible(true);
}
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList<>();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jTextField6 = new javax.swing.JTextField();
jTextField5 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox<>();
jTextField3 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jDateChooser1 = new com.toedter.calendar.JDateChooser();
jComboBox1 = new javax.swing.JComboBox<>();
jTextField1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jList1.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(jList1);
setBackground(new java.awt.Color(69, 105, 159));
setClosable(true);
getContentPane().setLayout(null);
jButton1.setFont(new java.awt.Font("Segoe UI", 0, 12));
jButton1.setIcon(new javax.swing.ImageIcon("D:\\GTradingPK\\src\\gtradingpk\\images\\floppy-disk.png")); // NOI18N
jButton1.setText("Submit");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton1.setBounds(10, 385, 593, 50);
jTable1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jTable1.setModel(dmodel);
jTable1.setRowHeight(24);
jTable1.setShowGrid(true);
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(10, 210, 593, 170);
jTextField6.setEditable(false);
jTextField6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
getContentPane().add(jTextField6);
jTextField6.setBounds(453, 180, 150, 25);
jTextField5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jTextField5.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
jTextField5FocusLost(evt);
}
});
getContentPane().add(jTextField5);
jTextField5.setBounds(171, 180, 280, 25);
jTextField4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
getContentPane().add(jTextField4);
jTextField4.setBounds(10, 180, 160, 25);
jLabel7.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("Amount");
getContentPane().add(jLabel7);
jLabel7.setBounds(10, 162, 100, 14);
jLabel8.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("Narration");
getContentPane().add(jLabel8);
jLabel8.setBounds(171, 162, 100, 14);
jLabel9.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("Balance");
getContentPane().add(jLabel9);
jLabel9.setBounds(453, 162, 100, 14);
jComboBox2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select", "Debit", "Credit" }));
getContentPane().add(jComboBox2);
jComboBox2.setBounds(453, 130, 150, 25);
jTextField3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
getContentPane().add(jTextField3);
jTextField3.setBounds(171, 130, 280, 25);
jTextField2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jTextField2.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
jTextField2FocusLost(evt);
}
});
getContentPane().add(jTextField2);
jTextField2.setBounds(10, 130, 160, 25);
jLabel4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Acct Code");
getContentPane().add(jLabel4);
jLabel4.setBounds(10, 110, 120, 20);
jLabel5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Acct Name");
getContentPane().add(jLabel5);
jLabel5.setBounds(171, 110, 120, 20);
jLabel6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("Debit / Credit");
getContentPane().add(jLabel6);
jLabel6.setBounds(453, 110, 120, 20);
jDateChooser1.setDateFormatString("dd-MM-yyyy");
jDateChooser1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
getContentPane().add(jDateChooser1);
jDateChooser1.setBounds(453, 80, 150, 25);
jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select Voucher Type", "1-JV", "2-RV", "3-PV", "4-CV" }));
jComboBox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBox1ItemStateChanged(evt);
}
});
getContentPane().add(jComboBox1);
jComboBox1.setBounds(171, 80, 280, 25);
jTextField1.setEditable(false);
jTextField1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jTextField1.setFocusable(false);
jTextField1.setRequestFocusEnabled(false);
getContentPane().add(jTextField1);
jTextField1.setBounds(10, 80, 160, 25);
jLabel1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Voucher Code");
getContentPane().add(jLabel1);
jLabel1.setBounds(10, 64, 120, 14);
jLabel2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Voucher Type");
getContentPane().add(jLabel2);
jLabel2.setBounds(171, 64, 120, 14);
jLabel3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Date");
getContentPane().add(jLabel3);
jLabel3.setBounds(453, 64, 120, 14);
jPanel1.setBackground(new java.awt.Color(46, 26, 71));
jPanel1.setLayout(null);
jLabel10.setFont(new java.awt.Font("Segoe UI", 0, 20)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel10.setText("CREATE VOUCHER");
jPanel1.add(jLabel10);
jLabel10.setBounds(0, 10, 610, 30);
getContentPane().add(jPanel1);
jPanel1.setBounds(0, 0, 620, 60);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTextField1.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Voucher No is Missing ....");
}
else if (jComboBox1.getSelectedIndex() == 0)
{
JOptionPane.showMessageDialog(null, "Voucher Type is Missing ....");
jComboBox1.grabFocus();
}
else if(jTextField5.getText().equalsIgnoreCase(""))
{
JOptionPane.showMessageDialog(null, "Narration is Missing ....");
jTextField5.grabFocus();
}
else if (Balance != 0 )
{
JOptionPane.showMessageDialog(null, "Debit / Credit is not Equal");
}
else
{
double damount = 0.0 , camount = 0.0, balanceamt = 0.0;
try
{
CreateValues();
Current_Date = jDateChooser1.getDate();
String datestamp = simpleformat.format(Current_Date.getTime());
String timeStamp = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
String DateTimess = datestamp+" "+timeStamp;
xToken = new StringTokenizer(jComboBox1.getSelectedItem().toString(), "-");
String voutype = xToken.nextToken().trim();
Integer voint= Integer.parseInt(voutype);
connection.setAutoCommit(false);
Query = "insert into voucher(voucherno, vdate, cof, decr, naration, debitamount,creditamount, balance, void,statuss, xdate) values(?,?,?,?,?,?,?,?,?,?,?) ";
preparedStatement = connection.prepareStatement(Query);
for(int x = 0 ; x<jTable1.getRowCount(); x++)
{
preparedStatement.setString(1, jTextField1.getText());
preparedStatement.setObject(2,DateTimess);
preparedStatement.setLong(3 , Long.parseLong(jTable1.getValueAt(x, 0).toString()));
preparedStatement.setString(4, jTable1.getValueAt(x , 2).toString());
preparedStatement.setString(5, jTextField5.getText());
if(jTable1.getValueAt(x , 2).toString().equalsIgnoreCase("Debit"))
{
damount = Double.parseDouble( jTable1.getValueAt(x, 3).toString() );
balanceamt = damount - camount;
preparedStatement.setDouble(6, damount);
preparedStatement.setDouble(7, camount);
preparedStatement.setDouble(8, balanceamt);
}
else {
camount = Double.parseDouble( jTable1.getValueAt(x, 3).toString() );
balanceamt = damount - camount;
preparedStatement.setDouble(6, damount);
preparedStatement.setDouble(7, camount);
preparedStatement.setDouble(8, balanceamt);
}
preparedStatement.setInt(9 , voint);
preparedStatement.setString(10 , "u");
preparedStatement.setObject(11, Current_Date);
preparedStatement.addBatch();
damount = 0.0 ;
camount = 0.0;
balanceamt = 0.0;
}
preparedStatement.executeBatch();
Query = "insert into vouchercounter values(?,?,?)";
preparedStatement = connection.prepareStatement(Query);
preparedStatement.setInt(1 , MaxVoucher);
preparedStatement.setObject(2 , Current_Date );
preparedStatement.setString(3, jTextField1.getText());
preparedStatement.execute();
connection.commit();
//System.out.println(resultSet.isClosed());
JOptionPane.showMessageDialog(null, "Voucher Saved Sccessfully....");
MaxVoucher++;
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jTextField6.setText("");
//jTextField2.requestFocus();
jComboBox1.setSelectedIndex(0);
jComboBox2.setSelectedIndex(0);
dmodel.setNumRows(0);
row=0;
}catch(SQLException sskl){System.out.println(sskl.getMessage());}
} // else closes
// TODO add your handling code here:
}
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getClickCount() == 2 && !evt.isConsumed())
{
evt.consume();
dmodel.removeRow(jTable1.getSelectedRow());
row--;
}
// TODO add your handling code here:
}
private void jTextField5FocusLost(java.awt.event.FocusEvent evt) {
if(jTextField2.getText().equals(""))
{
jTextField2.requestFocus();
}
else if (jTextField3.getText().equals(""))
{
jTextField3.requestFocus();
}
else if (jTextField4.getText().equals(""))
{
jTextField4.requestFocus();
}
else if (jTextField5.getText().equals(""))
{
jTextField5.requestFocus();
}
else if (jComboBox2.getSelectedIndex() == 0)
{
JOptionPane.showMessageDialog(null, "Please Select Debit / Credit");
jComboBox2.requestFocus();
}
else
{
dmodel.addRow(new Object[]{"","","",""});
jTable1.setValueAt(jTextField2.getText(), row, 0);
jTable1.setValueAt(jTextField3.getText(), row, 1);
jTable1.setValueAt(jComboBox2.getSelectedItem().toString(), row, 2);
jTable1.setValueAt(jTextField4.getText(), row, 3);
CalculateValues();
jComboBox2.setSelectedIndex(0);
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField2.grabFocus();
row++;
}
// TODO add your handling code here:
}
private void jTextField2FocusLost(java.awt.event.FocusEvent evt) {
boolean cofound = false;
if( jTextField2.getText().length() >= 4)
{
COF = Integer.parseInt(jTextField2.getText());
try{
AccountChartSet.beforeFirst();
while(AccountChartSet.next())
{
if (COF == AccountChartSet.getInt(1))
{
jTextField3.setText(AccountChartSet.getString(2));
cofound = true;
break;
}
}
if( (COF < 1100) || (COF > 9999))
{
// System.out.println("I am here");
JOptionPane.showMessageDialog(jTextField2, "Invalid Chart of Acctount");
jTextField2.requestFocus();
}
}catch(Exception zsdf){ System.out.println(zsdf.getMessage());}
}
// TODO add your handling code here:
}
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
/* if(evt.getStateChange() == ItemEvent.SELECTED && jComboBox1.getSelectedIndex() > 0 )
{
CreateValues();
}
*/
CreateValues();
// TODO add your handling code here:
}
void CalculateValues()
{
Balance=0.0;
CREDIT =0.0;
DEBIT = 0.0;
if(jTable1.getRowCount() > 0)
{
for (int x = 0 ; x<jTable1.getRowCount(); x++)
{
if(jTable1.getValueAt(x, 2).toString().equals("Debit"))
{
DEBIT = DEBIT + Double.parseDouble(jTable1.getValueAt(x, 3).toString()) ;
}
else //(jTable1.getValueAt(x, 2).toString().equals("Crdit"))
{
CREDIT = CREDIT + Double.parseDouble(jTable1.getValueAt(x, 3).toString()) ;
}
}
Balance = DEBIT- CREDIT;
jTextField6.setText(Balance.toString());
} // outer if closes
}
void CreateValues()
{
if (jComboBox1.getSelectedIndex()> 0)
{
Current_Date = jDateChooser1.getDate();
DateVal = simpleformat.format(Current_Date);
//sqlDate = new java.sql.Date(Current_Date.getTime());
xToken = new StringTokenizer(jComboBox1.getSelectedItem().toString() , "-");
firstval = xToken.nextToken().trim();
secondVal= xToken.nextToken().trim();
CreatedVoucher = secondVal+"-"+DateVal+"-"+MaxVoucher.toString();
jTextField1.setText(CreatedVoucher);
}
}
void FetchCOF()
{
try{
Query = "select cof, cofname from accountchart ";
preparedStatement = connection.prepareStatement(Query, ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
AccountChartSet = preparedStatement.executeQuery();
Query = "select count(vcounter) from vouchercounter ";
preparedStatement = connection.prepareStatement(Query, ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
resultSet = preparedStatement.executeQuery();
resultSet.next();
MaxVoucher = resultSet.getInt(1);
MaxVoucher++;
// jTextField2.requestFocus();
}catch(SQLException sdfsda){}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JComboBox<String> jComboBox2;
private com.toedter.calendar.JDateChooser jDateChooser1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JList<String> jList1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;
// End of variables declaration
}
I'm making a particle-attractor-thing in Processing 3.0, and I'm having difficulty when adding multiples of what I've deemed 'Nodes'; objects that automatically attract or repel particles without mouse input. Normally left-clicking the mouse attracts these particles and right-clicking repels them. I made Nodes so that I could have multiple locations attracting/repelling at once.
The main problem I'm having atm is when I add more than one Node, only the last-added one actually works; all others do nothing.
Here is all my code including two other classes (Particle and Node). It's a lot of code, but I'd really appreciate it if someone could point out my error(s).
http://pastebin.com/iKELuVJ7
I believe the trouble is in the Particle class in the Node for loop where I am setting acc = d, but I don't know a good workaround.
As an additional question, does anyone know a good way to make the strength of the attraction scale inversely with distance from the attracting object? I tried a backwards map() function with arbitrary upper/lower limits which works for now, but I'd prefer not to hardcode it. Any other general improvements/recommendations are appreciated.
That's a nice looking sketch. You are totally right about acc = d.
This part:
for (Node n: nodes) {
PVector d = PVector.sub(n.loc, loc);
d.normalize();
d.mult(n.strength);
acc = d;
}
means you're overwriting the acc vector which d.
Since you run loop, in the end acc will be equal to the last node in your list.
If you want each node to have a certain influence, simply add the node based vector to acc:
for (Node n: nodes) {
PVector d = PVector.sub(n.loc, loc);
d.normalize();
d.mult(n.strength);
acc.add(d);
}
You did this already on the mouse interaction.
In terms of other recommendations, you could try to cache PVector instances more often. Bellow I supply a basic example of how to cache the mousePosition (as a single top level variable, rather than multiple instances, per particle, per frame). mag() uses sqrt() which can be costly. Try using magSq() instead (and using squared ranges instead). You can spot these this in chapter 6.15 A Few Last Notes: Optimization Tricks of Nature of Code by Daniel Shiffman. I warmly recommend this book.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PVector m = new PVector(mouseX, mouseY);
ArrayList<Particle> parts = new ArrayList<Particle>();
ArrayList<Node> nodes = new ArrayList<Node>();
float speed = 2;
float grav = 4;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup() {
size(800, 800, P2D);
// fullScreen(P2D);
noStroke();
smooth(4);
blendMode(ADD);
frameRate(60);
for (int i = 0; i < 1000; i++) {
parts.add(new Particle(new PVector(random(width), random(height)), (int)random(1, 25)));
}
nodes.add(new Node(new PVector(200, 400), 0.75));
nodes.add(new Node(new PVector(400, 400), 0.50));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void draw() {
background(0);
if(mousePressed){
m.set(mouseX, mouseY);
}
for (Node n: nodes) {
n.draw();
}
for (int i = 0; i < parts.size(); i++) {
Particle p = (Particle) parts.get(i);
p.draw();
p.boundary();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Particle {
PVector loc, vel, acc;
int size = 5;
Particle(PVector loc, int size) {
this.loc = loc;
vel = new PVector();
acc = new PVector();
this.size = size;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void draw() {
acc.mult(0);
for (Node n: nodes) {
PVector d = PVector.sub(n.loc, loc);
d.normalize();
d.mult(n.strength);
//acc = d;
acc.add(d);
}
if (mousePressed && mouseButton == LEFT) {
PVector d = PVector.sub(m, loc);
//d.normalize();
d.setMag(map(d.mag(), 0, 2200, speed, 0));
d.mult(speed);
//acc = d;
acc.add(d);
} else if (mousePressed && mouseButton == RIGHT) {
PVector d = PVector.sub(m, loc);
d.normalize();
d.mult(-1*speed);
//acc = d;
acc.add(d);
}
acc.set(acc);
acc.mult(acc.mag());
vel.add(acc);
//vel.add(new PVector(0, grav));
loc.add(vel);
acc.mult(0);
//vel.mult(pow(0.90, 0.1*size));
vel.mult(0.97);
colorScheme(0);//"RedYellow"
ellipse(loc.x, loc.y, size, size);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void boundary() {
if(loc.x < 0)
vel.x *= -1;
if(loc.x > width)
vel.x *= -1;
if(loc.y < 0)
vel.y *= -1;
if(loc.y > height)
vel.y *= -1;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
String[] patterns = {"RedYellow","RedMagenta","GreenYellow","GreenCyan","BlueMagenta","BlueCyan","Cyclic","BWCyclic","PROTOTYPE"};
//void colorScheme(String pattern) {
void colorScheme(int pattern) {
//compute this once, rather than multiple times per case
//also check out magSq() https://processing.org/reference/PVector_magSq_.html
float mag = vel.mag();
switch (pattern) {
case 0:
fill(255, map(mag, 0, 20, 0, 255), map(mag - 20, 0, 20, 0, 255)); //Red Yellow White
break;
case 1:
fill(255, map(mag - 20, 0, 20, 0, 255), map(mag, 0, 20, 0, 255)); //Red Magenta White
break;
case 2:
fill(map(mag, 0, 20, 0, 255), 255, map(mag - 20, 0, 20, 0, 255)); //Green Yellow White
break;
case 3:
fill(map(mag - 20, 0, 20, 0, 255), 255, map(mag, 0, 20, 0, 255)); //Green Cyan White
break;
case 4:
fill(map(mag, 0, 20, 0, 255), map(mag - 20, 0, 20, 0, 255), 255); //Blue Magenta White
break;
case 5:
fill(map(mag - 20, 0, 20, 0, 255), map(mag, 0, 20, 0, 255), 255); //Blue Cyan White
break;
case 6:
fill(cos(map(mag, 0, 20, 0, 360))*255, cos(map(mag + 20/3, 0, 20, 0, 360))*255, cos(map(mag + 40/3, 0, 20, 0, 360))*255); //Cyclic
break;
case 7:
fill(cos(map(mag, 0, 20, 0, 360))*255, cos(map(mag, 0, 20, 0, 360))*255, cos(map(mag, 0, 20, 0, 360))*255); //B&W Cyclic
break;
case 8:
fill(0, 0, 0); //Cyclic
break;
default:
stroke(255, 255, 255);
fill(255, 255, 255);
break;
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Node {
PVector loc;
float strength;
Node(PVector loc, float strength) {
this.loc = loc;
this.strength = strength;
}
void draw() {
fill(255, 255, 255,64);
ellipse(loc.x, loc.y, 50, 50);
}
}
I have some problems with rendering of mirror reflection in OpenTK. I need to see reflection of objects only from one side from my mirror, but my program also gives reflection from another side and it hides the first one. Could you help me?
private void glControl1_Load(object sender, EventArgs e)
{
loaded = true;
GL.ClearColor(Color.SkyBlue);
initRendering();
Matrix4 p = Matrix4.CreatePerspectiveFieldOfView((float)(80 * Math.PI / 180), 1, 20, 500);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadMatrix(ref p);
Matrix4 modelview = Matrix4.LookAt(70, 70, 70, 0, 0, 0, 0, 1, 0);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadMatrix(ref modelview);
}
private void glControl1_Paint(object sender, PaintEventArgs e)
{
if (!loaded)
return;
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
drawScene();
/*axes*/
GL.Color3(Color.Black);
GL.Begin(BeginMode.Lines);
GL.Vertex3(0, 0, 0);
GL.Vertex3(70, 0, 0);
GL.Vertex3(0, 0, 0);
GL.Vertex3(0, 70, 0);
GL.Vertex3(0, 0, 0);
GL.Vertex3(0, 0, 70);
GL.End();
glControl1.SwapBuffers();
}
void initRendering()
{
GL.ShadeModel(ShadingModel.Flat);
GL.ClearDepth(1.0f);
GL.ClearStencil(0);
GL.Enable(EnableCap.DepthTest);
GL.DepthFunc(DepthFunction.Lequal);
GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
GL.Enable(EnableCap.AutoNormal);
// Setup the drawing area and shading mode
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Enable(EnableCap.PointSmooth);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.Enable(EnableCap.Lighting);
GL.LightModel(LightModelParameter.LightModelAmbient, ambientLight);
GL.Enable(EnableCap.Normalize);
GL.Enable(EnableCap.ColorMaterial);
}
public class CustomOpenGLControl : GLControl
{
public CustomOpenGLControl()
: base(new OpenTK.Graphics.GraphicsMode(32, 24, 8))
{
}
}
private void drawFrame()
{
GL.Color3(Color.Red);
GL.Begin(BeginMode.Quads);
GL.Normal3(0.0f, -1.0f, 0.0f);
for (int i = 0; i < upWall.Length; i++)
{
GL.Vertex3(upWall[i].x, upWall[i].y, upWall[i].z);
}
GL.End();
GL.Color3(Color.Yellow);
GL.Begin(BeginMode.Quads);
GL.Normal3(0.0f, -1.0f, 0.0f);
for (int i = 0; i < downWall.Length; i++)
{
GL.Vertex3(downWall[i].x, downWall[i].y, downWall[i].z);
}
GL.End();
GL.Color3(Color.Green);
GL.Begin(BeginMode.Quads);
GL.Normal3(0.0f, 0.0f, -1.0f);
for (int i = 0; i < backWall.Length; i++)
{
GL.Vertex3(backWall[i].x, backWall[i].y, backWall[i].z);
}
GL.End();
GL.Color3(Color.Blue);
GL.Begin(BeginMode.Quads);
GL.Normal3(-1.0f, 0.0f, 0.0f);
for (int i = 0; i < rightWall.Length; i++)
{
GL.Vertex3(rightWall[i].x, rightWall[i].y, rightWall[i].z);
}
GL.End();
GL.Color3(Color.Orange);
GL.Begin(BeginMode.Quads);
GL.Normal3(1.0f, 0.0f, 0.0f);
for (int i = 0; i < leftWall.Length; i++)
{
GL.Vertex3(leftWall[i].x, leftWall[i].y, leftWall[i].z);
}
GL.End();
}
private void drawMirror()
{
GL.PushMatrix();
GL.Begin(BeginMode.Quads);
GL.Normal3(0.0f, -1.0f, 0.0f);
for (int i = 0; i < mirror.Length; i++)
{
GL.Vertex3(mirror[i].x, mirror[i].y, mirror[i].z);
}
GL.End();
GL.PopMatrix();
}
private void drawScene()
{
GL.Clear(ClearBufferMask.AccumBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit | ClearBufferMask.ColorBufferBit);
double[] eqr = { 0f, y0 + height / 6f, 0f, 0.0f };
GL.PushMatrix();
GL.ColorMask(false, false, false, false);
GL.Enable(EnableCap.StencilTest);
GL.StencilFunc(StencilFunction.Always, 1, 1);
GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Replace);
GL.Disable(EnableCap.DepthTest);
drawMirror();
GL.Enable(EnableCap.DepthTest);
GL.ColorMask(true, true, true, true);
GL.StencilFunc(StencilFunction.Equal, 1, 1);
GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Keep);
GL.Enable(EnableCap.ClipPlane0);
GL.ClipPlane(ClipPlaneName.ClipPlane0, eqr);
GL.PushMatrix();
GL.Scale(1, -1, 1);
drawFrame();
GL.PopMatrix();
GL.Disable(EnableCap.ClipPlane0);
GL.Disable(EnableCap.StencilTest);
GL.Enable(EnableCap.Blend);
GL.Disable(EnableCap.Lighting);
GL.Color4(1, 1, 1, 0.3f);
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
drawMirror();
GL.Enable(EnableCap.Lighting);
GL.Disable(EnableCap.Blend);
drawFrame();
GL.PopMatrix();
}
}
Sorry, I cant help too much with this. I would run your code, but unfortunately I am not at my programming computer right now, and I don't have any experience with opentk.
I am writing a small program in Processing to display the values of a speed trap and elapsed time(like a drag strip, but for a waterslide for Australia Day) coming from a microcontroller over serial.
I have had the Processing sketch running and have done most of the development with just a mouse click to imitate new data and run the program, I also have set up the hardware and had it running with the microcontroller sending the serial data and the program displaying it.
I have done some further development, and now when it runs I am getting some strange things happening, boxes sometimes come through in the wrong color, some artifacts in the displayed numbers, and a lot of wrong colors for only some of the graph(the graph is made with a for loop and the color is set outside of it).
I have tried adding in some delays to make sure its getting a full string of data and I have also tried moving around the sub routines but nothing works.
The faults only appeared after I added in the elapsed time code to the serial data, before it was just one string, now it is two numbers separated by a colon.
I have put my code in here as well, its pretty straight forward, I am only new to programming, please excuse(and point out!) any errors.
import processing.serial.*;
Serial myPort;
float inString;
float inFloat0, inFloat1;
float[] list = new float[0];
float[] etlist = new float[0];
PFont f1, f2, f3, f4, f5, f6;
int index;
float rank;
float percentage;
int trapDistance = 1000;
int SgraphH = 38; //Speed graph scale
int ETgraphH = 15; //ET graph scale
int valueX = 0;
int valueY = 0;
boolean graph30 = false, graph690 = false;
color c1, c2, c3 = color(220, 0, 0), c4 = color(220, 0, 0);
int boxX = 295, boxY = 430, boxSize = 15; //Graph 30 box
void setup () {
size(1280, 700);
index = 0;
//Load list from textfile
String loadlist[] = loadStrings("list.txt");
for (int i = 0; i < loadlist.length; i++) {
String[] split = split(loadlist[i], ',');
list = append(list, float(split[0]));
etlist = append(etlist, float(split[1]));
index++;
}
println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 9600);
myPort.bufferUntil('\n');
//Create fonts
f1 = createFont("Arial Unicode MS", 20);
f2 = createFont("Arial Unicode MS", 240);
f3 = createFont("Arial Unicode MS", 35);
f4 = createFont("Arial Unicode MS", 15);
f5 = createFont("Arial Unicode MS", 15);
f6 = createFont("Arial Unicode MS", 12);
}
void draw () {
stroke(225);
fill(225);
rectMode(CORNER);
rect(0, 0, 500, 20);
fill(0);
text(mouseX, 20, 20);
text(mouseY, 50, 20);
text(mouseX - valueX, 80, 20);
text(mouseY - valueY, 110, 20);
}
void mousePressed() {
//Check if Mouse is over button and toggle Graph on
if (mouseX > boxX && mouseX < boxX+boxSize && mouseY >boxY && mouseY < boxY+boxSize) {
if (graph30) {
graph30 = false;
c3 = color(220, 0, 0);
}
else {
graph30 = true;
c3 = color(0, 220, 0);
}
create();
graphCheck();
graph();
}
//Check if Mouse is over button and toggle Graph on
if (mouseX > boxX+100 && mouseX < boxX+100+boxSize && mouseY >boxY && mouseY < boxY+boxSize) {
if (graph690) {
graph690 = false;
c4 = color(220, 0, 0);
}
else {
graph690 = true;
c4 = color(0, 220, 0);
}
create();
graphCheck();
graph();
}
}
void serialEvent (Serial myPort) {
delay(100);
String inString = myPort.readStringUntil('\n');
delay(100);
if (inString != null) {
inString = trim(inString);
String[] split = split(inString, ',');
inFloat0 = float(split[0]);
inFloat1 = float(split[1]);
index++;
float speed = trapDistance / inFloat0 * 3.6;
list = append(list, speed);
float et = inFloat1;
etlist = append(etlist, et);
//Clear screen
background(225);
//Run sub routines
create();
graphCheck();
graph();
}
}
void delay(int delay)
{
int time = millis();
while(millis() - time <= delay);
}
void create() {
//Clear screen
background(225);
//Sorting
float[] sortlist = new float[index+1];
sortlist = sort(list);
float[] sortetlist = new float[index+1];
sortetlist = sort(etlist);
//Calculate rank
int pos = 1;
while (list[index-1] > sortlist[pos - 1]) {
pos++;
}
if (pos == 1) {
rank = 0;
}
else {
rank = (pos / float(sortlist.length));
}
//Calculate Percentage of Speed
percentage = list[index-1] / sortlist[sortlist.length -1];
//Speed colour for fastest and slowest
if (index != 0) {
if (list[index-1] < sortlist[1]) {
c1 = color(240, 0, 0);
}
else if (list[index-1] > sortlist[index-1]) {
c1 = color(0, 240, 0);
}
else {
c1 = color(255);
}
}
else {
c1 = color(255);
}
//ET colour for fastest and slowest
if (index != 0) {
if (etlist[index-1] < sortetlist[1]) {
c2 = color(240, 0, 0);
}
else if (etlist[index-1] > sortetlist[index-1]) {
c2 = color(0, 240, 0);
}
else {
c2 = color(255);
}
}
else {
c2 = color(255);
}
//Boxes
rectMode(CORNER);
stroke(0);
fill(c1);
rect(15, 15, width-30, 200); //Speed
fill(c2);
rect(15, 230, width-30, 200); //ET
fill(255);
rect(15, height - 255, 125, 240); //Left
rect(155, height -255, 125, 240); //Left
rect(width - 140, height - 255, 125, 240); //Right
rect(width - 280, height - 255, 125, 240); //Right
//Text
fill(0);
textFont(f3);
textAlign(CENTER);
text("Speed", 78, height - 220);
text("ET", width - 78, height - 220);
text("ET", 218, height - 220);
text("Speed", width - 218, height - 220);
textFont(f4);
textAlign(LEFT);
text("Trap Distance: " + trapDistance + "mm", 2, height - 2);
//Big Numbers
textAlign(CENTER);
textFont(f2);
text(String.format("%.2f", list[index-1])+"km/h", width/2, 200); //Speed
text(String.format("%.2f", etlist[index-1])+"sec", width/2, 415); //ET
//Last 10
for (int i = 0; i <= index-1 && i < 10; i++) {
textAlign(LEFT);
textFont(f5);
text((index-1 - i + 1)+". "+String.format("%.3f", list[index-1 - i])+"km/h", 23, (height - 200 + (i * 20)));
}
//Last 10 ET
for (int i = 0; i <= index-1 && i < 10; i++) {
textAlign(LEFT);
textFont(f5);
text((index-1 - i + 1)+". "+String.format("%.3f", etlist[index-1 - i])+"sec", 163, (height - 200 + (i * 20)));
}
//Fastest
for (int i = 0; i <= index-1 && i < 10; i++) {
textAlign(CENTER);
textFont(f5);
text((i+1)+". "+String.format("%.3f", sortlist[sortlist.length - (i+1)])+"km/h", width - 220, (height - 200 + (i * 20)));
}
//Fastest ET
for (int i = 0; i <= index-1 && i < 10; i++) {
textAlign(CENTER);
textFont(f5);
text((i+1)+". "+String.format("%.3f", sortetlist[i])+"sec", width - 80, (height - 200 + (i * 20)));
}
//Create string for saving to text file
String[] listString = new String[index-1+1];
for (int i = 0; i < index-1+1; i++) {
listString[i] = (Float.toString(list[i]) + ',' + Float.toString(etlist[i]));
}
//Save to text file
saveStrings("list.txt", listString);
//Graph with curves
// beginShape();
// stroke(125, 125, 255);
// for (int i = 1; i <= index && i < 34; i++) {
// float y = map(list[index - (i - 1)], 0, SgraphH, 150, 0);
// curveVertex((width + 25 - (i * 25)), 25 + y);
// }
// endShape();
}
void graph() {
//Create graph area
fill(255);
rectMode(CENTER);
rect(width/2, height - 135, 690, 240);
stroke(192);
for (int i = 1; i < 30.; i++) {
line((((width - 690)/2) + (i * (690/30))), 446, ((((width - 690)/2) + (i * (690/30)))), 684);
}
for (int i = 1; i < 10; i++) {
line(((width - 690)/2)+1, (445 + (i * 24)), (width - (width - 690)/2)-1, (445 + (i * 24)));
}
//Graph last 690
if (graph690) {
stroke(0, 170, 0);
for (int i = 1; i <= index-1 && i < 690; i++) {
float start = map(list[index-1 - (i - 1)], 0, SgraphH, 240, 0);
float end = map(list[index-1 - i], 0, SgraphH, 240, 0);
line(((width - (width - 690)/2) + 1 - (i)), 445 + start, ((width- (width - 690)/2) + 1 - ((i + 1))), 445 + end);
}
}
//Graph last 690
if (graph690) {
stroke(120, 0, 120);
for (int i = 1; i <= index-1 && i < 690; i++) {
float start = map(etlist[index-1 - (i - 1)], 0, ETgraphH, 240, 0);
float end = map(etlist[index-1 - i], 0, ETgraphH, 240, 0);
line(((width - (width - 690)/2) + 1 - (i)), 445 + start, ((width- (width - 690)/2) + 1 - ((i + 1))), 445 + end);
}
}
//Graph last 30 speeds
if (graph30) {
stroke(0, 0, 240);
for (int i = 1; i <= index-1 && i < 31; i++) {
float start = map(list[index-1 - (i - 1)], 0, SgraphH, 240, 0);
float end = map(list[index-1 - i], 0, SgraphH, 240, 0);
line(((width - (width - 690)/2) + 23 - (i * 23)), 445 + start, ((width- (width - 690)/2) + 23 - ((i + 1) * 23)), 445 + end);
}
}
//Graph last 30 ETs
if (graph30) {
stroke(240, 0, 0);
for (int i = 1; i <= index-1 && i < 31; i++) {
float start = map(etlist[index-1 - (i - 1)], 0, ETgraphH, 240, 0);
float end = map(etlist[index-1 - i], 0, ETgraphH, 240, 0);
line(((width - (width - 690)/2) + 23 - (i * 23)), 445 + start, ((width- (width - 690)/2) + 23 - ((i + 1) * 23)), 445 + end);
}
}
fill(0);
textAlign(LEFT);
text("0", width / 2 - 345, height - 15);
text(SgraphH, width / 2 - 345, height - 243);
}
void graphCheck() {
//Draw box and text for graph selection
rectMode(CORNER);
textFont(f6);
textAlign(LEFT);
stroke(0);
fill(0);
text("Graph last 30", boxX+20, boxY+13);
fill(c3);
rect(boxX, boxY, boxSize, boxSize);
stroke(0);
fill(0);
text("Graph last 690", boxX+120, boxY+13);
fill(c4);
rect(boxX+100, boxY, boxSize, boxSize);
}
void keyPressed() {
valueX = mouseX;
valueY = mouseY;
}
Also, when triggered from a mouse click (turning on the graph's) it works fine.
Cheers,
Matt
I fixed it.
When the subroutines were being called by the serial trigger, it some how still allowed the looped code in the draw() function to still run, which was causing the issues.
I just put noLoop() and loop() in before and after the calls for the subroutines.
All good now.
I'm having a dilemma with this code and have no clue what to do. I'm pretty new to processing. This is a project from this link...
http://blog.makezine.com/2012/08/10/build-a-touchless-3d-tracking-interface-with-everyday-materials/
any help is massively appreciated... Thanks in advance
import processing.serial.*;
import processing.opengl.*;
Serial serial;
int serialPort = 1;
int sen = 3; // sensors
int div = 3; // board sub divisions
Normalize n[] = new Normalize[sen];
MomentumAverage cama[] = new MomentumAverage[sen];
MomentumAverage axyz[] = new MomentumAverage[sen];
float[] nxyz = new float[sen];
int[] ixyz = new int[sen];
float w = 256; // board size
boolean[] flip = {
false, true, false};
int player = 0;
boolean moves[][][][];
PFont font;
void setup() {
size(800, 600, P3D);
frameRate(25);
font = loadFont("TrebuchetMS-Italic-20.vlw");
textFont(font);
textMode(SCREEN);
println(Serial.list());
serial = new Serial(this, Serial.list()[serialPort], 115200);
for(int i = 0; i < sen; i++) {
n[i] = new Normalize();
cama[i] = new MomentumAverage(.01);
axyz[i] = new MomentumAverage(.15);
}
reset();
}
void draw() {
updateSerial();
drawBoard();
}
void updateSerial() {
String cur = serial.readStringUntil('\n');
if(cur != null) {
String[] parts = split(cur, " ");
if(parts.length == sensors) {
float[] xyz = new float[sen];
for(int i = 0; i < sen; i++)
xyz[i] = float(parts[i]);
if(mousePressed && mouseButton == LEFT)
for(int i = 0; i < sen; i++)
n[i].note(xyz[i]);
nxyz = new float[sen];
for(int i = 0; i < sen; i++) {
float raw = n[i].choose(xyz[i]);
nxyz[i] = flip[i] ? 1 - raw : raw;
cama[i].note(nxyz[i]);
axyz[i].note(nxyz[i]);
ixyz[i] = getPosition(axyz[i].avg);
}
}
}
}
float cutoff = .2;
int getPosition(float x) {
if(div == 3) {
if(x < cutoff)
return 0;
if(x < 1 - cutoff)
return 1;
else
return 2;
}
else {
return x == 1 ? div - 1 : (int) x * div;
}
}
void drawBoard() {
background(255);
float h = w / 2;
camera(
h + (cama[0].avg - cama[2].avg) * h,
h + (cama[1].avg - 1) * height / 2,
w * 2,
h, h, h,
0, 1, 0);
pushMatrix();
noStroke();
fill(0, 40);
translate(w/2, w/2, w/2);
rotateY(-HALF_PI/2);
box(w);
popMatrix();
float sw = w / div;
translate(h, sw / 2, 0);
rotateY(-HALF_PI/2);
pushMatrix();
float sd = sw * (div - 1);
translate(
axyz[0].avg * sd,
axyz[1].avg * sd,
axyz[2].avg * sd);
fill(255, 160, 0);
noStroke();
sphere(18);
popMatrix();
for(int z = 0; z < div; z++) {
for(int y = 0; y < div; y++) {
for(int x = 0; x < div; x++) {
pushMatrix();
translate(x * sw, y * sw, z * sw);
noStroke();
if(moves[0][x][y][z])
fill(255, 0, 0, 200);
else if(moves[1][x][y][z])
fill(0, 0, 255, 200);
else if(
x == ixyz[0] &&
y == ixyz[1] &&
z == ixyz[2])
if(player == 0)
fill(255, 0, 0, 200);
else
fill(0, 0, 255, 200);
else
fill(0, 100);
box(sw / 3);
popMatrix();
}
}
}
fill(0);
if(mousePressed && mouseButton == LEFT)
msg("defining boundaries");
}
void keyPressed() {
if(key == TAB) {
moves[player][ixyz[0]][ixyz[1]][ixyz[2]] = true;
player = player == 0 ? 1 : 0;
}
}
void mousePressed() {
if(mouseButton == RIGHT)
reset();
}
void reset() {
moves = new boolean[2][div][div][div];
for(int i = 0; i < sen; i++) {
n[i].reset();
cama[i].reset();
axyz[i].reset();
}
}
void msg(String msg) {
text(msg, 10, height - 10);
}
You are missing a class, in fact, more than one. Go back to the github and download, or copy and paste, all three codes, placing each one in a new tab named same name of the class (well this is not required, but is a good practice). The TicTacToe3D.pde is the main code. To make a new tab choose "new tab" from the arrow menu in Processing IDE (just below the standard button at the right). The code should run. WIll need an Arduino though to really get it working.