All jTextFields Fields Freeze when I Select the JComboBox - jtextfield
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
}
Related
Trying to deduce location of mouse drag with JavaFX Gridpane
Note: 25 years with Java, 2.5 hours (almost) with JavaFX. I want to be able to highlight all cells of a GridPane that the mouse is dragged across - i.e. everything that intersects with the rectangle cornered by the click point and the current drag point. I can do that if all children are 1x1, but with mixed sizes I'm having no joy. For example, if the top row has 1 1 column cell (A) and 1 2 column cell (B) and the bottom has 1 2 column cell (C) and 1 1 column cell (D), if I click in A and drag down into C I can highlight both. However, I cannot figure out when I drag into the right half of C so that B should be highlighted. Sample Board: Apologies for the HSCE - it's a bit long but I felt stripping it down would reduce readability. import java.util.*; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.input.MouseEvent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.*; import javafx.scene.Node; import javafx.stage.Stage; import javafx.geometry.*; public class AddTestSSCE extends Application { ArrayList<StackPane> sPanes = new ArrayList<StackPane>(); // selected panes GridPane theGrid; Node startNode = null; int col0, col1; int row0, row1; #Override public void start(Stage stage) { theGrid = new GridPane(); ColumnConstraints col = new ColumnConstraints(300); theGrid.getColumnConstraints().addAll(col, col, col); RowConstraints row = new RowConstraints(200); theGrid.getRowConstraints().addAll(row, row, row); addGridPane(); theGrid.getStyleClass().add("bg-grid"); Scene scene = new Scene(theGrid, 1024, 768); scene.getStylesheets().add("addtestssce.css"); stage.setScene(scene); stage.show(); } public void addGridPane() { theGrid.setHgap(10); theGrid.setVgap(10); theGrid.setPadding(new Insets(0, 10, 0, 10)); StackPane theSP = sPAdd(new Label("A")); theGrid.add(theSP, 0, 0, 1, 1); theSP = sPAdd(new Label("B")); theGrid.add(theSP, 1, 0, 2, 1); theSP = sPAdd(new Label("C")); theGrid.add(theSP, 0, 1, 2, 1); theSP = sPAdd(new Label("D")); theGrid.add(theSP, 2, 1, 1, 1); theGrid.addEventFilter(MouseEvent.MOUSE_PRESSED, //Creating the mouse event handler new EventHandler<MouseEvent>() { #Override public void handle(MouseEvent e) { System.out.println("We're Moving!!"); startNode = (Node)e.getTarget(); sPanes.add((StackPane)startNode); col0 = GridPane.getColumnIndex(startNode).intValue(); row0 = GridPane.getRowIndex(startNode).intValue(); System.out.printf("Starting at %d %d\n", col0, row0); } }); theGrid.addEventFilter(MouseEvent.MOUSE_DRAGGED, //Creating the mouse event handler new EventHandler<MouseEvent>() { Node lastNode = null; #Override public void handle(MouseEvent e) { Node target = (Node)e.getTarget(); double xLoc = e.getX(); double yLoc = e.getY(); Bounds bs = target.localToScene(target.getBoundsInLocal()); Node moveTarget; if( bs.contains(xLoc, yLoc) ) { moveTarget = target; } else { moveTarget = getContainingNode((int)xLoc, (int)yLoc); } if( moveTarget != null && lastNode != moveTarget ) { col1 = GridPane.getColumnIndex(moveTarget).intValue(); row1 = GridPane.getRowIndex(moveTarget).intValue(); doHighlighting(); lastNode = moveTarget; } } }); } void doHighlighting() { int c0, c1, r0, r1; c0 = col0 > col1 ? col1 : col0; c1 = !(col0 > col1) ? col1 : col0; r0 = row0 > row1 ? row1 : row0; r1 = !(row0 > row1) ? row1 : row0; Rectangle2D rec1 = new Rectangle2D(c0, r0, c1-c0+1, r1-r0+1); System.out.printf("Box: %d %d %d %d\n", c0, c1, r0, r1); List<Node> nodes = theGrid.getChildren(); for( Node node : nodes ) { StackPane sp = (StackPane)node; unhighlight(sp); int col = GridPane.getColumnIndex(sp).intValue(); int row = GridPane.getRowIndex(sp).intValue(); if( occupiesCell(sp, rec1) ) { highlight(sp); } } } boolean occupiesCell(Node node, Rectangle2D r1) { boolean result = false; int col = GridPane.getColumnIndex(node).intValue(); int row = GridPane.getRowIndex(node).intValue(); int wid = GridPane.getColumnSpan(node).intValue(); int hei = GridPane.getRowSpan(node).intValue(); Rectangle2D r2 = new Rectangle2D( col, row, wid, hei); return r2.intersects(r1); } void unhighlight(Node node) { if( !(node instanceof StackPane) ) { return; } StackPane label = (StackPane)node; List<String> cList = label.getStyleClass(); cList.remove("b2"); cList.add("b1"); } void highlight(Node node) { if( !(node instanceof StackPane) ) { return; } StackPane label = (StackPane)node; List<String> cList = label.getStyleClass(); cList.remove("b1"); cList.add("b2"); } private Node getContainingNode(int xLoc, int yLoc) { Node tgt = null; for( Node node : theGrid.getChildren() ) { Bounds boundsInScene = node.localToScene(node.getBoundsInLocal()); if( boundsInScene.contains(xLoc, yLoc) ) { return node; } } return tgt; } private StackPane sPAdd(Label label) { StackPane gPPane = new StackPane(); gPPane.getChildren().add(label); gPPane.getStyleClass().addAll("b1", "grid-element"); GridPane.setFillHeight(gPPane, true); GridPane.setFillWidth(gPPane, true); return gPPane; } public static void main(String[] args) { launch(); } } .bg-grid { -fx-background-color: slategrey; } .grid-element { -fx-border-width: 10; -fx-border-color: rgb(225, 128, 217); -fx-background-color: rgb(247, 146, 146); -fx-font: 36 arial; } .b1 { -fx-text-base-color: white; -fx-border-color: rgb(225, 128, 217); } .b2 { -fx-text-base-color: lightgray; -fx-border-color: rgb(233, 228, 86); }
After a bit of back and forth with #james_d and #slaw, finally came up with a working solution. import java.util.*; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.input.MouseEvent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.*; import javafx.scene.Node; import javafx.stage.Stage; import javafx.geometry.*; import javafx.css.PseudoClass; public class AddTestSSCE extends Application { private static final PseudoClass highlight = PseudoClass.getPseudoClass("highlight"); ArrayList<StackPane> sPanes = new ArrayList<StackPane>(); // selected panes GridPane theGrid; Node startNode = null; int x0, y0, x1, y1; #Override public void start(Stage stage) { theGrid = new GridPane(); ColumnConstraints col = new ColumnConstraints(300); theGrid.getColumnConstraints().addAll(col, col, col); RowConstraints row = new RowConstraints(200); theGrid.getRowConstraints().addAll(row, row, row); addGridPane(); theGrid.getStyleClass().add("bg-grid"); Scene scene = new Scene(theGrid, 1024, 768); scene.getStylesheets().add("addtestssce.css"); stage.setScene(scene); stage.show(); } public void addGridPane() { theGrid.setHgap(10); theGrid.setVgap(10); theGrid.setPadding(new Insets(0, 10, 0, 10)); StackPane theSP = sPAdd(new Label("A")); theGrid.add(theSP, 0, 0, 1, 1); theSP = sPAdd(new Label("B")); theGrid.add(theSP, 1, 0, 2, 1); theSP = sPAdd(new Label("C")); theGrid.add(theSP, 0, 1, 2, 1); theSP = sPAdd(new Label("D")); theGrid.add(theSP, 2, 1, 1, 1); theGrid.addEventFilter(MouseEvent.MOUSE_PRESSED, //Creating the mouse event handler new EventHandler<MouseEvent>() { #Override public void handle(MouseEvent e) { System.out.println("We're Moving!!"); startNode = (Node)e.getTarget(); sPanes.add((StackPane)startNode); x0 = x1 = (int)e.getX(); y0 = y1 = (int)e.getY(); doHighlighting(); System.out.printf("Starting at %d %d\n", x0, y0); } }); theGrid.addEventFilter(MouseEvent.MOUSE_DRAGGED, //Creating the mouse event handler new EventHandler<MouseEvent>() { #Override public void handle(MouseEvent e) { Node target = (Node)e.getTarget(); x1 = (int)e.getX(); y1 = (int)e.getY(); Bounds bs = target.localToScene(target.getBoundsInLocal()); Node moveTarget; if( bs.contains(x1, y1) ) { moveTarget = target; } else { moveTarget = getContainingNode( x1, y1); } if( moveTarget != null ) { doHighlighting(); } } }); } void doHighlighting() { int c0, c1, r0, r1; c0 = x0 > x1 ? x1 : x0; c1 = !(x0 > x1) ? x1 : x0; r0 = y0 > y1 ? y1 : y0; r1 = !(y0 > y1) ? y1 : y0; Bounds dragged = new BoundingBox(c0, r0, c1-c0+1, r1-r0+1); for (Node child : theGrid.getChildren()) { child.pseudoClassStateChanged(highlight, dragged.intersects(child.getBoundsInParent())); } } private Node getContainingNode(int xLoc, int yLoc) { Node tgt = null; for( Node node : theGrid.getChildren() ) { Bounds boundsInScene = node.localToScene(node.getBoundsInLocal()); if( boundsInScene.contains(xLoc, yLoc) ) { return node; } } return tgt; } private StackPane sPAdd(Label label) { StackPane gPPane = new StackPane(); gPPane.getChildren().add(label); gPPane.getStyleClass().addAll("b1", "grid-element"); GridPane.setFillHeight(gPPane, true); GridPane.setFillWidth(gPPane, true); return gPPane; } public static void main(String[] args) { launch(); } } and the CSS: .bg-grid { -fx-background-color: slategrey; } .grid-element { -fx-border-width: 10; -fx-border-color: rgb(225, 128, 217); -fx-background-color: rgb(247, 146, 146); -fx-font: 36 arial; } .grid-element:highlight { -fx-text-base-color: lightgray; -fx-border-color: rgb(233, 228, 86); }
Start a New Game ( running a program with a New Game Button ) JavaFX
I wrote a Snake Game , when it hit it's tail , it will be Game Over and throw an alert. I set a Button in stage of my alert for new game , and i want to use that to run my cod again at first. is there any method or something... It's my alert class class alart { public static void Game_over_alart(int dom) { dom = (dom - 9) * 10 ; Label sdom = new Label(Integer.toString(dom)); Stage window = new Stage(); window.setTitle("Game_Over"); Label gameOver = new Label("Game Over"); Label scor = new Label("SCORE : "); Label best = new Label("BEST : "); Text newgame = new Text("NEW GAME"); HBox hbox1 = new HBox(2, scor , sdom ); HBox hbox2 = new HBox(2, best); VBox vbox = new VBox(2, hbox1, hbox2); gameOver.setStyle("" + "-fx-alignment: top;" + "-fx-font-size: 40px;" + "-fx-font-style: italic;" + "-fx-font-weight: bold;" + "-fx-font-family: fantasy;" + "-fx-text-fill: lightgrey ;"); // + "-fx-background-color: gray"); DropShadow d = new DropShadow(5, Color.BLACK); ScaleTransition st=new ScaleTransition(Duration.millis(100),newgame); st.setToX(1.1); st.setToY(1.1); st.setFromX(1); st.setFromY(1); //st.setAutoReverse(true); // st.setCycleCount(Animation.INDEFINITE); gameOver.setEffect(d); BorderPane b = new BorderPane(); b.setTop(gameOver); b.setCenter(vbox); b.setBottom(newgame); gameOver.setAlignment(Pos.CENTER); Scene s = new Scene(b, 400, 200); window.setScene(s); window.show(); window.setResizable(false); newgame.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() { #Override public void handle(MouseEvent event) { } }); newgame.addEventHandler(MouseEvent.MOUSE_ENTERED, new EventHandler<MouseEvent>() { #Override public void handle(MouseEvent event1) { st.play(); } }); newgame.addEventHandler(MouseEvent.MOUSE_EXITED, new EventHandler<MouseEvent>() { #Override public void handle(MouseEvent event1) { st.setFromX(1.1); st.setFromY(1.1); st.setToX(1); st.setToY(1); } }); } } and it's the whole of my code /** * Created by Nadia on 12/31/2015. */ import javafx.animation.Animation; import javafx.animation.AnimationTimer; import javafx.animation.ScaleTransition; import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Label; import javafx.scene.effect.DropShadow; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.util.Duration; import sun.jvm.hotspot.debugger.cdbg.Sym; import javax.swing.text.StyledEditorKit; import java.util.ArrayList; public class Main_Snake extends Application{ Canvas canvas = new Canvas(399, 599); Rectangle round = new Rectangle(0 ,0 , 400 , 600 ); B_Part snake = new Snake(); B_Part apple = new Apple(); B_Part mane = new Mane(); #Override public void start(Stage primaryStage) throws Exception { round.setStroke(Color.BLACK); round.setFill(Color.WHITE); StackPane ss = new StackPane(); ss.getChildren().addAll(round, canvas); BorderPane b = new BorderPane(); b.setBottom(ss); Scene scene = new Scene(b, 410, 700); primaryStage.setScene(scene); primaryStage.setTitle ( "Snake" ); primaryStage.show(); primaryStage.setResizable(false); play(); } public void play() { AnimationTimer timer = new AnimationTimer() { private long lastUpdate = 0; #Override public void handle(long now) { if (now - lastUpdate >= 20_000_000) { // payin avordane sor# GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.WHITE); gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight()); try { for ( int i = 0 ; i < 5 ; i++) mane.Move(canvas.getScene()); } catch (Game_Over_Exception e) { }finally { mane.Drow(canvas); } try { apple.Move(canvas.getScene()); }catch (Exception e) { }finally { apple.Drow(canvas); } try { snake.Move(canvas.getScene()); } catch (Game_Over_Exception e) { stop(); alart.Game_over_alart(snake.X.size()); }finally { snake.Drow(canvas); // har bar mar rasm mishe bad az move va ye sib ba X,Y khodesh rasm mishe tu tabe move dar morede tabe Point hast } lastUpdate = now; // sor# } } }; timer.start(); } } abstract class B_Part { boolean goNorth = true, goSouth = false, goWest = false, goEast = false; /////////////////////////////////////////////////////// static int GM = 0 ; int Mx , My ; static ArrayList<Integer> Mane_x = new ArrayList<>(); static ArrayList<Integer> Mane_y = new ArrayList<>(); static int x, y ; // marbut be apple static int j = 0; // int gm_ov = 0; // vase game over shodan static ArrayList<Integer> X = new ArrayList<>(); static ArrayList<Integer> Y = new ArrayList<>(); static int Domx1 =400 , Domy1 =390 ; static int Domx2 =400, Domy2 =400 ; abstract public void Drow(Canvas canvas); abstract public void Move(Scene scene)throws Game_Over_Exception; void Point() { if (X.get(0) == x && Y.get(0) == y) j = 0; } void Game_Over() { for (int i = 1 ; i < X.size() ; i ++) { // inke mokhtasate sare mar tu mokhtasate tanesh hast ya na if (X.get(0).equals(X.get(i)) && Y.get(0).equals(Y.get(i))) { GM = 1; } } for (int i = 0 ; i < Mane_x.size() ; i ++) { // inke mokhtasate sare mar be mane hast ya na if (X.get(0).equals(Mane_x.get(i)) && Y.get(0).equals(Mane_y.get(i))) { GM = 1; } } } } class Apple extends B_Part { #Override public void Move(Scene scene) { if (j == 0) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme ) do { x = (int) ( Math.random() * 390 + 1 ); y = (int) ( Math.random() * 590 + 1 ); } while (X.indexOf(x) != -1 && Y.get(X.indexOf(x)) == y || x % 10 != 0 || y % 10 != 0); /* inja aval chek kardam tu araylist x hast ya na ag bud sharte aval ok hala sharte do ke tu Y ham mibinim tu hamun shomare khune y barabare y mast ag bud pas ina bar ham montabeghan va sharte dovom ham ok . 2 sharte akhar ham vase ine ke mare ma faghat mazrab haye 10 and pas ta vaghti in se shart bargharare jahayie ke ma nemikhaym va hey jaye dg mide */ j = 1; } } #Override public void Drow(Canvas canvas) { DropShadow dd = new DropShadow(20,Color.RED); GraphicsContext a = canvas.getGraphicsContext2D(); a.setFill(Color.RED); a.setEffect(dd); a.fillRect( x , y , 9 ,9); a.setEffect(null); } } class Snake extends B_Part { Snake() { //cunstructor X.add(400); Y.add(300); X.add(400); Y.add(310); X.add(400); Y.add(320); X.add(400); Y.add(330); X.add(400); Y.add(340); X.add(400); Y.add(350); X.add(400); Y.add(360); X.add(400); Y.add(370); X.add(400); Y.add(380); } #Override public void Drow(Canvas canvas) { GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.BLACK); // keshidane mar (body yeki ezafe tar az adade morabaA mide) for (int i = X.size() - 1; i >= 0; i--) { gc.fillRect(X.get(i), Y.get(i), 9, 9); gc.setStroke(Color.WHITE); } } #Override public void Move(Scene scene) throws Game_Over_Exception { scene.setOnKeyPressed(new EventHandler<KeyEvent>() { #Override public void handle(KeyEvent small) { switch (small.getText()) { case "W": if (!goSouth) { goNorth = true; goSouth = false; goWest = false; goEast = false; } break; case "w": if (!goSouth) { goNorth = true; goSouth = false; goWest = false; goEast = false; } break; case "S": if (!goNorth) { goSouth = true; goNorth = false; goWest = false; goEast = false; } break; case "s": if (!goNorth) { goSouth = true; goNorth = false; goWest = false; goEast = false; } break; case "A": if (!goEast) { goWest = true; goEast = false; goSouth = false; goNorth = false; } break; case "a": if (!goEast) { goWest = true; goEast = false; goSouth = false; goNorth = false; } break; case "D": if (!goWest) { goEast = true; goWest = false; goSouth = false; goNorth = false; } break; case "d": if (!goWest) { goEast = true; goWest = false; goSouth = false; goNorth = false; } break; } } }); /* scene.setOnKeyPressed(new EventHandler<KeyEvent>() { #Override public void handle(KeyEvent e) { switch (e.getCode()) { case UP: if (!goSouth) { goNorth = true; goSouth = false; goWest = false; goEast = false; } break; case DOWN: if (!goNorth) { goSouth = true; goNorth = false; goWest = false; goEast = false; } break; case LEFT: if (!goEast) { goWest = true; goEast = false; goSouth = false; goNorth = false; } break; case RIGHT: if (!goWest) { goEast = true; goWest = false; goSouth = false; goNorth = false; } break; } } }); */ Domx1 = X.get(X.size() - 1); Domy1 = Y.get(Y.size() - 1); for (int z = X.size() - 1; z > 0; z--) { X.remove(z); X.add(z, X.get(z - 1)); Y.remove(z); Y.add(z, Y.get(z - 1)); } if (goNorth) { Y.add(0, Y.get(0) - 10); Y.remove(1); } if (goSouth) { Y.add(0, Y.get(0) + 10); Y.remove(1); } if (goEast) { X.add(0, X.get(0) + 10); X.remove(1); } if (goWest) { X.add(0, X.get(0) - 10); X.remove(1); } Point(); // emtiaz gerefte if (j == 0) { X.add(Domx1); Y.add(Domy1); X.add(Domx2); Y.add(Domy2); Domx2 = Domx1; Domy2 = Domy1; System.out.println(); System.out.println("size : "+Mane_x.size() ); System.out.print(" clear : " ); Mane_x.clear(); Mane_y.clear(); System.out.println("size : "+Mane_x.size() ); } Game_Over(); if ( GM == 1 ) { throw new Game_Over_Exception("Game Over"); } if (X.get(0) > 390) { X.remove(0); X.add(0, 0); } if (X.get(0) < 0) { X.remove(0); X.add(0, 400); } if (Y.get(0) > 590) { Y.remove(0); Y.add(0, 0); } if (Y.get(0) < 0) { Y.remove(0); Y.add(0, 600); } } } class Mane extends B_Part{ #Override public void Drow(Canvas canvas) { GraphicsContext gc = canvas.getGraphicsContext2D(); for ( int i = 0 ; i < Mane_x.size() ; i++) { gc.setFill(Color.GRAY); gc.fillRect(Mane_x.get(i), Mane_y.get(i), 9, 9); } //System.out.println(Mane_x.get(i)+" "+Mane_y.get(i));} } #Override public void Move(Scene scene) { if (j == 0) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme ) do { Mx = (int) (Math.random() * 390 + 1); My = (int) (Math.random() * 590 + 1); } while (Mx == x && My == y || Mane_x.indexOf(Mx) != -1 && Mane_y.get(Mane_x.indexOf(Mx)) == My || X.indexOf(Mx) != -1 && Y.get(X.indexOf(Mx)) == My || Mx % 10 != 0 || My % 10 != 0 /* Mx == X.get(0) + 10 && My == Y.get(0) || // yeki joloye saresh nayofte (vaghti rast mire) Mx == X.get(0) - 10 && My == Y.get(0) || // ( vaghti chap mire) Mx == X.get(0) && My == Y.get(0) + 10 || // yek ta jolo tar az saresh nayofte vaghtti payi Mx == X.get(0) && My == Y.get(0) - 10*/); // vaghti bala //sharte chek kardane in ke har maneye random rooye mar ya maneye ghablia nayofte ( sib hamintor ) Mane_x.add(Mx); Mane_y.add(My); } } } class Game_Over_Exception extends Exception{ public Game_Over_Exception (String s){ super(s); } }
Hand over a restart method to the alert handler. You can do that directly or via interface, e. g.: public interface GameManager { public void restart(); } Your main class must implement that interface: public class Main_Snake extends Application implements GameManager { public void restart() { // TODO: reset playfield & restart game } public void play() { ... try { snake.Move(canvas.getScene()); } catch (Game_Over_Exception e) { stop(); alart.Game_over_alart(snake.X.size(), Main_Snake.this); } ... } } And in your alart class you invoke that method: class alart { public static void Game_over_alart(int dom, GameManager gameManager) { ... newgame.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() { #Override public void handle(MouseEvent event) { // TODO: close dialog // restart game gameManager.restart(); } }); ... } }
junit test for javafx sample login form
please help to test this code using junit #Override public void start(Stage primaryStage) { primaryStage.setTitle("JavaFX Welcome"); GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(25, 25, 25, 25)); Text scenetitle = new Text("Welcome"); scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20)); grid.add(scenetitle, 0, 0, 2, 1); Label userName = new Label("User Name:"); grid.add(userName, 0, 1); TextField userTextField = new TextField(); grid.add(userTextField, 1, 1); Label pw = new Label("Password:"); grid.add(pw, 0, 2); PasswordField pwBox = new PasswordField(); grid.add(pwBox, 1, 2); Label status = new Label(); status.setId( "status-label" ); Button btn = new Button("Sign in"); btn.setId("btn"); HBox hbBtn = new HBox(10); hbBtn.setAlignment(Pos.BOTTOM_RIGHT); hbBtn.getChildren().add(btn); grid.add(hbBtn, 1, 4); grid.add(status, 1, 8); final Text actiontarget = new Text(); grid.add(actiontarget, 1, 6); // ImageView imageView = new ImageView(new Image(getClass().getResourceAsStream("person.png"), 0, 65, true, true)); //grid.add(imageView, 0, 0,2,2); //btn.setOnAction( ( e ) -> status.setText( computeStatus() ) ); //private String computeStatus() { // return "Name: " + userTextField.getText() + ", Password: " + pwBox.getText(); //} btn.setOnAction(new EventHandler<ActionEvent>() { #Override public void handle(ActionEvent e) { actiontarget.setFill(Color.CORNFLOWERBLUE); actiontarget.setText("Name: " + userTextField.getText() + ", Password: " + pwBox.getText()); } }); Scene scene = new Scene(grid, 300, 275); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); }
The OnEndPage event and a table with a RowSpan
I added the creation of a table cone page header in OnEndPage. In table I a RowSpan that is not printed, while the rest is. table.WriteSelectedRows (0, -1, pageSize.GetLeft (25), pageSize.GetTop (10), cb); If I remove the RowSpan prints!
This is the code I use: public override void OnEndPage(PdfWriter writer, Document document) { if (document.PageNumber != 1) { if (report.repeatHead) //ripete l'intestazione del report su tutte le pagine di stampa { repeatHead(writer, document); } else { if (document.PageNumber == 2) //ripete l'intestazione del report solo sulla second pagina dopo la copertina { repeatHead(writer, document); } } } } public void repeatHead(PdfWriter writer, Document document) { //OnStartPage base.OnStartPage(writer, document); Rectangle pageSize = document.PageSize; PdfPTable table = new PdfPTable(2); //table.WidthPercentage = 100; table.TotalWidth = pageSize.Width - 50; table.DefaultCell.Border = Rectangle.NO_BORDER; //impostazione larghezza celle iTextSharp.text.Rectangle rect = PageSize.A4; float pageWidth = rect.Width; table.SetWidthPercentage(new float[] { (float).70 * pageWidth , (float).30 * pageWidth, }, rect); //Cella nome banca table.AddCell(CellTest(report.banca, 1, 2)); //Cella descrizione indagine table.AddCell(CellTest("Valore1", 0, 0)); //Cella data apertura table.AddCell(CellTest("Data apertura: " + DateTime.Now, 0, 0)); //Cella descrizione table.AddCell(CellTest("Descrizione", 0, 0)); //Cella data chiusura table.AddCell(CellTest("Data chiusura: " + DateTime.Now, 0, 0)); table.WriteSelectedRows(0, -1, pageSize.GetLeft(25), pageSize.GetTop(10), cb); } private PdfPCell CellTest(string value, int colSpan, int rowSpan) { iTextSharp.text.Font font = FontFactory.GetFont("Arial"); PdfPCell c = new PdfPCell(new Phrase(value, font)); c.BorderWidthLeft = 1f; c.BorderWidthTop = 1f; c.BorderWidthRight = 1f; c.BorderWidthBottom = 1f; if (rowSpan != 0) { c.Rowspan = rowSpan; } if (colSpan != 0) { c.Colspan = colSpan; } return c; } public override void OnCloseDocument(PdfWriter writer, Document document) { base.OnCloseDocument(writer, document); template.BeginText(); template.SetFontAndSize(bf, 8); template.SetTextMatrix(0, 0); template.ShowText("" + (writer.PageNumber - 1)); template.EndText(); }
the function display() does not exist
I keep getting the error "the function display() does not exist. I'm just trying to put my own image in instead of a pre drawn ellipse in processing. Here is my code: import processing.serial.*; import cc.arduino.*; import com.tinkerkit.*; Arduino arduino; //declare the button TKButton but; TKButton but1; { arduino = new Arduino(this, Arduino.list()[2], 57600); } PFont myFont; PImage ball1; int pScore; // don't touch em! int gameState; //0= pre game 1= in game 2= game over //setting up perimeter to contain ball character int width = 600; int height = 600; void setup() { size(width, height); smooth(); //myFont = loadFont("MyFutura.vlw"); //textFont(myFont); gameState = 0; ball1 = loadImage("ball.gif"); pScore = 0; } { but = new TKButton(arduino, TK.I0); but1 = new TKButton(arduino, TK.I1); } void draw() { background(0); if (gameState==0) { fill(255, 255, 255, 70); rect(-10, 30, 370, 70, 7); fill(255, 255, 255, 70); rect(-10, 120, 330, 50, 7); fill(255); textSize(60); text("Ball Game", 30, 85); textSize(40); text("Press B to Start", 30, 157); if (keyPressed && key == 'b') { gameState = 1; } } if (gameState == 2) { fill(255, 255, 255, 70); rect(-10, 30, 370, 70, 7); fill(255, 255, 255, 70); rect(-10, 120, 250, 50, 7); fill(255, 255, 255, 70); rect(-10, 190, 330, 50, 7); fill(255); textSize(50); text("Final Score:", 20, 85); text(pScore, 280, 85); textSize(30); text("Play Again?", 30, 157); textSize(30); text("Press R to Restart", 30, 225); if (keyPressed && key == 'r') { gameState = 0; setup(); } } ball1.display(); ball1.keyPressed(); } void display() { fill(255); noStroke(); } void reset() { ... } class ball1 { float x; float y; float speed; float r; //radius color c = color(255, 20, 245); ball1(float tempX, float tempY, float tempR) { x = tempX; y = tempY; r = tempR; speed = 0; } void change() { c = color(random(255), random(220), random(245)); } void display() { fill (c); noStroke(); ellipse(x, y, r, r); } //key commands //ball flies off page in response to key command void keyPressed() { if (key == CODED) { } if (but.read ()== TK.HIGH) { x = x+5; if (x >= width - 25) { x = width - 25; } println(but.read()); } else if (but1.read() == TK.HIGH) { x = x-5; if (x <= 25) { x = 25; } println(but1.read()); } } }
Your ball1 variable is of type PImage. The PImage class does not have a display() method. Maybe your ball1 variable should be inside the ball1 class? If so, rename your class to something sane like Ball (in other words, follow the standard naming conventions and don't use the same name for a class and variable). Then rename your ball1 variable to something sane like ballImage. Then inside your Ball class's display() function, call image(ballImage, x, y) or one of the other image() functions. Recommended reading: https://processing.org/reference/PImage.html https://processing.org/reference/image_.html