在收到建议后,我重写了我的第一个应用程序,不要像以前那样使用静态,我滥用了固有性。但现在我的应用程序已经不起作用了。
我不明白为什么不。我想我装错了东西,但看不清是什么东西。我在stackoverflow和其他网站上读到了instagriation,但我仍然不完全理解
我是java新手,不会写那么长时间的代码。我在Netbeans中构建了一个布局。每次你点击"添加"按钮,一个食品杂货就会显示在文本区域。我的旧代码(所有内容都是静态的)运行良好。
我偶尔会收到一个"线程中的异常"AWT-EventQueue-0"java.lang.ClassCastException:java.lang.Boolean无法转换为java.AWT.Color"错误。但它并不是总是出现。如果我没有设置错误,然后点击"添加"按钮,就会注意到发生了什么。
有人能告诉我我做错了什么吗?
任何关于我做错了什么或如何调试的建议都将不胜感激。
GroceryList2ActionListener.java
package javaclasses;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import grocerylist2jframe.GroceryList2JFrame;
// this is the ActionListener for adding a grocery item
public class GroceryList2ActionListener {
public void getButtonActionAddGroceryItem() {
GroceryList2JFrame jFrameAdd = new GroceryList2JFrame();
jFrameAdd.buttonAddGroceryItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String groceryItem = jFrameAdd.jTextField1GroceryItem.getText();
String quantity = jFrameAdd.jTextField2Quantity.getText();
String unit = jFrameAdd.jComboBox1Unit.getSelectedItem().toString();
jFrameAdd.jTextArea1.append(groceryItem + " " + quantity + " " + unit + "n" );
}
});
}
// this is the ActionListener for removing a grocery item
public void getButtonActionRemoveGroceryItem() {
GroceryList2JFrame jFrameRemove = new GroceryList2JFrame();
jFrameRemove.buttonRemoveGroceryItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jFrameRemove.jTextArea1.setText(jFrameRemove.jTextArea1.getText().replaceAll(jFrameRemove.jTextArea1.getSelectedText(),""));
}
});
}
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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GroceryList2JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new GroceryList2JFrame().setVisible(true);
}
});
GroceryList2ActionListener action = new GroceryList2ActionListener();
action.getButtonActionAddGroceryItem(); // I think I call here the "addItem" and "removeItem" on button click.
action.getButtonActionRemoveGroceryItem();
}
}
这是我写的ActionListener。接下来是我在Netbeans中制作的应用程序的布局。我不是自己写的,我用了一个JForm。
GroceryList2JFrame.java
package grocerylist2jframe;
public class GroceryList2JFrame extends javax.swing.JFrame {
/**
* Creates new form GroceryList2JFrame
*/
public GroceryList2JFrame() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jComboBox1Unit = new javax.swing.JComboBox();
jTextField2Quantity = new javax.swing.JTextField();
jTextField1GroceryItem = new javax.swing.JTextField();
jPanel3 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setSize(new java.awt.Dimension(0, 0));
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Grocerylist2", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Georgia", 3, 18))); // NOI18N
jPanel1.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Grocerylist Input", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Georgia", 3, 14))); // NOI18N
jLabel2.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jLabel2.setText("Choose a Quantity");
jLabel1.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jLabel1.setText("Add a Grocery Item");
jLabel3.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jLabel3.setText("Choose A Unit");
jComboBox1Unit.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jComboBox1Unit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Kilogram", "Gram", "Liter", "Millilitre", "Piece(s)" }));
jComboBox1Unit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1UnitActionPerformed(evt);
}
});
jTextField2Quantity.setFont(new java.awt.Font("Georgia", 0, 9)); // NOI18N
jTextField2Quantity.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2QuantityActionPerformed(evt);
}
});
jTextField1GroceryItem.setFont(new java.awt.Font("Georgia", 0, 9)); // NOI18N
jTextField1GroceryItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1GroceryItemActionPerformed(evt);
}
});
buttonAddGroceryItem.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
buttonAddGroceryItem.setText("Add Grocery Item To Grocerylist");
buttonAddGroceryItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonAddGroceryItemActionPerformed(evt);
}
});
buttonRemoveGroceryItem.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
buttonRemoveGroceryItem.setText("Remove Grocery Item From Gocerylist");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1GroceryItem)
.addComponent(jTextField2Quantity)
.addComponent(jComboBox1Unit, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(buttonAddGroceryItem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonRemoveGroceryItem, javax.swing.GroupLayout.DEFAULT_SIZE, 338, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1GroceryItem, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField2Quantity, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox1Unit, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(86, 86, 86)
.addComponent(buttonAddGroceryItem, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(buttonRemoveGroceryItem, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(217, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Grocerylist2 View", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Georgia", 1, 14))); // NOI18N
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE)
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
);
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()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, 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(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void buttonAddGroceryItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField1GroceryItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField2QuantityActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jComboBox1UnitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify
public final javax.swing.JButton buttonAddGroceryItem = new javax.swing.JButton();
public final javax.swing.JButton buttonRemoveGroceryItem = new javax.swing.JButton();
public javax.swing.JComboBox jComboBox1Unit;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
public javax.swing.JTextArea jTextArea1;
public javax.swing.JTextField jTextField1GroceryItem;
public javax.swing.JTextField jTextField2Quantity;
// End of variables declaration
}
我认为您已经使这个程序过于复杂了。其他SO用户是正确的,除非绝对合理,否则应该避免对方法和变量使用static。您应该阅读一些关于JavaSwing事件处理的内容,特别是关于如何使用ActionListener
的内容。
在您的案例中,您不需要单独的类(GroceryList2ActionListener
),因为NetBeans正在为您的(通常)创建事件处理方法。GroceryList2JFrame
已经有了一个处理添加杂货的方法。由于某些原因,当您添加删除按钮时,在构建表单时没有选择添加动作侦听器。
此外,有一个带有main的"driver"类来实例化帧、设置look-n-feel等也是有意义的。
1) 您可以移除/删除GroceryList2ActionListener
类—不再需要它。
2) 将此类添加到与GroceryList2JFrame
类相同的包中。这是现在具有main()方法的驱动程序类。
package grocerylist2jframe;
public class GroceryList {
public static void main(String args[]) {
System.out.println("Running the GroceryList program...");
/* 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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GroceryList2JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
GroceryList2JFrame frame = new GroceryList2JFrame();
frame.setVisible(true);
}
});
}
}
3) 当使用NetBeans构建表单时,它已经添加了一个事件处理程序方法,并为add按钮注册了它,但为remove按钮省略了它。如果你环顾GroceryList2JFrame
类的第70行,你会看到方法调用buttonAddGroceryItem.addActionListener()...
,我添加了一个类似的块来为buttonRemoveGroceryItem
注册一个新方法。将此代码块放在`buttonAddGroceryItem.addActionListener()code:下面
buttonRemoveGroceryItem.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
buttonRemoveGroceryItem.setText("Remove Grocery Item From Gocerylist");
buttonRemoveGroceryItem.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
buttonRemoveGroceryItemActionPerformed(evt);
}
});
最后,您将找到由NetBeans创建的现有方法GroceryList2JFrame.buttonAddGroceryItemActionPerformed()
。我已经填写了方法,复制了GroceryList2ActionLIstener
的内容,还为buttonRemoveGroceryItemActionPerformed()
添加了一个方法,两者如下所示:
private void buttonAddGroceryItemActionPerformed(java.awt.event.ActionEvent evt) {
String groceryItem = jTextField1GroceryItem.getText();
String quantity = jTextField2Quantity.getText();
String unit = jComboBox1Unit.getSelectedItem().toString();
jTextArea1.append(groceryItem + " " + quantity + " " + unit + "n" );
}
private void buttonRemoveGroceryItemActionPerformed(java.awt.event.ActionEvent evt){
String choice = jTextArea1.getSelectedText();
try {
jTextArea1.setText(jTextArea1.getText().replaceAll(choice, ""));
}
catch(Exception ex){
JOptionPane.showMessageDialog(this, "Please select a valid item from the grocery list before clicking to remove.",
"Invalid Item selected for removal", JOptionPane.ERROR_MESSAGE);
}
}
一旦您进行了这些小的更改,您的程序应该可以按预期工作。祝你好运