每当我再次点击按钮时,我想更新数量和价格,但它不起作用。我的代码中有什么问题吗?我尝试了一切。我正在创建一个简单的销售点系统,用户只需单击按钮即可添加菜单并自动进行计算。我为调节添加了增量。
你有什么想法吗?
package sampletable;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class SampleTable extends JFrame
{
Container con;
JPanel pane1,pane2;
JButton btn1;
JTable JT;
String[] columns = {"Menu","Price","Quantity"};
String[][] data = new String[0][0];
Object [] row1 = new Object[3];
DefaultTableModel model = new DefaultTableModel();
int price1=0;
int price1Mul;
int Clicks1=0;
public SampleTable()
{
con = getContentPane();
con.setLayout(new GridLayout(2,1));
pane1 = new JPanel();
btn1 = new JButton("Food 1");
btn1.addActionListener(new btnAction1());
pane1.add(btn1);
con.add(pane1);
model.setDataVector(data, columns);
JT = new JTable();
JT.setPreferredScrollableViewportSize(new Dimension(200,200));
JT.setFillsViewportHeight(true);
JT.setModel(model);
JScrollPane JPS = new JScrollPane(JT);
con.add(JPS);
pane2 = new JPanel();
con.add(pane2);
}
/*In here I want to change the value thats why I use incrementation so
that the next click it would increment and satisfy the other if.*/
public class btnAction1 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
price1 = 20;
price1Mul++;
if (Clicks1 == 0)
{
row1[0] ="Food1";
row1[1] =price1;
row1[2] =price1Mul;
model.addRow(row1);
int x = price1 * price1Mul;
price1 = x;
Clicks1++;
}
else if (Clicks1 == 1)
{
int addPrice = price1 * price1Mul;
row1[0] ="Food1";
row1[1] =addPrice;
row1[2] =price1Mul;
}
}
}
//Main Class
public static void main(String[] args)
{
SampleTable ST = new SampleTable();
ST.setTitle("Sample JTable");
ST.setSize(500,500);
ST.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ST.setVisible(true);
ST.setResizable(false);
}
}
答案 0 :(得分:0)
您需要将model.addRow(row1)
放在if / else
块之外,才能将该行添加到模型中,无论该按钮是否被点击。如果要更新上次添加的行,只需按removeRow(int row)
删除它,然后插入更新的行,如前所述。
public void actionPerformed(ActionEvent e) {
price1 = 20;
price1Mul++;
if (Clicks1 == 0) {
row1[0] = "Food1";
row1[1] = price1;
row1[2] = price1Mul;
int x = price1 * price1Mul;
price1 = x;
Clicks1++;
} else if (Clicks1 == 1) {
int lasRowAdded = model.getRowCount() - 1;
model.removeRow(lastRowAdded);
int addPrice = price1 * price1Mul;
row1[0] = "Food1";
row1[1] = addPrice;
row1[2] = price1Mul;
}
model.addRow(row1);
}