Swing高级UI之表格

 注意table的参数(Object[] [],Object[])就行了。

class WinTable extends JFrame implements FocusListener, java.awt.event.ActionListener{

	private Container con = this.getContentPane();
	
	private Object data[] [] = {{"孙悟空","88","92","0"},
			{"猪八戒","55","69","0"},
			{"唐僧","92","89","0"}
			
	};
	private Object title[] = { "姓名","英语成绩","数学成绩","总成绩" };

	private JButton button = new JButton("计算每人总成绩");
	private JTable table = new JTable(data,title);
	
	public WinTable() {
		this.setTitle("表格案例");
		this.setSize(500, 300);
		this.setLocation(500, 300);
		con.add(new JLabel("修改或输入数据后,需要回车确认"),BorderLayout.NORTH);
		con.add(button, BorderLayout.SOUTH);
		table.setRowHeight(30);
		table.setFont(new Font("宋体",Font.BOLD,20));
		table.getTableHeader().setFont(new Font("宋体",Font.BOLD,20));
		
		con.add(new JScrollPane(table), BorderLayout.CENTER);
		
		button.addActionListener(this);
		table.addFocusListener(this);
		
		this.setVisible(true);
		this.validate();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public void calculateTotal() {
		for(int i=0;i<data.length;i++) {
			double sum=0;
			boolean boo=true;
			for(int j=1;j<=2;j++) {
				sum=sum+Double.parseDouble(data[i][j].toString());
				table.repaint();
			}
		}
	}
	
	
	@Override
	public void focusGained(FocusEvent arg0) {
		// TODO Auto-generated method stub
		this.calculateTotal();
	}

	@Override
	public void focusLost(FocusEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onAction() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		this.calculateTotal();
	}
	
}

public class table {
	public static void main(String[] args) {
		new WinTable();
	}
  
}

效果显示:


猜你喜欢

转载自blog.csdn.net/qq_37334150/article/details/80289613